2015-05-14 62 views
0

我使用pygame和python3.4在Odroid電路板中傳輸網絡攝像頭。該服務器在此(提取這個帖子:using pygame to stream over sockets in python error):Pygame網絡攝像頭流媒體客戶端無法使用python 3.4執行

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我得到以下錯誤的客戶端:

Traceback (most recent call last): File "client.py", line 30, in image = pygame.image.fromstring(dataset,(320,240),"RGB") # convert received image from string TypeError: must be bytes, not 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 =','。join(str(v)for v in received),因爲我讀過python3.x中的某個地方,它就是這個。 現在的錯誤行是:image = pygame.image.fromstring(dataset,(320,240),「RGB」)

謝謝!

回答

0

這2條線似乎是明顯的錯誤:

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") 
+0

好了,現在的錯誤是:序項目0:預計字節,字節數組,或者與緩衝接口的對象,STR發現。所以問題仍然存在 – selan

+0

啊,對不起,我急於發佈更正的答案,我複製你的線,並將其固定在兩個地方中的一個。當然,「v」上的「str」調用也必須被刪除。固定在上面。 – jsbueno

+0

很好,它工作正常! – selan

相關問題