"""
@File : 轮廓_更多函数.py
@Author : jiaming
@Modify Time: 2020/2/5 16:26
@Contact : https://blog.csdn.net/weixin_39541632
@Version : 1.0
@Desciption : 凸缺陷
找到某一点到一个多边形的最短距离
不同形状的匹配
"""
import os
import sys
import numpy as np
import cv2
import pprint
from matplotlib import pyplot as plt
rawPath = os.path.abspath(__file__)
currentFile = os.path.basename(sys.argv[0])
dataPath = rawPath[:rawPath.find(currentFile)] + r'static\\'
凸缺陷
"""
对象上的任何凹陷都被称为凸缺陷。
OpenCV 中有一段函数 cv2.convexityDefect() 可以帮助我们找到凸缺陷。
hull = cv2.convexHull(cnt, returnPoints=False)
defects = cv2.convexityDefect(cnt, hull) 返回一个数组,其中每一行包含的值是[
起点,终点,最远的点,到最远点的近似距离]
"""
img = cv2.imread(dataPath + 'star.png')
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(img_gray, 127, 255, 0)
contours, hierarchy = cv2.findContours(thresh, 2, 1)
cnt = contours[0]
hull = cv2.convexHull(cnt, returnPoints=False)
defects = cv2.convexityDefects(cnt, hull)
for i in range(defects.shape[0]):
s, e, f, d = defects[i, 0]
start = tuple(cnt[s][0])
end = tuple(cnt[e][0])
far = tuple(cnt[f][0])
cv2.line(img, start, end, [0, 255, 0], 2)
cv2.circle(img, far, 5, [0, 0, 255], -1)
cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Point Polygon Test
"""
Point Polygon Test
求解图像中的一个点到一个对象轮廓的最短距离。如果点在轮廓外部,返回值为负。如果在轮廓上,
返回值为 0, 如果在轮廓内部,返回值为正。
dist = cv2.pointPolygonTest(cnt, (50, 50), True)
此函数第三个参数是 measureDist,如果设置为 True,就会计算最短距离,如果是 False,只会判断这个点
与轮廓之间的位置关系,返回(+1, -1, 0)
"""
形状匹配
"""
形状匹配
比较两个轮廓的近似程度。返回值越小,匹配效果越好。
根据 Hu 矩来计算的。
"""
img1 = cv2.imread(dataPath+'A.png', 0)
img2 = cv2.imread(dataPath+'B.png', 0)
img3 = cv2.imread(dataPath+'C.png', 0)
ret, thresh = cv2.threshold(img1, 127, 255, 0)
ret, thresh2 = cv2.threshold(img2, 127, 255, 0)
ret, thresh3 = cv2.threshold(img3, 127, 255, 0)
contours, hierarchy = cv2.findContours(thresh, 2, 1)
cnt1 = contours[0]
contours, hierarchy = cv2.findContours(thresh2, 2, 1)
cnt2 = contours[0]
contours, hierarchy = cv2.findContours(thresh3, 2, 1)
cnt3 = contours[0]
ret = cv2.matchShapes(cnt1, cnt1, 1, 0.0)
print('A', ret)
ret = cv2.matchShapes(cnt1, cnt2, 1, 0.0)
print('B', ret)
ret = cv2.matchShapes(cnt1, cnt3, 1, 0.0)
print('C', ret)
A 0.0
B 1.7976931348623157e+308
C 1.7976931348623157e+308