简体   繁体   English

如何通过虚拟相机将 OpenCV 视频源发送到 Python?

[英]How to send OpenCV video feed to Python via virtual camera?

I'm trying to send a video feed from my physical camera to a virtual camera in Python so I can perform certain effects on it.我正在尝试将视频源从我的物理相机发送到 Python 中的虚拟相机,以便我可以对其执行某些效果。

This is my code so far:到目前为止,这是我的代码:

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")

After I ran this code, I got an error saying that I also needed to add an alpha channel.运行此代码后,我收到一条错误消息,提示我还需要添加 Alpha 通道。 I copied some code from this post.我从这篇文章中复制了一些代码。 This was my new code that added an alpha channel to the code:这是我在代码中添加了 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")

After running this code, it just suddenly exits the program without any error message even though it is in a while True loop.运行此代码后,它只是突然退出程序而没有任何错误消息,即使它处于while True循环中。 I am unable to debug this problem.我无法调试这个问题。 What is the issue?问题是什么?

You probably have mismatching frame sizes from your source vs the virtual cam.您的源与虚拟摄像头的帧大小可能不匹配。 Currently this leads to a hard crash (see also https://github.com/letmaik/pyvirtualcam/issues/17 ).目前这会导致严重崩溃(另请参见https://github.com/letmaik/pyvirtualcam/issues/17 )。

The solution is to query the source webcam width and height and use that to initialize the virtual camera.解决方案是查询源网络摄像头的宽度和高度,并使用它来初始化虚拟摄像头。 The webcam_filter.py sample at https://github.com/letmaik/pyvirtualcam/blob/master/samples/webcam_filter.py shows how to do exactly that. https://github.com/letmaik/pyvirtualcam/blob/master/samples/webcam_filter.pywebcam_filter.py示例显示了如何做到这一点。

Roughly:大致:

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:
   ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM