在openCV2 Python中绘制convexHull
所以我试图从python中的轮廓绘制convexHull,但是当我打印图像时它没有改变。
So I am trying to draw the convexHull from a contour in python, however when i print the image it is not changing.
roi=mask[y:y+h,x:x+w]
roi = cv2.fastNlMeansDenoisingColored(roi,None,15,15,7,21)
hull = cv2.convexHull(cnt)
cv2.drawContours(roi,[hull],0,(147,0,255),2)
cv2.imshow(str(i),roi)
blank_image[y:y+h,x:x+w] = roi
然而,显示的图像完全相同如果我没有包含代码。我在网上看了,但似乎找不到答案。
以下是一个示例图片:
However, the images that show are the exact same if I did not include the code. I looked online, but cannot seem to find the answer. Here is a sample Image:
我使用了以下代码为你给出的图像获得凸包:
I used the following code to obtain convex hull for the image given by you:
import cv2
import numpy as np
img = cv2.imread('2.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)
print len(contours)
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)
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
由于轮廓基于图像中的白色区域,因此我可以通过更改获得两个 类型 轮廓代码中的第5行。
Since contours are based on the white region in an image, I was able to obtain two types of contours by altering line 5 in the code.
案例1:
CASE 1 :
我能够获得这个:
案例2:
现在当我更改代码段中的第五行行时,我得到了这样的结果:当我反转二进制文件时image ret,thresh = cv2.threshold(img_gray,127,255,1)
CASE 2 :
Now when I change the fifth line in the code segment, I obtain this: when I invert the binary image ret, thresh = cv2.threshold(img_gray, 127, 255, 1)
这是因为在案例1 轮廓为f基于此图像
This is because in case 1 the contour was found based on this image
现在在案例2 中,基于此图片找到了轮廓
Now in case 2 the contour was found based on this image
如您所见,基于二进制图像中的白色区域找到轮廓。
As you can see, contours are found based on the white region in the binary image.
希望这会有所帮助。
我使用了此链接,用于获取代码和参考。
I used THIS LINK for obtaining the code and for reference.