Search code examples
opencvpython-imaging-libraryflask-socketio

Getting error - 'PngImageFile' object has no attribute 'shape' on transferring video frames from client to flask server using Socketio


My application is to switch on cam on the client-side, take the frame, perform the ML process on it in the backend and throw it back to the client.

This part of the code (in bold) is throwing error - PngImageFile' object has no attribute 'shape'.

This code line has a problem - frame = imutils.resize(pimg, width=700)

I guess some processing is not in the right format. Please guide

@socketio.on('image')
def image(data_image):
    sbuf = io.StringIO()
    sbuf.write(data_image)

    # decode and convert into image
    b = io.BytesIO(base64.b64decode(data_image))
    pimg = Image.open(b)

    # Process the image frame
    frame = imutils.resize(**pimg,** width=700)
    frame = cv2.flip(frame, 1)
    imgencode = cv2.imencode('.jpg', frame)[1]

    # base64 encode
    stringData = base64.b64encode(imgencode).decode('utf-8')
    b64_src = 'data:image/jpg;base64,'
    stringData = b64_src + stringData

    # emit the frame back
    emit('response_back', stringData)

Solution

  • The problem is that pimg is in PIL image format. While imutils.resize function expects the image in Numpy array format. So, after pimg = Image.open(b) line you need to convert the PIL image to Numpy array like below:

    pimg = np.array(pimg)
    

    For this you have to import numpy library like below:

    import numpy as np