在非凸壳中寻找最大内接圆。

3
“非凸包”是指像这样的东西 enter image description here 图像的黑色区域(如果这不是“非凸包”,请见谅,我没有更好的词来描述它)。
我想要的是在黑色部分内的最大内切圆,就像下面图片中的红圆一样。 enter image description here 换句话说,我想知道空闲空间中的圆。这在使用opencv时是否可能?当我尝试使用以下代码获取圆时:
dist_map = cv2.distanceTransform(src_mask, cv2.DIST_L2, cv2.DIST_MASK_PRECISE)
_, radius, _, center = cv2.minMaxLoc(dist_map)
result = cv2.cvtColor(src_mask, cv2.COLOR_GRAY2BGR)
cv2.circle(result, tuple(center), int(radius), (0, 0, 255), 2, cv2.LINE_8, 0)

我得到了这个代替品。 enter image description here 你可以看到,圆圈超出了边界。 我很乐意听取任何建议和指针。谢谢! 编辑: 我添加了一个最小的示例来重现此问题。以下是脚本和结果。
import cv2
import numpy as np


##########
# create mask
# 0 if background, 255 if foreground
##########
src_mask = np.zeros((281, 500))
src_mask[100:170, 200:400] = 255
src_mask[127:143, 150:440] = 255
src_mask[213: 244, 30:59] = 255
src_mask[239: 279, 360:460] = 255
src_mask = src_mask.astype("uint8")
result = cv2.cvtColor(src_mask, cv2.COLOR_GRAY2BGR)
cv2.imwrite("mask.png", result)

##########
# draw contours
# the reason for 255-src_mask is that I want to have a circle in black portion instead of white portion 
##########
dist_map = cv2.distanceTransform(255 - src_mask, cv2.DIST_L2, cv2.DIST_MASK_PRECISE)
contours, _ = cv2.findContours(255 - src_mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[-2:]
result = cv2.cvtColor(src_mask, cv2.COLOR_GRAY2BGR)
cv2.drawContours(result, contours, -1, (255, 0, 0))
cv2.imwrite('contour.png', result)

##########
# circle
##########
dist_map = cv2.distanceTransform(255 - src_mask, cv2.DIST_L2, cv2.DIST_MASK_PRECISE)
_, radius, _, center = cv2.minMaxLoc(dist_map)
result = cv2.cvtColor(src_mask, cv2.COLOR_GRAY2BGR)
cv2.circle(result, tuple(center), int(radius), (0, 0, 255), 2, cv2.LINE_8, 0)
cv2.imwrite('circle.png', result)

输出结果为输入图像描述。同样,圆形超出了边界。

2个回答

4

这个可以做到奇迹般的效果。同时也要遮掩您的帧边界,例如:

src_mask[:, 0 ] = 255
src_mask[:, -1 ] = 255
src_mask[0, : ] = 255
src_mask[-1, : ] = 255

那样计算出的距离将考虑到框架的边界。(如果需要掩码,请在更改之前复制它)
我用你的示例得到了这个结果: enter image description here

我看到了。设置边界成功了!!谢谢! - dragon_and_dracula
With pleasure :) - matanj

0

出现这种情况有以下几种情况:

情况1: 变量center设置错误;-;

情况2: 由于cv2坐标(0,0)是屏幕左上角,因此如果中心点正确,则确保您已将cv2屏幕设置为您的屏幕大小,否则会发生这种情况


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接