如何使用二进制掩码来掩码图像 [英] How to mask image with binary mask

查看:152
本文介绍了如何使用二进制掩码来掩码图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在这里有一个灰度图像:

Suppose I have a greyscale image here:

这里有一个二进制蒙版图像:

And a binary masked image here:

具有相同的尺寸和形状.我如何生成这样的东西:

With the same dimensions and shape. How do I generate something like this:

其中二进制掩码中 1 表示的值为真实值,掩码中为 0 的值在最终图像中为空.

Where the values indicated by the 1 in the binary mask are the real values, and values that are 0 in the mask are null in the final image.

推荐答案

使用 cv2.bitwise_and 用二进制掩码对图像进行掩码.蒙版上的任何白色像素(值为 1)将被保留,而黑色像素(值为 0)将被忽略.举个例子:

Use cv2.bitwise_and to mask an image with a binary mask. Any white pixels on the mask (values with 1) will be kept while black pixels (value with 0) will be ignored. Here's a example:

输入图像(左),蒙版(右)

Input image (left), Mask (right)

屏蔽后的结果

代码

import cv2
import numpy as np

# Load image, create mask, and draw white circle on mask
image = cv2.imread('1.jpeg')
mask = np.zeros(image.shape, dtype=np.uint8)
mask = cv2.circle(mask, (260, 300), 225, (255,255,255), -1) 

# Mask input image with binary mask
result = cv2.bitwise_and(image, mask)
# Color background white
result[mask==0] = 255 # Optional

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

这篇关于如何使用二进制掩码来掩码图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆