Python 这里的错误是什么?我正在尝试使用OpenCV在人的头上添加帽子?

Python 这里的错误是什么?我正在尝试使用OpenCV在人的头上添加帽子?,python,opencv,computer-vision,Python,Opencv,Computer Vision,我正在尝试输入一个人的帽子图像。had需要根据人头进行旋转和调整大小。我真的被困在这里了。 这是我从实时视频中修改的代码。我不知道怎么做。任何帮助都将不胜感激。我可以对实时视频做同样的处理,但对图像则不行。如果这是不正确的,请帮助我在编码的图像 import dlib import cv2 import numpy as np from scipy import ndimage import matplotlib.pyplot as plt #video_capture = cv2.Video

我正在尝试输入一个人的帽子图像。had需要根据人头进行旋转和调整大小。我真的被困在这里了。 这是我从实时视频中修改的代码。我不知道怎么做。任何帮助都将不胜感激。我可以对实时视频做同样的处理,但对图像则不行。如果这是不正确的,请帮助我在编码的图像

import dlib
import cv2
import numpy as np
from scipy import ndimage
import matplotlib.pyplot as plt

#video_capture = cv2.VideoCapture("male.mp4")
glasses = cv2.imread("sunglasses.png", -1)
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")

#Resize an image to a certain width
def resize(img, width):
    r = float(width) / img.shape[1]
    dim = (width, int(img.shape[0] * r))
    img = cv2.resize(img, dim, interpolation=cv2.INTER_AREA)
    return img

#Combine an image that has a transparency alpha channel
def blend_transparent(face_img, sunglasses_img):

    overlay_img = sunglasses_img[:,:,:3]
    overlay_mask = sunglasses_img[:,:,3:]
    
    background_mask = 255 - overlay_mask

    overlay_mask = cv2.cvtColor(overlay_mask, cv2.COLOR_GRAY2BGR)
    background_mask = cv2.cvtColor(background_mask, cv2.COLOR_GRAY2BGR)

    face_part = (face_img * (1 / 255.0)) * (background_mask * (1 / 255.0))
    overlay_part = (overlay_img * (1 / 255.0)) * (overlay_mask * (1 / 255.0))

    return np.uint8(cv2.addWeighted(face_part, 255.0, overlay_part, 255.0, 0.0))

#Find the angle between two points
def angle_between(point_1, point_2):
    angle_1 = np.arctan2(*point_1[::-1])
    angle_2 = np.arctan2(*point_2[::-1])
    return np.rad2deg((angle_1 - angle_2) % (2 * np.pi))


#Start main program

img =cv2.imread('adrian.jpg',-1)
   # ret, img = video_capture.read()
img = resize(img, 700)
img_copy = img.copy()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)


    
        # detect faces
dets = detector(gray, 1)

        #find face box bounding points
for d in dets:

        x = d.left()
        y = d.top()
        w = d.right()
        h = d.bottom()

dlib_rect = dlib.rectangle(x, y, w, h)

        ##############   Find facial landmarks   ##############
detected_landmarks = predictor(gray, dlib_rect).parts()

landmarks = np.matrix([[p.x, p.y] for p in detected_landmarks])

for idx, point in enumerate(landmarks):
        pos = (point[0, 0], point[0, 1])
        if idx == 0:
                eye_left = pos
        elif idx == 16:
                eye_right = pos

        try:
                #cv2.line(img_copy, eye_left, eye_right, color=(0, 255, 255))
            degree = np.rad2deg(np.arctan2(eye_left[0] - eye_right[0], eye_left[1] - eye_right[1]))

        except:
            pass

        ##############   Resize and rotate glasses   ##############

        #Translate facial object based on input object.

eye_center = (eye_left[1] + eye_right[1]) / 2

        #Sunglasses translation
glass_trans = int(.2 * (eye_center - y))

        #Funny tanslation
        #glass_trans = int(-.3 * (eye_center - y ))

        # Mask translation
        #glass_trans = int(-.8 * (eye_center - y))


        # resize glasses to width of face and blend images
face_width = w - x

        # resize_glasses
glasses_resize = resize(glasses, face_width)

        # Rotate glasses based on angle between eyes
yG, xG, cG = glasses_resize.shape
glasses_resize_rotated = ndimage.rotate(glasses_resize, (degree+90))
glass_rec_rotated = ndimage.rotate(img[y + glass_trans:y + yG + glass_trans, x:w], (degree+90))


        #blending with rotation
h5, w5, s5 = glass_rec_rotated.shape
rec_resize = img_copy[y + glass_trans:y + h5 + glass_trans, x:x + w5]
blend_glass3 = blend_transparent(rec_resize , glasses_resize_rotated)
img_copy[y + glass_trans:y + h5 + glass_trans, x:x+w5 ] = blend_glass3
    

#except:
 #   cv2.imshow('Output', img_copy)
    
#cv2.imshow('Output', img_copy)
plt.imshow(img_copy)
错误回溯(最近一次调用上次)
在里面
126 h5,w5,s5=玻璃形状
127 rec_resize=img_复制[y+玻璃_trans:y+h5+玻璃_trans,x:x+w5]
-->128 blend_glass3=blend_透明(调整大小,调整大小,旋转玻璃)
129 img_拷贝[y+玻璃_trans:y+h5+玻璃_trans,x:x+w5]=混合玻璃3
130
混合透明(面部、太阳镜)
38背景遮罩=255-覆盖遮罩
39
--->40叠加遮罩=cv2.CVT颜色(叠加遮罩,cv2.COLOR\U GRAY2BGR)
41背景遮罩=cv2.CVT颜色(背景遮罩,cv2.COLOR\U GRY 2BGR)
42
错误:OpenCV(4.5.1)c:\users\appveyor\appdata\local\temp\1\pip req build-
kh7iq4w7\opencv\modules\imgproc\src\color.simd_helpers.hpp:92:错误:(-2:未指定的错误)在
函数“\uu cdecl cv::impl::`anonymous namespace'::cvt输入映像中的通道数无效:
>'VScn::contains(scn)'
>在哪里
>“scn”是512

将您的代码简化为最小的可重复示例
error                                     Traceback (most recent call last)
<ipython-input-4-2a72696a8374> in <module>
126 h5, w5, s5 = glass_rec_rotated.shape
127 rec_resize = img_copy[y + glass_trans:y + h5 + glass_trans, x:x + w5]
--> 128 blend_glass3 = blend_transparent(rec_resize , glasses_resize_rotated)
129 img_copy[y + glass_trans:y + h5 + glass_trans, x:x+w5 ] = blend_glass3
130 

<ipython-input-4-2a72696a8374> in blend_transparent(face_img, sunglasses_img)
 38     background_mask = 255 - overlay_mask
 39 
---> 40     overlay_mask = cv2.cvtColor(overlay_mask, cv2.COLOR_GRAY2BGR)
 41     background_mask = cv2.cvtColor(background_mask, cv2.COLOR_GRAY2BGR)
 42 

error: OpenCV(4.5.1) c:\users\appveyor\appdata\local\temp\1\pip-req-build- 
kh7iq4w7\opencv\modules\imgproc\src\color.simd_helpers.hpp:92: error: (-2:Unspecified error) in 
function '__cdecl cv::impl::`anonymous-namespace'::CvtHelper<struct cv::impl::`anonymous 
namespace'::Set<1,-1,-1>,struct cv::impl::A0x206ccf44::Set<3,4,-1>,struct 
cv::impl::A0x206ccf44::Set<0,2,5>,2>::CvtHelper(const class cv::_InputArray &,const class 
cv::_OutputArray &,int)'
> Invalid number of channels in input image:
>     'VScn::contains(scn)'
> where
>     'scn' is 512