【问题标题】:shrink and enlarge contour image with Python OpenCV使用 Python OpenCV 缩小和放大轮廓图像
【发布时间】:2021-12-23 22:46:50
【问题描述】:

我有一个带有如下对象的图像:

我可以检测轮廓并得到一个只有球区域的掩码,但我的 ROI 是边缘区域,这意味着我需要一个更大和更小的掩码结合起来得到这个:

所以我的问题是:如何缩小/放大轮廓中心周围的轮廓蒙版?

【问题讨论】:

  • 我不确定我是否理解。但如果我这样做了,那么您可以使用形态扩张和侵蚀来分别放大和缩小蒙版。
  • 谢谢你的想法,我刚刚尝试过侵蚀,当内核大小或交互更大时,轮廓的形状被扭曲:椭圆看起来像平行四边形。你知道如何避免它吗?

标签: python numpy opencv contour edge-detection


【解决方案1】:

这是在 Python/OpenCV 中执行此操作的一种方法。

 - Read the input
 - Convert to grayscale
 - Threshold
 - Use morphology close and open to clean up noise and small regions to form a mask
 - Dilate the mask
 - Erode the mask
 - Merge the input and dilated mask
 - Merge the eroded mask with the previous result
 - Save the result

输入:

import cv2
import numpy as np

# read image
img = cv2.imread("basketball.png")

# convert img to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# make anything not white into black
mask = gray.copy()
mask[mask!=255] = 0

# invert mask so center is white and outside is black
mask = 255 - mask

# close open mask to clean up small regions and make 3 channels
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5))
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
mask = cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR)

# erode mask
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (51,51))
erode = cv2.morphologyEx(mask, cv2.MORPH_ERODE, kernel)

# dilate mask and make 3 channels
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (51,51))
dilate = cv2.morphologyEx(mask, cv2.MORPH_DILATE, kernel)

# merge image onto dilated mask using mask
result = np.where(mask==(255,255,255), img, dilate)

# merge inverted erode onto result using erode
result = np.where(erode==(255,255,255), (255-erode), result)

# write result to disk
cv2.imwrite("basketball_mask.png", mask)
cv2.imwrite("basketball_eroded_mask.png", erode)
cv2.imwrite("basketball_dilate_mask.png", dilate)
cv2.imwrite("basketball_dilate_mask.png", dilate)
cv2.imwrite("basketball_result.png", result)

# display it
cv2.imshow("image", img)
cv2.imshow("mask", mask)
cv2.imshow("erode", erode)
cv2.imshow("dilate", dilate)
cv2.imshow("result", result)
cv2.waitKey(0)

面具:

腐蚀面具:

扩张蒙版:

结果:

注意:如果扩张过多,则会到达图像的边缘,然后形状会发生变化。为避免这种情况,请使用足够的背景颜色填充输入以包含扩张后的大小。

【讨论】:

  • 太棒了。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-13
  • 1970-01-01
  • 2015-04-24
  • 2019-12-06
  • 1970-01-01
相关资源
最近更新 更多