python - 在 python 中画一条线直到掩码 OpenCV 的边缘

标签 python opencv image-processing image-masking

给出如下图这样的图片

Blue circle on a white back ground

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

Masked image

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

#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)

然后我可以使用轮廓和力矩来识别 mask 区域的中心。 标记中心的图像是这样的:

center point identified and drawn on result 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 条线,从该图像的中心到蒙版从黑色到白色的点。我一直无法做到这一点。

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

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

Line does not stop where expected

正如所见,这条线并没有在我期望的圆圈边缘停止。

这是我用来画线和检查像素值的代码。

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)

编辑:这是我正在使用的照片的链接。 https://vignette.wikia.nocookie.net/uncyclopedia/images/b/bc/Trick110.png/revision/latest?cb=20170408115814

编辑:在我循环时打印出像素值,我可以看到它们在跳转到 130 之前都是 0。这让我觉得蒙版和原始图像之间存在比例问题?此外,仅在掩码更改的位置不需要该线。画线是为了可视化

最佳答案

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

while (mask[cx,cy + localIndex] ==0)

enter image description here

关于python - 在 python 中画一条线直到掩码 OpenCV 的边缘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47237797/

相关文章:

python - Numpy 掩码数组修改

python - 使用 clint 进度条显示 urllib.urlretrieve() 的状态

python - 如何计算android相机捕获的图像中物体的深度

image - MATLAB 中的部分卷积

python - 如何在 python 中将图像转换为 16 位 zip (deflate) 压缩的 TIF?

python - python字符串索引访问的时间复杂度?

python - MyClass(k=random.randint(1,7) == 1) 是什么意思?

c++ - Blob 噪声生成

python - 使用带有掩码的 calcHist 时出错

RotatedRect 顶点的 OpenCV 顺序