OpenCV学习笔记(15)——更多的轮廓函数

  • 凸缺陷,以及如何找到凸缺陷
  • 找某一点到一个多边形的最短距离 
  • 不同形状的匹配

1.凸缺陷

  前面已经设计了轮廓的凸包和凸性缺陷的概念。OpenCV中有一个函数cv2.convexityDefect()可以帮助我们找到凸缺陷:  

hull = cv2.convexHull(cnt,returnPoints=False)#这里必须是False

defect = cv2.convexityDefects(cnt,hull)
  

它会返回一个数组,每一行的值为[起点,终点,最远的点,到最远点的近似距离]。我们可以在一张图上显示它。我们将起点和终点用一天绿线连接,在最远点画一个圆圈。记住返回的前三个值是点在轮廓中的索引,所以要到轮廓中去找到它们:

# -*- coding:utf-8 -*-

import numpy as np
import cv2
from matplotlib import pyplot as plt

im = cv2.imread('10.png')
img = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)#用这个方式转换的原因是最后输出时希望能看到彩色的的轮廓图
ret,thresh = cv2.threshold(img,127,255,0)

img,contours,hierarchy = cv2.findContours(thresh,1,2)
cnt = contours[0]

hull = cv2.convexHull(cnt,returnPoints=False)#这里必须是False
defect = cv2.convexityDefects(cnt,hull)
#它的输出包含很多项,可以尝试输出一下便可以知道该list的排列格式

for i in range(defect.shape[0]):
s,e,f,d = defect[i,0]
start = tuple(cnt[s][0])
end = tuple(cnt[e][0])
far = tuple(cnt[f][0])
cv2.line(im,start,end,[0,255,0],2)
cv2.circle(im,far,5,[0,0,255],-1)

cv2.imshow('img',im)
cv2.waitKey(0)

2.Point Polygon Test

  求解图像中的一个点到一个对象的轮廓的最短距离。如果点在轮廓外部,返回值为负。如果在轮廓上,返回值为0,。如果在轮廓外部,返回值为正。例子如下

   dist = cv2.pointPolygonTest(cnt,(50,50),True)

  其中第三个参数是measureDist。如果设为True,会返回最短距离;如果设为False,则只会判断这个点和轮廓之间的位置关系(返回+1,-1,0).

  如果实际运转中不需要知道最短距离,建议设为False,这样可以使速度提升2到3倍。

3.形状匹配

  cv2.matchShape()可以帮我们比较两个形状或轮廓的相似度。如果返回值越小,则匹配越好。它是根据Hull矩来确定的。

  # -*- coding:utf-8 -*-

import numpy as np
import cv2
from matplotlib import pyplot as plt

im = cv2.imread('10.png')
im2 = cv2.imread('11.png')
img = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)#用这个方式转换的原因是最后输出时希望能看到彩色的的轮廓图
img2 = cv2.cvtColor(im2,cv2.COLOR_BGR2GRAY)

ret,thresh = cv2.threshold(img,127,255,0)
ret,thresh2 = cv2.threshold(img2,127,255,0)

img,contours,hierarchy = cv2.findContours(thresh,1,2)
cnt = contours[0]
img2,contours,hierarchy = cv2.findContours(thresh2,1,2)
cnt2 = contours[0]

ret = cv2.matchShapes(cnt,cnt2,1,0.0)#后面的两个参数有啥用暂时不知道
print(ret)

根据测试,该匹配对于某些变化如缩放,旋转,镜像映射都具有较好的匹配效果

  

猜你喜欢

转载自www.cnblogs.com/zodiac7/p/9289732.html