使用python从mongodb检索存储的图像 [英] Retrieve stored image from mongodb using python

查看:85
本文介绍了使用python从mongodb检索存储的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我将图像存储在mongo db中.现在我想按文件名从数据库中检索那些图像,并将相同文件名的图像(或像素)存储在数组或列表中.假设有2个文件名为"class1"的图像,则它们应位于一个数组中.

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.

推荐答案

像以前一样创建您的fs变量,并且:

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()

此外,还要对您的代码进行注释:对于循环的每次迭代,重新创建MongoClient和GridFS实例非常慢.在开始循环之前,请创建一次,然后重复使用.

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.

这篇关于使用python从mongodb检索存储的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆