作者:杨芷寻找最真的自己 | 来源:互联网 | 2023-06-14 16:08
我正在尝试将网络摄像头流式传输到pygame窗口,问题似乎出在字符串长度与接收者实际接收到的东西之间有些混淆。我检查了所有内容,看不到任何问题。这是发生的错误:
File "VideoRecieve.py",line 34,in
displayImage = pygame.image.fromstring(pixels,(width,height),'RGB')
ValueError: String length does not equal format and resolution size
以下是相关代码:
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) 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,'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,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()
提前感谢您的帮助!