python - 如何将这两个图像与 python numpy 和 opencv 合并?

标签 python numpy opencv mask

我有两个二进制图像。第一个是这样的:

enter image description here

最后一个是这样的:

enter image description here

它们的曲线大小不同。我想将第二个包含在黑色区域中的两个白色区域添加到第一个的黑色区域。

我的代码是这样运行的,但这是一个错误的答案:

enter image description here

问题是这样的,我想得到我用the final image 在图片中绘制的finally 图像:

enter image description here

我怎样才能完成这个任务?

最佳答案

假设 img1 是您的第一个数组(较大的实心 blob)而 img2 是第二个(带有孔的较小 blob),您需要一种方法来识别和删除外部第二张图的区域。 flood fill算法是一个很好的选择。它在 opencv 中实现为 cv2.floodFill .

最简单的做法是填充外边缘,然后将结果相加:

mask = np.zeros((img2.shape[0] + 2, img2.shape[1] + 2), dtype=np.uint8)
cv2.floodFill(img2, mask, (0, 0), 0, 0)
result = img1 + img2

这是一个玩具示例,显示了在拓扑上与您的原始图像等效的迷你图像:

img1 = np.full((9, 9), 255, dtype=np.uint8)
img1[1:-1, 1:-1] = 0
img2 = np.full((9, 9), 255, dtype=np.uint8)
img2[2:-2, 2:-2] = 0
img2[3, 3] = img2[5, 5] = 255

图像看起来像这样:

fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.imshow(img1)
ax2.imshow(img2)

start

填充后的图像是这样的:

enter image description here

将生成的图像加在一起看起来像这样:

enter image description here

请记住,floodFill 是就地操作的,因此您可能需要在继续此操作之前复制一份 img2

关于python - 如何将这两个图像与 python numpy 和 opencv 合并?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52501817/

相关文章:

python - Numpy Vector (N,1) 维度 -> (N,) 维度转换

python - 在python中将numpy数组转换为csv文件

python - 使用 pandas 的列 View ?

opencv - 如果我在我的内核函数中调用 OpenCV GPU 模块中的函数,它会工作并且更快吗?

opencv - 图像处理opencv 3.0断言失败错误

Python 连接字符串 - UnicodeDecodeError : 'ascii' codec can't decode byte

python - 我如何只在 x 轴上居中文本,但能够在 pygame 中移动 y 轴?

linux - opencv cuda程序编译报错

python - 如何强制操作系统使用 python 释放端口

Python 导入的细微差别