繁体   English   中英

如何从 Python 中的蒙版分割图像创建轮廓(厚度可控)?

[英]How to create an outline (with controllable thickness) from a mask segmentation image in Python?

蒙版图像

在这里,我有一张来自其中一个分割模型的分割图像 output。 我想为这些掩码创建一个轮廓,然后将该轮廓放在原始图像上,以将图像上的预测区域指示为分割 output。

我尝试使用 PIL 过滤器 FIND_EDGES,但它为轮廓提供了非常薄的边缘。

有没有办法将此蒙版图像转换为仅具有这些蒙版轮廓的图像,我可以在其中控制轮廓的厚度?

如果我理解正确,您想找到所有斑点的轮廓,然后将此轮廓绘制到另一个具有可控轮廓厚度的图像上。 您可以使用cv2.drawContours()执行此操作,并使用thickness参数控制轮廓厚度。 设置负值,例如。 -1 ,将填充轮廓,同时增加参数会给你一个更厚的轮廓。

在此示例中,我们使用 cv2.findContours() 找到每个 blob 的轮廓,然后使用cv2.drawContours() cv2.findContours()将轮廓绘制到蒙版上。 在您的情况下,您可以将其绘制到所需的图像上,而不是将其绘制到蒙版上。 thickness=2

在此处输入图像描述

thickness=5

在此处输入图像描述

import cv2
import numpy as np

image = cv2.imread('1.png')
mask = np.ones(image.shape, dtype=np.uint8) * 255
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(mask, [c], -1, (36, 255, 12), thickness=5)

cv2.imshow('mask', mask)
cv2.waitKey()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM