简体   繁体   中英

Replacing part of image with a mask in opencv

I have an image that is 384x384 pixels.I want to mask out or replace everything in the middle of the image, so I just have the borders of the image. For this I have created a mask that is 352x352 pixels (just a black image). Now I want to place this mask in the middle of the image so it has a distance of 32 pixels to every corner.

I thought of something like this but it does not work:

mask = cv2.imread('C://Users//but//Desktop//mask.png')
hh, ww, dd = mask.shape

image = cv2.imread('C://Users//but//Desktop//Train//OK//train_image1.jpg')

x = 32
y = 352
print('left:', x, 'top:', y)

# put mask into black background image
mask2 = np.full_like(image, 255)
mask2[x:x + hh, y:y + ww] = mask

# apply mask to image
img_masked = cv2.bitwise_and(image, mask2)

cv2.imshow('masked image', img_masked)
cv2.waitKey(0)
cv2.destroyAllWindows()

The error I get is:

Traceback (most recent call last):
File "C:/Users/but/PycharmProjects/SyntheticDataWriter.py", line 17, in <module>
mask2[x:x + hh, y:y + ww] = mask
ValueError: could not broadcast input array from shape (352,352,3) into shape (352,32,3)

You can make the middle of the image black without creating a black image and overlaying it or anding it, just use Numpy slicing:

import cv2

# Load image and get its dimensions
im = cv2.imread('paddington.png', cv2.IMREAD_COLOR)
h,w = im.shape[0:2]

# Make middle black
im[32:h-32, 32:w-32, :] = 0

cv2.imwrite('result.png', im)

在此处输入图像描述

Here's a thumbnail of how he used to be in case anyone doesn't know:

在此处输入图像描述

This will help you to add a mask to your image.

import cv2


# image = cv2.imared("path to image")  # (384x384X3)
image = np.ones((384, 384, 3), dtype=np.uint8) * 150  # creating 3d image with pixel value 150

h, w, c = image.shape

border_padding = 32  # border width and height you want to set

# we will set pixel value to zero from [32: 384-32, 32: 384-32]
image[border_padding:h-border_padding, border_padding:w-border_padding] = 0  # black mask image

Image

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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