hull = cv2.convexHull(cnt,returnPoints = False)
defects = cv2.convexityDefects(cnt,hull)
注意:如果要查找凸缺陷,在使用函数 cv2.convexHull
找凸包时,
参数returnPoints
一定要是 False
。
它会返回一个数组,其中每一行包含的值是 [起点,终点,最远的点,到最远点的近似距离]。 可以在一张图上显示它。将起点和终点用一条绿线连接, 在最远点画一个圆圈,要记住的是返回结果的前三个值是轮廓点的索引。 所以还要到轮廓点中去找它们。
import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('star.jpg')
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)
plt.imshow(img)
#cv2.imshow('img',img)
#cv2.waitKey(0)
#cv2.destroyAllWindows()
<matplotlib.image.AxesImage at 0x7f3da0f8bd50>
dist = cv2.pointPolygonTest(cnt,(50,50),True)
import cv2
import numpy as np
img1 = cv2.imread('messimg.png',0)
img2 = cv2.imread('bridnest.jpg',0)
ret, thresh = cv2.threshold(img1, 127, 255,0)
ret, thresh2 = cv2.threshold(img2, 127, 255,0)
contours,hierarchy = cv2.findContours(thresh,2,1)
cnt1 = contours[0]
contours,hierarchy = cv2.findContours(thresh2,2,1)
cnt2 = contours[0]
ret = cv2.matchShapes(cnt1,cnt2,1,0.0)
print (ret)
0.0
得到的结果是:
A 与自己匹配 0.0
A 与 B 匹配 0.001946
A 与 C 匹配 0.326911
及时发生了旋转对匹配的结果影响也不是非常大。 注意:Hu 矩是归一化中心矩的线性组合,之所以这样做是为了能够获取代表图像的某个特征的矩函数, 这些矩函数对某些变化如缩放,旋转,镜像映射(除了 h1)具有不变形。此段摘自《学习 OpenCV》中文版。
练习
创建一个小程序,可以将图片上的点绘制成不同的颜色,颜色是根据这个 点到轮廓的距离来决定的。要使用的函数:
cv2.pointPolygonTest()
。使用函数
cv2.matchShapes()
匹配带有字母或者数字的图片。