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


Streaming video from Raspberry Pi to 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(('', 8081))

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

def streaming(self):

        #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'):

if __name__ == '__main__':

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

Press 'q' to exit
Traceback (most recent call last):
  File "C:/Users/tiger/Desktop/", line 48, in <module>
  File "C:/Users/tiger/Desktop/", line 19, in __init__
  File "C:/Users/tiger/Desktop/", 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 on my web browser) to my PC with this program)

Asked By: Mohd Salman



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.