简体   繁体   English

用原始图像opencv Python替换掩码

[英]replace mask with original image opencv Python

I am trying to replace objects which I found using a mask with the original images pixels.我正在尝试用原始图像像素替换我使用蒙版找到的对象。 I have a mask that shows black where the object is not detected and white if detected.我有一个蒙版,在未检测到物体的地方显示黑色,如果检测到,则显示为白色。 I am then using the image in a where statement然后我在 where 语句中使用图像

image[np.where((image2 == [255,255,255].any(axis = 2)) 

I am stuck here and I have no idea how to change found white values to what the original image is (to use alongside other masks).我被困在这里,我不知道如何将找到的白色值更改为原始图像(与其他蒙版一起使用)。 I have tried image.shape and this did not work.我试过image.shape但这没有用。

Thanks.谢谢。

Make a copy of the mask and then draw the original image over the white pixels of the mask from the white pixel coordinates. 复制蒙版,然后从白色像素坐标在蒙版的白色像素上绘制原始图像。 You can also check mask == 255 to compare element-wise. 您还可以检查mask == 255以进行逐元素比较。 You don't need np.where because you can index arrays via the boolean mask created by mask == 255 . 您不需要np.where,因为您可以通过mask == 255创建的布尔掩码对数组进行索引。

out = mask.copy()
out[mask == 255] = original_image[mask == 255]

You can use bitwise operations. 您可以使用按位运算。 Try this: 尝试这个:

replaced_image = cv2.bitwise_and(original_image,original_image,mask = your_mask)

例 Visit https://docs.opencv.org/3.3.0/d0/d86/tutorial_py_image_arithmetics.html to learn more about bitwise operations 访问https://docs.opencv.org/3.3.0/d0/d86/tutorial_py_image_arithmetics.html进一步了解按位操作

import os
import cv2
from netpbmfile import imread
 
img_dir = '.'
mask_dir = '.'
new_bg = 'image.png'

def get_foreground(fg_image_name, mask_name, bg_image_name):
    fg_image = cv2.imread(fg_image_name)
    mask = imread(mask_name)
    mask_inverse = (1-mask)
    bg_image = cv2.imread(bg_image_name)
    bg_image = cv2.resize(bg_image, (fg_image.shape[1], fg_image.shape[0]))
    foregound = cv2.bitwise_and(fg_image, fg_image, mask=mask)
    background = cv2.bitwise_and(bg_image, bg_image, mask=mask_inverse)
    composite = foregound + background
    
    return composite


image_fg = get_foreground(os.path.join(img_dir, "NP1_0.jpg"), os.path.join(mask_dir, "NP1_0_mask.pbm"), new_bg)
cv2.imwrite("foreground.jpg", image_fg)

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

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