Thanoj Hansana
Thanoj Hansana

Reputation: 1

I want to output video as the virtual cam in python

I write a script for share video from laptop to laptop though the network. I want to out put my receiving video as the virtual cam. please help me.

import cv2, socket, numpy, pickle
def camera(ip2):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  
    ip = ip2  
    port = 2323  # Server Port Number to identify the process that needs to recieve or send packets
    s.bind((ip, port)) 
    while True:
        x = s.recvfrom(100000000)  
        clientip = x[1][0]  
        data = x[0] 
        data = pickle.loads(data)  
        data = cv2.imdecode(data, cv2.IMREAD_COLOR)  
        cv2.imshow('my pic', data)  # Show Video/Stream
        if cv2.waitKey(10) == 13:
            break
    cv2.destroyAllWindows()
def main():
    a = input('Enter IP Address')
    camera(a)

main()

I want to output my receiving video as the virtual cam.

Upvotes: 0

Views: 252

Answers (1)

Noname NoSurname
Noname NoSurname

Reputation: 404

import cv2, socket, numpy, pickle
import pyvirtualcam
from pyvirtualcam import PixelFormat

def camera(ip2):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  
    ip = ip2  
    port = 2323  # Server Port Number to identify the process that needs to receive or send packets
    s.bind((ip, port)) 

    # Initialize virtual camera. Default is 640x480 @ 20fps
    with pyvirtualcam.Camera(width=640, height=480, fps=20, fmt=PixelFormat.BGR) as cam:
        while True:
            x = s.recvfrom(100000000)  
            clientip = x[1][0]  
            data = x[0] 
            data = pickle.loads(data)  
            data = cv2.imdecode(data, cv2.IMREAD_COLOR)  
            
            # Ensure the image fits your virtual cam resolution. You might need to resize it with cv2.resize
            frame = cv2.resize(data, (640, 480))

            # Flip frame to RGB format and send to virtual cam
            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            cam.send(frame)

            # Break loop with enter key
            if cv2.waitKey(10) == 13:
                break

        cv2.destroyAllWindows()

def main():
    a = input('Enter IP Address')
    camera(a)

main()

Please note that pyvirtualcam depends on a native library that creates the actual virtual camera device. You might need to install additional software for this, depending on your operating system:

On Windows, you need OBS VirtualCam 2.0.4 or later. You can download it from the OBS project website. On macOS, you need CamTwist. You can download it from the CamTwist website. On Linux, you need v4l2loopback. You can install it from your package manager, e.g., sudo apt install v4l2loopback-dkms on Ubuntu. You will also need to load the module with sudo modprobe v4l2loopback before running your script. To make this change permanent, you can add v4l2loopback to /etc/modules.

Upvotes: 0

Related Questions