【问题标题】:How to fill closed contour region with white如何用白色填充闭合轮廓区域
【发布时间】:2019-12-22 08:54:47
【问题描述】:

我正在尝试仅使用 ROI 在单元格图像中制作蒙版,因此我在 ROI 周围使用 OpenCV 应用了轮廓,但我一直在努力使该区域位于轮廓内。我想把这个区域放在白色里面,然后丢弃轮廓和外面的其余部分。

cell = cv.imread(original, 0) # original cell image after matching template
imgray = cv.cvtColor(cell,cv.COLOR_BGR2GRAY) 
ret,thresh_binary = cv.threshold(imgray,127,255,cv.THRESH_BINARY)

生成的图像是:

而原文是:

从匹配模板后的另一张图像和已经标记的单元格轮廓,代码中读取的图像:

所以基本上我需要的是在那个封闭的轮廓区域中使用白色并丢弃所有其余部分(即黑色)。 有人可以给我一些帮助或提示我该怎么做吗?

【问题讨论】:

  • 你能添加你的原始图像和预期的输出图像吗?您可以使用形态学运算来平滑异常值部分,然后找到生成的轮廓。然后就可以使用cv2.drawContours(),用白色填充闭合轮廓区域
  • 见 CV_FILLED 或 -1 以获取 cv2.drawContours() 中的厚度参数docs.opencv.org/3.1.0/d6/d6e/…
  • 已编辑-nathancy

标签: python opencv image-processing image-segmentation scikit-image


【解决方案1】:

这是一种方法:

  • 将图像转换为灰度
  • 查找轮廓并填充轮廓
  • 执行形态转换以删除不需要的部分

我们找到轮廓然后用cv2.drawContours()填充轮廓,使用-1作为厚度参数

要删除行部分,我们可以使用morphological transformations

import cv2

image = cv2.imread('1.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

cnts = cv2.findContours(gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]

for c in cnts:
    cv2.drawContours(gray,[c], 0, (255,255,255), -1)

kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (20,20))
opening = cv2.morphologyEx(gray, cv2.MORPH_OPEN, kernel, iterations=2)

cv2.imshow('gray', gray)
cv2.imshow('opening', opening)
cv2.imwrite('opening.png', opening)
cv2.waitKey(0)

【讨论】:

  • 非常感谢。感谢您的回答 nathancy。
猜你喜欢
  • 1970-01-01
  • 2021-01-15
  • 2020-11-13
  • 1970-01-01
  • 2013-01-01
  • 2018-02-24
  • 1970-01-01
  • 1970-01-01
  • 2021-10-15
相关资源
最近更新 更多