Retrieve stored image from mongodb using python

大城市里の小女人 提交于 2019-12-02 10:06:43

问题


from pymongo import MongoClient
from bson.objectid import ObjectId
import numpy as np
import gridfs 

import os,os.path
i=0
try:
    for file in os.listdir("/Users/sarthakgupta/Desktop/sae/Images"):
        if (file.endswith(".png") | file.endswith(".jpg")):
            filename = "/Users/sarthakgupta/Desktop/sae/Images/"+file
            datafile =  open(filename,"rb")
            thedata = datafile.read()
            datafile.close()


            c = MongoClient()
            i=i+1
            db = c.trial5
            fs = gridfs.GridFS(db)
            t = "class"+str(i)


            stored = fs.put(thedata,filename=q)

except IOError:
    print("Image file %s not found" %datafile)
    raise SystemExit

I stored image in a mongo db . Now i want to retrieve those images from database by the filename and to store the image(or pixels) of same filename in an array or list. Suppose if there is 2 images with filename "class1",then they should be in one array.


回答1:


Create your fs variable like before, and:

data = fs.get_last_version(filename).read()

You could also query for a list of files like:

from bson import Regex
for f in fs.find({'filename': Regex(r'.*\.(png|jpg)')):
    data = f.read()

Also, a comment about your code: it's very slow to recreate the MongoClient and GridFS instances for every iteration of your loop. Create them once before you start looping, and reuse them.



来源:https://stackoverflow.com/questions/42276665/retrieve-stored-image-from-mongodb-using-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!