%matplotlib inline
import matplotlib.pyplot as plt
import cv2
import numpy as np
img = cv2.imread('/data/cvdata/star.png', 0)
ret,thresh = cv2.threshold(img,127,255,0)
contours,hierarchy = cv2.findContours(thresh, 1, 2)
for cnt in contours:
area = cv2.contourArea(cnt)
print(area)
4.0 4.0 2.0 2.0 8.5 2.0 2.0 2.0 2.0 2.0 2.0 2.0 2.0 2.0 2.0 2.0 2.0 2.0 2.0 2.0 2.0 76185.5
hull = cv2.convexHull(cnt,returnPoints = False)
defects = cv2.convexityDefects(cnt,hull)
注意:
在寻找凸包时必须设置 returnPoints = False
,这样才能计算凸性缺陷。
该函数返回一个数组,其中每行包含以下值:
[ start point, end point, farthest point, approximate distance to farthest point\]
。
我们可以通过图像直观展示:
绘制连接起始点和结束点的线段,
在最远点位置绘制圆形。
特别需要注意的是:
返回的前三个值是轮廓点集 cnt
的索引值,因此需要从 cnt
中获取对应的坐标值。
import cv2
import numpy as np
img = cv2.imread('/data/cvdata/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)
for cnt in contours:
area = cv2.contourArea(cnt)
print(area)
76188.5 4.0 4.0 2.0 2.0 8.5 2.0 2.0 2.0 2.0 2.0 2.0 2.0 2.0 2.0 2.0 2.0 2.0
hull = cv2.convexHull(cnt,returnPoints = False)
hull
array([[0], [1], [2], [3]], dtype=int32)
defects = cv2.convexityDefects(cnt,hull)
defects
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()
dist = cv2.pointPolygonTest(cnt,(50,50),True)
import cv2
import numpy as np
img1 = cv2.imread('/data/cvdata/star.jpg',0)
img2 = cv2.imread('/data/cvdata/star.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不变矩(Hu-Moments)
是由七个具有平移、旋转和尺度不变性的矩组成的特征量,其中第七个矩还具备倾斜不变性。
可通过 cv2.HuMoments()
函数计算这些特征值。
练习
查看
cv2.pointPolygonTest()
的文档,可以找到一个红色和蓝色的漂亮图像。 它表示从所有像素到其上的白色曲线的距离。根据距离,曲线内的所有像素都是蓝色的。 同样,外部点为红色。轮廓边缘标记为白色。所以问题很简单。编写一段代码来创建这样的距离表示。使用
cv2.matchShapes()
比较数字或字母的图像。(这将是迈向OCR的简单一步)