使用 python 从 mongodb 中检索存储的图像

Retrieve stored image from mongodb using python

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 数据库中。现在我想通过文件名从数据库中检索这些图像,并将相同文件名的图像(或像素)存储在数组或列表中。假设如果有 2 张文件名为 "class1" 的图像,那么它们应该在一个数组中。

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

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

您还可以查询文件列表,例如:

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

此外,关于您的代码的评论:为循环的每次迭代重新创建 MongoClient 和 GridFS 实例的速度非常慢。在开始循环之前创建它们一次,然后重复使用它们。