Python 从套接字接收图像数据到pygame的问题
我试图将网络摄像头传输到pygame窗口,问题似乎来自于字符串长度与接收器实际接收内容之间的某种混淆。我看了所有的东西,没有发现任何问题。以下是发生的错误:Python 从套接字接收图像数据到pygame的问题,python,sockets,opencv,pygame,Python,Sockets,Opencv,Pygame,我试图将网络摄像头传输到pygame窗口,问题似乎来自于字符串长度与接收器实际接收内容之间的某种混淆。我看了所有的东西,没有发现任何问题。以下是发生的错误: File "VideoRecieve.py", line 34, in <module> displayImage = pygame.image.fromstring(pixels, (width, height), 'RGB') ValueError: String length does not equal fo
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
提前感谢您的帮助 您是否确保
len(像素)==width*height
?您是否确保len(像素)==width*height
?
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
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()