I am trying to stream a webcam to a pygame window, the problem seems to come from some sort of confusion between string length vs what the receiver is actually receiving. I've looked over everything and cannot see any issue. Here is the error that occurs:
File "VideoRecieve.py", line 34, in <module>
displayImage = pygame.image.fromstring(pixels, (width, height), 'RGB')
ValueError: String length does not equal format and resolution size
Here is the relevant code: VideoRecieve.py
import pygame
import socket
from zlib import decompress
import time
import threading
import numpy as np
(width, height) = (720, 480)
displayWindow = pygame.display.set_mode((width, height))
pygame.display.set_caption('Living Room')
displayWindow.fill((255,255,255))
pygame.display.flip()
running = True
socket = socket.socket()
socket.connect(('127.0.0.1', 5000))
def recieveAll(connection, length):
buffer = b''
while len(buffer) < length:
imageData = connection.recv(length-len(buffer))
if not imageData:
return imageData
buffer += imageData
return buffer
time.sleep(3)
while running:
try:
sizeLength = int.from_bytes(socket.recv(1), byteorder='big')
size = int.from_bytes(socket.recv(sizeLength), byteorder='big')
pixels = decompress(recieveAll(socket, size))
except:
pass
displayImage = pygame.image.fromstring(pixels, (width, height), 'RGB')
displayWindow.blit(displayImage, (0,0))
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
VideoTransmit.py
from socket import socket
from threading import Thread
from zlib import compress
import cv2
import time
import numpy as np
import pygame
width = 720
height = 480
capture = cv2.VideoCapture(0)
capture.set(3, width)
capture.set(4, height)
def captureVideo(connection):
while 'recording':
ret, frame = capture.read()
frame = np.swapaxes(frame, 0, 1)
finalImage = pygame.pixelcopy.make_surface(frame)
pixels = compress(pygame.image.tostring(finalImage, 'RGB'), 1)
size = len(pixels)
sizeLength = (size.bit_length() + 7) // 8
connection.send(bytes([sizeLength]))
sizeBytes = size.to_bytes(sizeLength, 'big')
connection.send(sizeBytes)
connection.sendall(pixels)
def main(host='127.0.0.1', port=5000):
connection = socket()
connection.bind((host, port))
try:
connection.listen(5)
print("Server Started")
while 'connected':
clientConnection, clientAddress = connection.accept()
print("Client connected, ip: ", clientAddress)
thread = Thread(target=captureVideo, args=(clientConnection,))
thread.start()
finally:
connection.close()
if __name__ == "__main__":
main()
Thanks in advance for the assistance!