在python中绘制一条直到掩码OpenCV的边缘

时间:2017-11-11 12:19:03

标签: python opencv image-processing image-masking

提供如下图像的图像

MNIST CNN example

我可以很容易地创建一个这样的面具。蒙面图像看起来像这样。

Blue circle on a white back ground

我使用以下代码来获取掩码。

#Convert to HSV
HSV = cv2.cvtColor(I, cv2.COLOR_BGR2HSV)
#Create a lower and upper range
HSVlower = np.array([0,0,0])
HSVupper = np.array([134,205,255])

#deine a mask
mask = cv2.inRange(HSV , HSVlower , HSVupper)
cv2.imshow("MASK" , mask)
cv2.waitKey(0)

然后我可以使用轮廓和时刻识别蒙面区域的中心。 带有中心标记的图像是:

Masked image

这是我用来获取种子点的代码。

#find biggest cont
contours,hierarchy = 
cv2.findContours(mask,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
#find largest contour in mask, use to compute minEnCircle
c = max(contours, key = cv2.contourArea)
cv2.drawContours(I , c , -1,(255,255,255) , 3 )


#get center of detected circle
moments = cv2.moments(c)
cx = int(moments['m10']/moments['m00'])
cy = int(moments['m01']/moments['m00'])

这是我的问题所在。我想在N / 360度处绘制N条线,从该图像的中心直到掩模从黑色到白色的点。我一直无法做到这一点。

我已将此问题简化为单行并且图像更简单且行为相同。 我一次从中心移出一个像素,检查掩模图像中该像素的值。如果值很暗,我画一条线并移动下一个像素。重复此过程,直到找到不暗的像素。

我使用上面的逻辑实现了以下结果。

center point identified and drawn on result image

如图所示,该线不会停在圆圈边缘的预期位置。

这是我用来绘制线条并检查像素值的代码。

localIndex = 0 
##move from the center until we hit white 
while mask[cx,cy + localIndex] < 20:
    cv2.line(img=I, pt1=(cx, cy), pt2=(cx,cy + localIndex), color=(0, 255, 255), 
thickness=3)
    localIndex =  localIndex + 1
    print  mask[cx, cy + localIndex]

cv2.imshow("linedImage" , I)
cv2.waitKey(0)

编辑:这是我正在使用的照片的链接。 Line does not stop where expected

编辑:在I循环中打印出像素值我可以看到它们都是0,直到跳到130.这让我觉得掩模和原始图像之间存在比例问题?此外,该线不仅仅需要掩模改变的点。绘制的线用于可视化

1 个答案:

答案 0 :(得分:1)

正确替换while循环条件。将其更改为 -

FormHelper::error()

enter image description here