Reputation: 5117
I am working with OpenCV and Python. I am detecting the face in a face image, I am focusing at the region of the face in the image and I create a mask (of zeros) which I want to fill in with white colour (or any colour in general) at the region of the face. My source code is the following:
import cv2
import numpy as np
import matplotlib.pyplot as plt
img = cv2.imread('ManWithGlasses.jpg')
RGB_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# Detect the face in the image
haar_face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
faces = haar_face_cascade.detectMultiScale(gray_img, scaleFactor=1.1, minNeighbors=8);
mask_face = np.zeros(RGB_img.shape[:2], np.uint8)
# Loop in all detected faces - in our case it is only one
for (x,y,w,h) in faces:
cv2.rectangle(RGB_img,(x,y),(x+w,y+h),(255,0,0), 2)
plt.imshow(RGB_img)
plt.show()
roi_rgb = img[y:y + h, x:x + w]
mask_face[y:y + h, x:x + w] = [255, 255, 255]
However I get the following error:
mask_face[y:y + h, x:x + w] = [255, 255, 255]
ValueError: could not broadcast input array from shape (3) into shape (462,462)
How can I set this region of the image to whichever colour I want?
Upvotes: 1
Views: 1679
Reputation: 246
The slicing method work's fine, but you need to create a valid image
, mask_face
need to be a rgb image
:
mask_face = np.zeros(RGB_img.shape[:2] + (3,), np.uint8)
Then you can use slicing method or just draw a rectangle like Maxime Guinin answer
UPDATE to improve answer.
RGB images are multidimensional arrays with 3 dimensions (height, width and color channels), so, when you created mask_face
you missed color channels, then + (3,)
to add this. This is like blank rgb_image
is created, the first arg can be a list
or a tuple
:
blank_image = np.zeros((height, width, 3), np.uint8)
Upvotes: 1
Reputation: 190
You can use:
mask_face = cv2.rectangle(mask_face, (x,y), (x + w,y + h), (255,255,255), -1)
Upvotes: 2