本文介绍了如何使用 numpy 为图像的所有相对白色部分创建蒙版?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有 2 张白色图像(RGB 800x600 图像)在某些未知位置脏",我想创建一个最终组合图像,其中包含两个图像的所有脏部分.

Say I have 2 white images (RGB 800x600 image) that is 'dirty' at some unknown positions, I want to create a final combined image that has all the dirty parts of both images.

只需将图像加在一起就可以减少每个 blob 的脏度",因为我将像素值减半,然后将它们相加(保持在 0->255 rgb 范围内),当您有超过 2 个像素值时,这会被放大图片.

Just adding the images together reduces the 'dirtyness' of each blob, since I half the pixel values and then add them (to stay in the 0->255 rgb range), this is amplified when you have more than 2 images.

我想要做的是为 3 通道图像中所有相对白色的像素创建一个蒙版,我已经看到如果所有 RGB 值都在 10-15 之间,那么一个像素是相对白色的.我将如何使用 numpy 创建这个掩码?

What I want to do is create a mask for all relatively white pixels in the 3 channel image, I've seen that if all RGB values are within 10-15 of each other, a pixel is relatively white. How would I create this mask using numpy?

我想做的伪代码:

img = cv2.imread(img) #BGR image
mask = np.where( BGR within 10 of each other)

然后我可以使用第一张图片,并在第二张图片没有被遮罩的地方替换它的像素,保持脏度"相对较脏.(我知道第二张图片的一些脏会取代第一张的,但这没关系)

Then I can use the first image, and replace pixels on it where the second picture is not masked, keeping the 'dirtyness level' relatively dirty. (I know some dirtyness of the second image will replace that of the first, but that's okay)

人们要求提供图像,所以我创建了一些示例图像,白色并不总是像这些示例中那样完全是白色,这就是为什么我需要使用在 10 BGR"范围内的原因.

People asked for images so I created some sample images, the white would not always be so exactly white as in these samples which is why I need to use a 'within 10 BGR' range.

图 1

图 2

图3(合并,忽略图2到这里黄色斑点的区别,应该是一样的)

Image 3 (combined, ignore the difference in yellow blob from image 2 to here, they should be the same)

推荐答案

您要求的是具有颜色之间距离小于 10 的像素.

What you asked for is having the pixels in which the distance between colors is under 10.

在这里,翻译成 numpy.

Here it is, translated to numpy.

img = cv2.imread(img) #  assuming rgb image in naming
r = img[:, :, 0]
g = img[:, :, 1]
b = img[:, :, 2]
rg_close = np.abs(r - g) < 10
gb_close = np.abs(g - b) < 10
br_close = np.abs(b - r) < 10

all_close = np.logical_and(np.logical_and(rg_close, gb_close), br_close)

然而,我确实相信这不是您真正想要的.

I do believe, however, that this is not what you REALLY want.

我认为你想要一个分割背景的面具.

I think what you want in a mask that segments the background.

这实际上更简单,假设背景是全白的:

This is actually simpler, assuming the background is completely white:

img = cv2.imread(img)
background_mask = 245 * 3 < img[: ,: ,0] + img[: ,: ,1] + img[: ,: ,2]

请注意此代码需要阈值游戏,仅显示一个概念.

Please note this code required thresholding games, and only shows a concept.

这篇关于如何使用 numpy 为图像的所有相对白色部分创建蒙版?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 20:03
查看更多