简体   繁体   English

从图像中切出或移除进入蒙版黑色像素的像素

[英]Cut out or remove the pixels from an image that run into the black pixels of a mask

I'm trying to cut out two images with OpenCV using Python.我正在尝试使用 Python 用 OpenCV 剪出两个图像。

The idea is to use an image like this one:这个想法是使用这样的图像:

在此处输入图片说明

As a mask.作为面具。 Note: this is only an example.注意:这只是一个例子。

So if I subtract this mask to another image, I will get an image with the original pixels only in the same location as the white rectangle in the mask.因此,如果我将这个蒙版减去另一个图像,我将得到一个原始像素仅与蒙版中的白色矩形位于同一位置的图像。 So, the idea is to remove the pixels from the first image that run into the same location that the black ones in the mask.因此,我们的想法是从第一张图像中删除与蒙版中黑色像素相同位置的像素。

How can I do it?我该怎么做?

Maybe I can do an AND operation between the two images (the mask will have only 0 (for black) and 1 (for white pixels).也许我可以在两个图像之间进行AND运算(掩码只有 0(黑色)和 1(白色像素)。

If what you are asking is how to make the image transparent where the mask is black and opaque where the mask is white, then just add the mask to the alpha channel of the input.如果您要问的是如何使蒙版为黑色的图像透明而蒙版为白色的不透明,则只需将蒙版添加到输入的 alpha 通道即可。 Here is how to do that in Python/OpenCV.下面是如何在 Python/OpenCV 中做到这一点。 (Revised per comment by Mark Setchell) (根据 Mark Setchell 的评论修订)

Input:输入:

在此处输入图片说明

Mask:面具:

在此处输入图片说明

import cv2
import numpy as np

# load image
img = cv2.imread('lena.png')

# load mask as grayscale
mask = cv2.imread('rect_mask.png', cv2.COLOR_BGR2GRAY)

# put mask into alpha channel of image
#result = img.copy()
#result = cv2.cvtColor(result, cv2.COLOR_BGR2BGRA)
#result[:, :, 3] = mask
result = np.dstack((img, mask))

# save resulting masked image
cv2.imwrite('lena_masked.png', result)


Result:结果:

在此处输入图片说明

This is how I did it.我就是这样做的。

Input arrays have a shape of (240, 240) and output array has a shape of (240, 240) .输入数组的形状为(240, 240) ,输出数组的形状为(240, 240)

I will mask the indices on image array with the indices in mask array which have a value of 0.我将使用mask数组中值为 0 的索引来mask image数组上的索引。

def cut_out(image, mask):
    if type(image) != np.ndarray:
        raise TypeError("image must be a Numpy array")
    elif type(mask) != np.ndarray:
        raise TypeError("mask must be a Numpy array")
    elif image.shape != mask.shape:
        raise ValueError("image and mask must have the same shape")

    return np.where(mask==0, 0, image)

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

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