【问题标题】:OpenCV&Python - Set specific colour to region of imageOpenCV Python - 为图像区域设置特定颜色
【发布时间】:2018-01-02 21:59:36
【问题描述】:

我正在使用 OpenCV 和 Python。我正在检测人脸图像中的人脸,我将注意力集中在图像中人脸的区域,并创建了一个蒙版(零),我想在该区域用白色(或一般的任何颜色)填充的脸。我的源代码如下:

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]

但是我收到以下错误:

  mask_face[y:y + h, x:x + w] = [255, 255, 255]
ValueError: could not broadcast input array from shape (3) into shape (462,462)

如何将图像的这个区域设置为我想要的任何颜色?

【问题讨论】:

    标签: python opencv


    【解决方案1】:

    你可以使用:

    mask_face = cv2.rectangle(mask_face, (x,y), (x + w,y + h), (255,255,255), -1)
    

    【讨论】:

    • 感谢您的回答。是的,我有这个想法(但请注意,它是 'cv2' 而不是 'cv' 和 '-1' 而不是 '1')。
    【解决方案2】:

    切片方法没问题,但是你需要创建一个valid imagemask_face需要是一个rgb image

    mask_face = np.zeros(RGB_img.shape[:2] + (3,), np.uint8)
    

    然后你可以使用切片的方法或者像Maxime Guinin answer这样画一个矩形

    更新以改进答案。

    RGB 图像是具有 3 维(高度、宽度和颜色通道)的多维数组,因此,当您创建 mask_face 时您错过了颜色通道,然后 + (3,) 将其添加。这就像创建了空白rgb_image,第一个参数可以是listtuple

    blank_image = np.zeros((height, width, 3), np.uint8)
    

    【讨论】:

    • 感谢您的回复。如果您有空余时间,请详细说明您的答案,因为即使我现在知道了,为什么例如您正在做“+ [3]”并不那么明显。
    • 是的,谢谢。但是我现在收到以下错误:mask_face = np.zeros(RGB_img.shape[:2] + [3], np.uint8) TypeError: can only concatenate tuple (not "list") to tuple。这是为什么呢?
    • 对不起,我的错,RGB_img.shape[:2] 返回一个元组,所以,你需要+ (3,),而不是+ [3],答案已修复。
    猜你喜欢
    • 2021-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-01
    • 2018-01-24
    • 2021-04-30
    • 1970-01-01
    相关资源
    最近更新 更多