流媒體視頻,使用此代碼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)
只需從代碼中移除'self.connection.close()'。 'socket'對象已經處理了關閉。不需要關閉整數句柄。 –
您的縮進看起來不正確,但不確定是因爲剪切/粘貼還是真正的錯誤。 – TuanDT
定義'stream_bytes = b'''(字節,不是字符串)。但你嚴重編輯你的問題,這使得答案無效(&評論) –