Search code examples
pythonnumpysocketsopencvtcp

Convert from socket data to numpy array


All welcome.

I'm trying to display a picture sent by sockets.

There is such a code: P.S Yes, yes, I know that this is the worst thing you have seen, but here it is:

while True:
    data = s.recv(BUFFER_SIZE)
    if data:
        print ("received data:", len(data))
        try:
            myfile = open("t.png", 'wb')
            myfile.write(data)
            img = cv2.imread('t.png')
            if img is not None:
                img = cv2.resize(img, (1280, 720))
                cv2.imshow("1", img)
                cv2.waitKey(1)
        except IOError as e:
            print(e)

He opens the file, writes the image there, and then opencv reads this image and shows it.

How can opencv display an image right away?

In order not to burn the picture to disk and read, and immediately show.


Solution

  • This converts the data (string) received from the socket into an OpenCV image:

    img = cv2.imdecode(np.fromstring(data, np.uint8), 1)
    

    The answer in wwii's comment has similar code but more clutter.