Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to decode jpg image from memory?

I can read a jpg image from disk via PIL, Python OpenCV, etc. into a numpy array via some built-in functions such as (in the case of OpenCV) arr= cv2.imread(filename).

But how do I decode a jpg in binary format directly from memory?

Use case: I want to put a jpg image into a database in binary format and then read it from the db into memory and decode it to a numpy array.

Is this possible?

like image 825
mrgloom Avatar asked Jun 02 '17 09:06

mrgloom


2 Answers

Assuming that you are storing the image data in your db as a string, you first need to construct a numpy array from that string that can later be converted to an image using cv2.imdecode. For example:

img = cv2.imdecode(np.fromstring(img_data, dtype=np.uint8), cv2.IMREAD_UNCHANGED)
like image 191
ZdaR Avatar answered Oct 18 '22 20:10

ZdaR


for python3 use this way

from scipy import misc
f= open('file.png', 'rb')
fs = f.read()
likefile = io.BytesIO(fs)
face1 = misc.imread(likefile)

python2 has StringIO

like image 1
feech Avatar answered Oct 18 '22 22:10

feech