Search code examples
pythonopencvpng

How to read raw png from an array in python opencv?


I'm streaming a png image from my iPhone to my MacBook over tcp. The MacBook code is from http://docs.python.org/library/socketserver.html#requesthandler-objects. How can the image be converted for use with OpenCV? A png was selected because they are efficient, but other formats could be used.

I wrote a test program that reads the rawImage from a file, but not sure how to convert it:

# Read rawImage from a file, but in reality will have it from TCPServer
f = open('frame.png', "rb")
rawImage = f.read()
f.close()

# Not sure how to convert rawImage
npImage = np.array(rawImage)
matImage = cv2.imdecode(rawImage, 1)

#show it
cv.NamedWindow('display')
cv.MoveWindow('display', 10, 10)
cv.ShowImage('display', matImage)
cv. WaitKey(0)

Solution

  • I figured it out:

    # Read rawImage from a file, but in reality will have it from TCPServer
    f = open('frame.png', "rb")
    rawImage = f.read()
    f.close()
    
    # Convert rawImage to Mat
    pilImage = Image.open(StringIO(rawImage));
    npImage = np.array(pilImage)
    matImage = cv.fromarray(npImage)
    
    #show it
    cv.NamedWindow('display')
    cv.MoveWindow('display', 10, 10)
    cv.ShowImage('display', matImage)
    cv. WaitKey(0)