2017-09-05 27 views
0

流媒體視頻,使用此代碼192.168.0.6:8081 ...TypeError:需要類似字節的對象,而不是'str'如何解決這個問題?從樹莓派

[編輯基於評論&丹尼爾]

import numpy as np 
import cv2 
import socket 


class VideoStreamingTest(object): 
def __init__(self): 

    #self.server_socket = socket.socket() 
    #self.server_socket.bind(('192.168.0.6', 8081)) 
    #self.server_socket.listen(0) 

    #self.connection, self.client_address = self.server_socket.accept() 
    #self.connection = self.connection.makefile('rb') 
    #self.streaming() 
    self.socket = socket.socket() 
    self.connection = self.socket.connect(('192.168.0.6', 8081)) 
    #self.socket.connect(('192.168.0.6', 8081)) 
    self.streaming() 

def streaming(self): 

    try: 
     #print ("Connection from: ", self.client_address) 
     print ("Streaming...") 
     print ("Press 'q' to exit") 

     stream_bytes = b' ' 
     while True: 

      stream_bytes += self.socket.recv(1024) 
      first = stream_bytes.find('\xff\xd8') 
      last = stream_bytes.find('\xff\xd9') 
      if first != -1 and last != -1: 
       jpg = stream_bytes[first:last + 2] 
       stream_bytes = stream_bytes[last + 2:] 
       #image = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8), cv2.CV_LOAD_IMAGE_GRAYSCALE) 
       image = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8), cv2.CV_LOAD_IMAGE_UNCHANGED) 
       cv2.imshow('image', image) 

       if cv2.waitKey(1) & 0xFF == ord('q'): 
        break 
    finally: 
     #self.connection.close() 
     self.socket.close() 

if __name__ == '__main__': 
    VideoStreamingTest() 

*但是我正在以下錯誤:(編輯):(*

Streaming... 
Press 'q' to exit 
Traceback (most recent call last): 
    File "C:/Users/tiger/Desktop/take_the_stream_from_pi.py", line 48, in <module> 
VideoStreamingTest() 
    File "C:/Users/tiger/Desktop/take_the_stream_from_pi.py", line 19, in __init__ 
self.streaming() 
    File "C:/Users/tiger/Desktop/take_the_stream_from_pi.py", line 32, in streaming 
first = stream_bytes.find('\xff\xd8') 
TypeError: a bytes-like object is required, not 'str' 

我該如何解決這個問題? PS:試圖打開從PI攝像頭(這在我的網頁瀏覽器上192.168.0.6:8081作品)流式窗口,我用這個程序PC)

+1

只需從代碼中移除'self.connection.close()'。 'socket'對象已經處理了關閉。不需要關閉整數句柄。 –

+0

您的縮進看起來不正確,但不確定是因爲剪切/粘貼還是真正的錯誤。 – TuanDT

+0

定義'stream_bytes = b'''(字節,不是字符串)。但你嚴重編輯你的問題,這使得答案無效(&評論) –

回答

0

connect_ex返回一個整數,這是一個錯誤代碼或0,如果沒有錯誤。您需要通過套接字本身讀取,而不是通過該調用的結果。

另請注意,正如文檔中提到的,沒有read方法;它叫recv

stream_bytes += self.socket.recv(1024) 

此外,如在評論中指出的那樣,你不需要調用self.connection.close,出於同樣的原因。

+1

更重要的是,'connect_ex'不返回任何類型的連接對象;相反,套接字是否被連接是對象狀態的一部分,這個'connect_ex'變異了。 – chepner

+0

OP再次編輯他的問題。現在問題在於'stream_bytes ='''應該是'stream_bytes = b'''因爲'recv'的輸出是二進制的。 –

相關問題