gpt4 book ai didi

Python 和 opencv : how do I convert the ALL of the background of this image to one colour or transparent

转载 作者:行者123 更新时间:2023-12-02 16:37:19 27 4
gpt4 key购买 nike

我使用图像 1 上的阈值蒙版(图像 2)创建了以下图像(图像 3)。我试图将图像 3(肺部)中央图像之外的所有像素转换为一种颜色(例如黑色)使用opencv。基本上这样我就只剩下肺部图像在统一的背景下(甚至是透明的)。我的问题是图像 3 上非常外部的像素与肺部内部的像素相似。这可以使用 opencv 吗?

IMAGE 1

IMAGE 2

IMAGE3

最佳答案

简单 floodFill() 从图像的边界用黑色蒙版。请参阅我的回答中的洪水填充步骤 here看看它在另一个场景中的使用。

同样,您可以使用 floodFill()找出哪些像素连接到图像的边缘,这意味着您可以使用它来将肺部的孔从阈值化中放回原处。看我的回答 here对于此孔填充过程的另一个示例。

我直接从上面的答案中复制并粘贴了代码,只修改了变量名称:

import cv2
import numpy as np

img = cv2.imread('img.jpg', 0)
mask = cv2.imread('mask.png', 0)

# flood fill to remove mask at borders of the image
h, w = img.shape[:2]
for row in range(h):
if mask[row, 0] == 255:
cv2.floodFill(mask, None, (0, row), 0)
if mask[row, w-1] == 255:
cv2.floodFill(mask, None, (w-1, row), 0)
for col in range(w):
if mask[0, col] == 255:
cv2.floodFill(mask, None, (col, 0), 0)
if mask[h-1, col] == 255:
cv2.floodFill(mask, None, (col, h-1), 0)

# flood fill background to find inner holes
holes = mask.copy()
cv2.floodFill(holes, None, (0, 0), 255)

# invert holes mask, bitwise or with mask to fill in holes
holes = cv2.bitwise_not(holes)
mask = cv2.bitwise_or(mask, holes)

# display masked image
masked_img = cv2.bitwise_and(img, img, mask=mask)
masked_img_with_alpha = cv2.merge([img, img, img, mask])
cv2.imwrite('masked.png', masked_img)
cv2.imwrite('masked_transparent.png', masked_img_with_alpha)

编辑:顺便说一句,“透明度”基本上是一个蒙版:值告诉您每个像素的不透明程度。如果像素为 0,则表示完全透明,如果为 255(对于 uint8),则表示完全不透明,如果介于两者之间,则表示部分透明。因此,最后使用的完全相同的蒙版可以堆叠到图像上以创建第四个 alpha channel (您可以使用 cv2.merge 或 numpy 来堆叠),它将使蒙版中的每个 0 像素完全透明;只需将图像另存为 png为了透明度。上面的代码创建了一个具有 alpha 透明度的图像以及一个具有黑色背景的图像。

Masked lungs with transparency

这里的背景看起来是白色的,因为它是透明的,但是如果您将图像保存到系统中,您会看到它实际上是透明的。仅供引用 OpenCV 在 imshow() 期间实际上忽略了 alpha channel 所以你只会看到保存图像的透明度。

编辑:最后一个说明……这里你的阈值已经去除了一些肺部。我已经从肺部内部发生的阈值处理中重新添加了孔,但这遗漏了沿边界被移除的一些块。如果您在蒙版上进行轮廓检测,如果重要的话,您实际上也可以将其平滑一些。查看 OpenCV 上的“轮廓近似”部分 contour features tutorial .基本上它会尝试平滑轮廓,但与实际轮廓保持一定的 epsilon 距离。这可能很有用并且很容易实现,所以我想我会在最后把它作为一个建议。

关于Python 和 opencv : how do I convert the ALL of the background of this image to one colour or transparent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55406274/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com