如何通过虚拟摄像机将OpenCV视频馈送到Python ?



我正在尝试从我的物理摄像机发送视频馈送到Python中的虚拟摄像机,以便我可以对其执行某些效果。

这是我到目前为止的代码:

import pyvirtualcam
import numpy as np

cam = pyvirtualcam.Camera(width=1280, height=720, fps=30)
cvCam = cv2.VideoCapture(0)
while True:
try:
_, frame = cvCam.read()

cam.send(frame)
cam.sleep_until_next_frame()
except KeyboardInterrupt:
cam.close()
cvCam.close()
break
print("Done")

在我运行这段代码之后,我得到了一个错误,说我还需要添加一个alpha通道。我从这篇文章中复制了一些代码。这是我的新代码,为代码添加了一个alpha通道:

import pyvirtualcam
import numpy as np

cam = pyvirtualcam.Camera(width=1280, height=720, fps=30)
cvCam = cv2.VideoCapture(0)
while True:
_, frame = cvCam.read()
b_channel, g_channel, r_channel = cv2.split(frame)
alpha_channel = np.ones(b_channel.shape, dtype=b_channel.dtype) * 50
frame = cv2.merge((b_channel, g_channel, r_channel, alpha_channel))
cam.send(frame)
cam.sleep_until_next_frame()
print("Done")

在运行这段代码后,它只是突然退出程序,没有任何错误消息,即使它是在while True循环中。我无法调试这个问题。有什么问题吗?

你可能有不匹配的帧大小从你的源与虚拟凸轮。目前这会导致硬崩溃(参见https://github.com/letmaik/pyvirtualcam/issues/17)。

解决方案是查询源网络摄像头的宽度和高度,并使用它来初始化虚拟摄像头。在https://github.com/letmaik/pyvirtualcam/blob/main/examples/webcam_filter.py上的webcam_filter.py样本显示了如何做到这一点。

约:

cvCam = cv2.VideoCapture(0)
width = int(cvCam.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cvCam.get(cv2.CAP_PROP_FRAME_HEIGHT))
with pyvirtualcam.Camera(width=width, height=height, fps=30) as cam:
...

最新更新