python - 如何在 opencv 2.4.11 python 中调整轮廓大小? (目标 : Object extraction)

标签 python opencv mask contour

我是 opencv 的 super 新手,请原谅我的无知......

基本上:我的图像中有一个感兴趣的对象。我想提取它。

我的问题来自缩小原始图像以方便处理。我在较小的图像上找到了物体的轮廓。我真正想做的是使用有关该轮廓的信息从原始全尺寸图像中提取对象。

我真的只能想到两种方法来做到这一点,但我不知道哪一种在 opencv 中真正有意义:

  1. 调整轮廓的大小。然后在原图上画出来。
  2. (我正在使用的那个,但没有成功...)使用轮廓创建 mask 。调整蒙版的大小。然后将蒙版添加到原始图像。

我用的是2号,但我觉得 mask 有问题。调整大小,它不再包含轮廓。

以下是我当前代码的重要部分:

image = cv2.imread(path)
orig = image.copy()
...

#resize the image
image = cv2.resize(image, dim, interpolation = cv2.INTER_AREA)
....

#convert to gray scale
...

#get contour
(cnts, _) = cv2.findContours(edged.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
...
screenCnt = cv2.approxPolyDP(c, 0.01 * peri, True) #<--the contour
...

#create the mask
mask = np.ones(image.shape,np.uint8)*255
cv2.drawContours(mask,[screenCnt],0,(0,0,0),-1)
cv2.imshow("Small mask",mask) #<--- looks good
print(mask.shape) #<---returns a 3 element tuple
cv2.waitKey(0)

#now resize the mask
mask_big = cv2.resize(mask,(0,0),fx=ratio,fy=300)
cv2.imshow("Big mask",mask_big) #<--- ends up big, but all white (no contour)
cv2.waitKey(0)

我一直在网上搜索,但运气不佳,但我认为我在这里遗漏了一些基本的东西。 非常感谢所有回答者!

最佳答案

如我所见,这是一个很老的问题。但是,我有同样的问题,无法通过代码示例快速找到答案。这是示例(对于 opencv 3.4)

_, contours, _ = cv2.findContours(mask.astype(np.uint8), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)

coef_y = img_orig.shape[0] / img_resized.shape[0]
coef_x = img_orig.shape[1] / img_resized.shape[1]

for contour in contours:
    contour[:, :, 0] = contour[:, :, 0] * coef_x
    contour[:, :, 1] = contour[:, :,  1] * coef_y

    cv2.drawContours(img_orig, contour, -1, (0, 255, 0), 2)

关于python - 如何在 opencv 2.4.11 python 中调整轮廓大小? (目标 : Object extraction),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31644899/

相关文章:

python - python 消除面积比小于阈值的连接像素数

python - Azure Functions Blob 部署

python - 程序的输出与公式不匹配(概率问题)

android - 对 `cv::fastFree(void*)' 的 undefined reference

c++ - 计算像素坐标 x 和 y

ios - 用动画剪出形状

user-interface - 比较可以掩盖差异的工具?

python - 绘图时将 pandas (python) 分类 x 轴转换为连续值

python - pyinstaller 2.0 - 如何为 Windows exe 文件添加描述?

opencv透视变换函数异常