我正在使用pygame和python3.4在Odroid板上流式传输网络摄像头。服务器是这个(摘自这篇文章:using pygame to stream over sockets in python error):
import socket
import pygame
import pygame.camera
import sys
import time
port = 5000
pygame.init()
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind(("",port))
serversocket.listen(1)
pygame.camera.init()
webcam = pygame.camera.Camera("/dev/video1",(320,240))
webcam.start()
while True:
connection, address = serversocket.accept()
image = webcam.get_image() # capture image
data = pygame.image.tostring(image,"RGB") # convert captured image to string, use RGB color scheme
connection.sendall(data)
time.sleep(0.1)
connection.close()
服务器在python和python 3.4中运行正常。 但是当我使用python 3.4执行客户端时,我收到以下错误:
追踪(最近一次通话): 文件“client.py”,第30行,在 image = pygame.image.fromstring(dataset,(320,240),“RGB”)#转换从字符串接收的图像 TypeError:必须是字节,而不是str
客户端如下:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import socket
import pygame
import sys
host = "192.168.45.103"
port=5000
screen = pygame.display.set_mode((320,240),0)
while True:
clientsocket=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket.connect((host, port))
received = []
# loop .recv, it returns empty string when done, then transmitted data is completely received
while True:
#print("esperando receber dado")
recvd_data = clientsocket.recv(230400)
if not recvd_data:
break
else:
received.append(recvd_data)
#dataset = ''.join(received)
dataset = ','.join(str(v) for v in received)
image = pygame.image.fromstring(dataset,(320,240),"RGB") # convert received image from string
screen.blit(image,(0,0)) # "show image" on the screen
pygame.display.update()
# check for quit events
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
我为dataset =','更改了line dataset =''。join(收到)。join(str(v)for v in received)因为我读了somwhere,在python3.x中它就是这个。 现在的错误行是:image = pygame.image.fromstring(dataset,(320,240),“RGB”)
谢谢!
答案 0 :(得分:0)
这两行似乎是完全错误的:
dataset = ','.join(received)
image = pygame.image.fromstring(dataset,(320,240),"RGB") # convert received
如果dataset
要包含二进制pxel数据,则不应将接收到的字节与“,”连接:它只会将丢失的无关“,”(十进制44)字节添加为垃圾信息您的像素数据 - 前一行,使用“join”与空字符串将起作用(在Python 2.x中),因为调用空字符串,连接只是连接各种数据,这就是您想要的。
在Python3中,二进制数据的处理(例如你正在接收的像素数据)已经与文本处理分开了 - 你在那里使用的'“”空字符串是一个表示空文本的对象 - 这与空的不同来自Python 2.x的字节 - 但你可以简单地用b
作为前缀来表示字节串(这就是你想要的)。
总而言之,尝试使用:
dataset = b''.join(str(v) for v in received)
image = pygame.image.fromstring(dataset,(320,240),"RGB")