简体   繁体   English

如何从图像中屏蔽掉 object?

[英]How to mask out the object from the image?

I have a RGB image of 256X256 with the binary mask.我有一个带有二进制掩码的 256X256 的 RGB 图像。 I want to remove the object from the main image with the help of mask and keep the rest background.我想借助掩码从主图像中删除 object 并保留 rest 背景。

I have tried with the below code but it didn't work.我已经尝试过使用下面的代码,但它没有用。

Can anyone let me know where I made the mistake?谁能让我知道我在哪里犯了错误?

import cv2
import numpy as np

# read image
img = cv2.imread('image.jpg')

mask2 = cv2.imread('mask.jpg') / 1
# mask by multiplication, clip to range 0 to 255 and make integer
result2 = (img * mask2).clip(0, 255).astype(np.uint8)



# save results
cv2.imwrite('result.png', result1)

Image, Mask:图片,面具:

图片 面具

Output I want, The result I am getting: Output 我想要,我得到的结果:

输出 我的结果

You need to use cv2.bitwise_and for your problem.您需要使用cv2.bitwise_and来解决您的问题。 It performs 'AND' operation between your img and mask in a bitwise manner.它以按位方式在您的imgmask之间执行“与”操作。

  • For white region in the mask , corresponding img region is preserved对于mask中的白色区域,保留对应的img区域
  • For white region in the mask , corresponding img region is occluded对于mask中的白色区域,对应的img区域被遮挡

Code:代码:

img = cv2.imread(r'C:\Users\524316\Desktop\Stack\eye\eye.jpg')
mask = cv2.imread(r'C:\Users\524316\Desktop\Stack\eye\mask.jpg', 0)

# invert the mask
th = cv2.threshold(mask,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)[1]

# preserve the background
res = cv2.bitwise_and(img, img, mask = th)

Result:结果:

在此处输入图像描述

You don't need Otsu thresholding, just ordinary thresholding, with a sensible threshold.您不需要 Otsu 阈值,只需普通阈值,具有合理的阈值。 Your "mask" image is a JPEG.您的“掩码”图像是 JPEG。 Lossy compression causes it to not be entirely black or white.有损压缩会导致它完全是黑色或白色。

Once you have the mask, you just need to learn about masking operations.有了遮罩后,您只需要了解遮罩操作即可。 That is a feature of numpy I'm using here:这是我在这里使用的numpy的一个功能:

im = cv.imread("VgAjK.jpg")
maskim = cv.imread("ZKKkp.jpg", cv.IMREAD_GRAYSCALE)

im[maskim >= 128] = 255 # "remove", paint over with white

输出

You multiplied... that might have worked (except inverted) if your arrays had the right value ranges.如果您的 arrays 具有正确的值范围,那么您乘以...可能会起作用(倒置除外)。

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

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