Fixing, TypeError: a bytes-like object is required, not 'str'

Question:

Streaming video from Raspberry Pi to 192.168.0.6:8081 using this code…

[Edited based on Comments & Daniel]

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('xffxd8')
            last = stream_bytes.find('xffxd9')
            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()

*However I am getting the following errors: (edited) 🙁 *

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('xffxd8')
TypeError: a bytes-like object is required, not 'str'

How do I tackle this ?
(PS: Trying to open a streamed window from pi camera(which works on 192.168.0.6:8081 on my web browser) to my PC with this program)

Asked By: Mohd Salman

||

Answers:

connect_ex returns an integer, which is an error code or 0 if there is no error. You need to read via the socket itself, not on the result of that call.

Also note, as mentioned in the docs, there is no read method; it is call recv.

stream_bytes += self.socket.recv(1024)

Also, as noted in the comments, you don’t need to call self.connection.close, for the same reason.

Answered By: Daniel Roseman
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.