热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

从套接字到pygame接收图像数据的问题

我正在尝试将网络摄像头流式传输到pygame窗口,问题似乎出在字符串长度与接收

我正在尝试将网络摄像头流式传输到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()

提前感谢您的帮助!





推荐阅读
author-avatar
杨芷寻找最真的自己
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有