TypeError:需要一个类似字节的对象,而不是'str'我该怎么解决这个问题?

时间:2017-09-05 12:07:16

标签: python video stream raspberry-pi3

使用此代码将视频从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)打开流媒体窗口到我的电脑上)

1 个答案:

答案 0 :(得分:0)

connect_ex返回一个整数,这是一个错误代码,如果没有错误则返回0。您需要通过套接字本身读取,而不是通过该调用的结果。

另请注意,正如文档中所述,没有read方法;这是致电recv

stream_bytes += self.socket.recv(1024)

此外,正如评论中所述,出于同样的原因,您无需致电self.connection.close