Lavinia Paganini
Lavinia Paganini

Reputation: 1

Alpha blending using opencv with a black png on python

I'm trying to create a aplication with opencv that overlaps a glass on me face. However, when the video appears the glasses have a black on the alpha layer. Here is my code:

video_capture = cv2.VideoCapture(0)
anterior = 0
glasses = cv2.imread('Glasses_1.png')

def put_glasses(glasses,fc,x,y,w,h):

    face_width = w
    face_height = h

    glasses_width = int(face_width)
    glasses_height = int(face_height*0.32857)



    glasses = cv2.resize(glasses,(glasses_width,glasses_height))

    for i in range(glasses_height):
        for j in range(glasses_width):
            for k in range(3):
                if glasses[i][j][k]<235:

                    fc[y+i-int(-0.25*face_height)-1][x+j][k] = glasses[i][j][k]
    return fc

while True:
    if not video_capture.isOpened():
        print('Unable to load camera.')
        sleep(5)
        pass
    ret, frame = video_capture.read()
    if ret is True:
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    else:
        continue

    faces = faceCascade.detectMultiScale(
        gray,
        scaleFactor=1.1,
        minNeighbors=5,
        minSize=(40,40)
    )
    for (x, y, w, h) in faces:
        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
        cv2.putText(frame,"Person Detected",(x,y),cv2.FONT_HERSHEY_SIMPLEX,1,(0,0,255),2)
        frame = put_glasses(glasses, frame, x, y, w, h)

I will be very grateful if anyone could help.

Upvotes: 0

Views: 2621

Answers (1)

Kinght 金
Kinght 金

Reputation: 18331

You read the png in bgr format, not the bgra or unchanged format. Then I don't think your glass image in the program is shape of (h,w,4). You should read with flag cv2.IMREAD_UNCHANGED.

glasses = cv2.imread("xxx.png", cv2.IMREAD_UNCHANGED)


Maybe this link will help. How do I clear a white background in OpenCV with c++?

The bgra worm:

enter image description here

Blending:

enter image description here

Upvotes: 1

Related Questions