Ask Your Question

Revision history [back]

Python opencv-Writing numpy object data to image file

in opencv we can read in an image using cv2.imread() or np.fromstring(, np.uint8) followed by img = cv2.imdecode(nparr, 0), for my use case I am bound to use :

with open("sample.png", "r") as f:
    nparr = np.fromstring(, np.uint8)
    img = cv2.imdecode(nparr, 0) # And I get a numpy array here

Now I want to reverse the scenario that is, getting a file object of .png format from the given numpy array. So let's assume that I have a numpy array as nparr = np.zeros((200, 200, 3)). Then how can I convert it to a binary string and write it to dest.png ? I used cv2.imencode(".png", img, [cv2.IMWRITE_PNG_COMPRESSION])[1], but it returns a ndarray object as well