使用此代码将视频从 Raspberry Pi 流式传输到 192.168.0.6:8081...
[根据评论和丹尼尔编辑]
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 上运行)打开一个流式窗口到我的电脑)
connect_ex
返回一个整数,它是一个错误代码,如果没有错误则返回 0。您需要通过套接字本身进行读取,而不是该调用的结果。
另请注意,如文档中所述,没有
read
方法;这是电话recv
.
stream_bytes += self.socket.recv(1024)
此外,如评论中所述,出于同样的原因,您无需致电
self.connection.close
。