python cv2 load image from binary

Issue

I’m new to cv2, I know that when I need to load an image from a file i use:

img = cv2.imread(IMG_PATH)

but I already have the image in binary format from the database.
how can I get the same result but from binary not from file path?

Solution

The following code demonstrates how to do it. Since cv2 expects images to be represented in the BGR color channel order, you have to swap the red and blue channel in a typical RGB image (can be done using cvtColor):

import requests
import cv2
import numpy as np

# just to get a sample image
img = requests.get('https://unsplash.it/id/767/500/300').content  # bytestring

img_buf = np.asarray(bytearray(img), dtype='uint8')
cv2_img = cv2.imdecode(img_buf, cv2.IMREAD_UNCHANGED)
cv2_img = cv2.cvtColor(cv2_img, cv2.COLOR_BGR2RGB)

Result:

enter image description here

Answered By – asdf

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published