首页 > 解决方案 > opencv显示带视频的图像,没有图像背景

问题描述

我想在 opencv 视频流上显示笑脸图像。使用这个程序,我可以显示图像,但问题是它带有图像的背景。我只想要一个没有背景的圆形图像。我曾尝试使用在线工具去除背景。有什么方法可以在没有图像背景的情况下显示笑脸?

import cv2
import time

cap= cv2.VideoCapture(0)


fps= int(cap.get(cv2.CAP_PROP_FPS))

print("This is the fps ", fps)

if cap.isOpened() == False:
    print("Error File Not Found")

while cap.isOpened():
    ret,frame= cap.read()

    if ret == True:

        time.sleep(1/fps)
        img = cv2.imread("/home/pi/Downloads/red-removebg-preview (1).png", cv2.IMREAD_UNCHANGED)
        frame[100:390, 0:290]=img 
        cv2.imshow('frame', frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    else:
        break

只是为了尝试我正在附加另一张图片。

在此处输入图像描述

标签: pythonopencv

解决方案


就像评论中提到的一样,这里是基本思想

import cv2
import time
from skimage import transform, img_as_float
import numpy as np

# reading the video
cap= cv2.VideoCapture('SampleVideo_1280x720_1mb.mp4')
# cap= cv2.VideoCapture(0) for camera


fps= int(cap.get(cv2.CAP_PROP_FPS))

print("This is the fps ", fps)

if cap.isOpened() == False:
    print("Error File Not Found")

# I am using an emoji that is not (290,290), that is why using resize
img = cv2.imread("d7glM.png", cv2.IMREAD_UNCHANGED)
img = transform.resize(img, (290,290))
img = img_as_float(img)

# the input imoji should have alpha channel, otherwise you cans mask
if(img.shape[2] <4):
    print('sorry can\'t mask')
        
while cap.isOpened():
    ret,frame= cap.read()

    if ret == True:
        # here I am using img_as_float() to convert
        # both the images to float64
        frame = img_as_float(frame)



        # I am using a sample video which has a shape (720,1800,3)
        # the emoji is png with a alpha channel (R G B A)
        # I will use the alpha to mask the background

        # masking Red channel
        frame[100:390, 0:290, 0] *= 1 - img[:,:,3]
        # masking Green channel
        frame[100:390, 0:290, 1] *= 1 - img[:,:,3]
        # masking Blue channel
        frame[100:390, 0:290, 2] *= 1 - img[:,:,3]
        
        # now finally add the image in that mask
        frame[100:390, 0:290, :] += img[:,:,:3]
        cv2.imshow('frame', frame)
        
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

在此处输入图像描述


推荐阅读