1. 程式人生 > >影象凸性檢測函式convexityDefects在Python2.7下使用opencv3.0的問題

影象凸性檢測函式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()

結果顯示,某處缺陷最大值定位錯誤,如圖:



而如果使用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版本還不夠穩定還是我的程式設計錯誤呢?不知道各位有沒有遇到類似的問題,特此提出來,希望大家討論一下!