图像凸性检测函数convexityDefects在Python2.7下使用opencv3.0的问题

最近在学习Python下的OpenCV,在图像的凸性检测中,发现opencv3.0下的convexityDefects函数对图像的凸性缺陷处理有错误。不知道是opencv3.0的版本问题还是我个人的错误代码。

例如使用的Python版本是2.7.6,使用的OpenCV版本是3.0,以下是图像凸性检测代码:

import cv2
import numpy as np

img = cv2.imread('star2.png')
img_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(img_gray,127,255,0)
img_c,contours,hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
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])
print start,end,far,d
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()


结果显示,某处缺陷最大值定位错误,如图:

图像凸性检测函数convexityDefects在Python2.7下使用opencv3.0的问题_第1张图片


而如果使用OpenCV2.4.13版本,以下是图像凸性检测代码:

import cv2
import numpy as np

img = cv2.imread('star2.png')
img_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(img_gray,127,255,0)
contours,hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
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])
print start,end,far,d
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()


结果显示,图像的凸性检测是正确的,如图所示:



总结:

出现这样的问题是因为OpenCV3.0版本还不够稳定还是我的编程错误呢?不知道各位有没有遇到类似的问题,特此提出来,希望大家讨论一下!

你可能感兴趣的:(图像处理,python,opencv,图像凸性检测)