python - 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
只是为了尝试我正在附加另一张图片。
解决方案
就像评论中提到的一样,这里是基本思想
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
推荐阅读
- javascript - 在闪亮中加入javascript
- pandas - 了解日期是否包含在预定义日期列表中
- flutter - Gradle 失败 评估项目 ':app' >com/google/common/util/concurrent/settablefuture 时出现问题
- javascript - 如何使用 react.js 计算购物车中产品的总价格
- python - 转置或旋转数据
- javascript - 键入时搜索,单击时自动完成输入字段
- scala - 未找到操作 - 玩从 2.2 到 2.4 的迁移
- jmeter - 如何根据 Jmeter 中的某些条件从响应中提取两个值?
- nsis - NSIS 执行系统命令
- c++ - 对 `__imp___glutInitWithExit' 和其他的未定义引用,但库已链接