Reputation: 447
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)
Upvotes: 0
Views: 1171
Reputation: 208003
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:
Upvotes: 3
Reputation: 899
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
Upvotes: 0