Video Chat using Python
Creating Live Streaming Video Chat without voice using CV2 module of Python.
Socket Library from python is used for connecting two nodes or computers. Here we have two nodes server node and client node. In the server node, it accepts the request from the client node using the socket program. client node sends connection requests to the server node until it accepts.
CV2 library from OpenCV used for capturing images and displaying images. Pickle the library used for encoding and decoding captured images. Threading library is used for running functions in parallel. time library is used for sleep mode.
GitHub link:https://github.com/Praneeth102/video_chat.git
Server Program:
import cv2
import socket
import time
import pickle
import threading
This is a server node it needs to accept request from the client node.
p1=socket.socket()
p1.setsockopt(socket.SOL_SOCKET ,socket.SO_REUSEADDR,1)
p1_port=1485
ip=””
p1.bind((ip,p1_port))
p1.listen()
p1_s,p1_addr=p1.accept()
print(p1_addr)
It accepts the request from the client node and creates a connection between them.
def recvimage():
i=0
while True:
time.sleep(0.2)
try:
data=p1_s.recv(10000000)
try:
ima=pickle.loads(data)
image=cv2.imdecode(ima,cv2.IMREAD_COLOR)
if image is not None:
#print(image)
print(image.shape)
cv2.imshow(‘2nd_per’,image)
if cv2.waitKey(100) == 13:
break
except:
pass
except:
pass
cv2.destroyAllWindows()
The above function receives images from the sender and decodes that image and then it displays the image. we are handling exception cases if sometimes data doesn’t receive.
def sendimage():
cap=cv2.VideoCapture(0)
while True:
time.sleep(0.2)
ret,pic=cap.read()
print(pic.shape)
ret,buffer=cv2.imencode(‘.jpg’,pic.reshape(480,640,3))
encodimage=pickle.dumps(buffer)
p1_s.send(encodimage)if cv2.waitKey(10)==13:
break
cv2.destroyAllWindows()
The above function sends the captured image from the server node to the client node in the encoded format.
recev=threading.Thread(target=recvimage)
sendd=threading.Thread(target=sendimage)recev.start()
sendd.start()
The above code runs functions in parallel and sends and receives images.
Client Node:
Most of the code is same in the client node, but only we need to make a change at socket code for sending a connection request.
s=socket.socket()
ip=”192.168.31.80"
port=1485
s.connect((ip,port))
Here is the received image from the client node:-