Here i have a example of server.py code on python for Raspberry pi to capture video from usb camera “A4 Tech” connected to Raspberry pi 4b
import cv2
import socket
import struct
import pickle
import logging
logging.basicConfig(level=logging.DEBUG)
def send_frame(client_socket, frame):
# Serialize the frame using pickle
data = pickle.dumps(frame)
# Pack the size of the serialized frame
message_size = struct.pack("Q", len(data))
try:
# Send the size of the serialized frame to the client
client_socket.sendall(message_size)
# Send the serialized frame data to the client
client_socket.sendall(data)
logging.debug(f"Sent frame size: {len(data)} bytes.")
return True
except Exception as e:
logging.error(f"Error sending data: {e}")
return False
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
host = 'IP' # Use the Raspberry Pi's IP address
port = 8000
server_socket.bind((host, port))
server_socket.listen(5)
camera = cv2.VideoCapture(0, cv2.CAP_V4L2) # Use V4L2 backend explicitly
if not camera.isOpened():
logging.error("Failed to open camera")
exit()
camera.set(cv2.CAP_PROP_FRAME_WIDTH, 320)
camera.set(cv2.CAP_PROP_FRAME_HEIGHT, 240)
logging.info('Waiting for client connection...')
try:
while True:
client_socket, addr = server_socket.accept()
logging.info(f'Connected to {addr}')
if client_socket:
try:
while camera.isOpened():
ret, frame = camera.read()
if not ret:
logging.error("Failed to read frame from camera")
break
if not send_frame(client_socket, frame):
break
except Exception as e:
logging.error(f"Error during frame send loop: {e}")
finally:
client_socket.close()
except KeyboardInterrupt:
logging.info("Server stopping")
finally:
camera.release()
server_socket.close()
And here is client.py code to recieve video but it doesnt work
import cv2
import socket
import struct
import pickle
import logging
logging.basicConfig(level=logging.DEBUG)
def receive_frame(client_socket):
data = b""
payload_size = struct.calcsize("Q")
# Receive the size of the incoming frame
while len(data) < payload_size:
packet = client_socket.recv(4096)
if not packet:
logging.error("No payload received. Exiting.")
return None
data += packet
if len(data) < payload_size:
logging.error(f"Incomplete payload size received. Expected size: {payload_size}, received size: {len(data)}. Exiting.")
return None
packed_msg_size = data[:payload_size]
data = data[payload_size:]
msg_size = struct.unpack("Q", packed_msg_size)[0]
logging.debug(f"Expected message size: {msg_size} bytes.")
# Receive the actual frame data
while len(data) < msg_size:
packet = client_socket.recv(4096)
if not packet:
logging.error(f"Incomplete data received. Expected size: {msg_size}, received size: {len(data)}. Exiting.")
return None
data += packet
if len(data) != msg_size:
logging.error(f"Data received does not match expected size. Expected: {msg_size}, Got: {len(data)}")
return None
try:
frame_data = pickle.loads(data)
return frame_data
except pickle.UnpicklingError as e:
logging.error(f"Error deserializing data: {e}")
return None
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = 'Same IP' # Use the Raspberry Pi's IP address
port = 8000
client_socket.connect((host, port))
try:
while True:
frame = receive_frame(client_socket)
if frame is None:
logging.error("No data packet received")
break
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
except Exception as e:
logging.error(f"Error processing data: {e}")
finally:
client_socket.close()
cv2.destroyAllWindows()
Server.py debug “DEBUG:root:Sent frame size: 230564 bytes.” and error in client.py “DEBUG:root:Expected message size: 230564 bytes.
ERROR:root:Data received does not match expected size. Expected: 230564, Got: 231572
ERROR:root:No data packet received”
Maybe someone know how to fix this problem and make this code work
i have ensure the server dynamically calculates and sends the frame size with each frame. This was done by serializing the frame data, packing the size, and sending both the size and data to the client. But it didnt work
Nickvels is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.