9

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?

jtlz2
  • 7,700
  • 9
  • 64
  • 114
mrgloom
  • 20,061
  • 36
  • 171
  • 301

3 Answers3

14

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)
ZdaR
  • 22,343
  • 7
  • 66
  • 87
2

for Python3 use this way:

from scipy import misc
import io

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

Python2 has StringIO.

Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
feech
  • 404
  • 4
  • 15
  • 2
    What on earth is `misc`? :) – jtlz2 Aug 24 '18 at 09:30
  • 1
    good point, jtlz2. I used scipy.misc. I've got it with Anaconda3. Now it's going to be deprecated but the documentation proposes imageio.imread. https://docs.scipy.org/doc/scipy/reference/generated/scipy.misc.imread.html – feech Oct 05 '18 at 00:54
-1

Fetching Images from Url to Jpg

    import requests
    from io import BytesIO

    response = requests.get("https://optse.ztat.net/teaser/ES/CW15_ES_bermuda_men.jpg")
    my_img_In_byts = BytesIO(response.content).read()


    path="C:/Users/XX/Desktop/TryingPython/downloadedPic.jpg"

    my_fprinter = open(path, mode='wb')
    print( my_fprinter .write(my_img_In_byts))
    my_fprinter.close()
    print("Done")