最近做一些数据库调研的工作,目标是实现影像更快的入库、出库、查询,并实现并行访问等操作。

将结果总结成一个mongoImg类,也算是小结吧。

 '''
Created on 2013-8-6
class mongoInsert
@author: tree
'''
__metaclass__ = type import os
from pymongo.database import Database
import time
import gridfs class mongoImg(object):
"""mongoInsert is a class for inserting document """
def __init__(self, database, dir):
"""Create a new instance of :class:mongoInsert
:Parameters:
- `database`: database to use
- `dir` : directory of document
"""
if not isinstance(database, Database):
raise TypeError("database must be an instance of Database")
if len(dir) < 1:
raise TypeError("dir must be an string of directory") # self.__con = Connection()
self.__imgdb = database
self.__imgfs = gridfs.GridFS (self.__imgdb)
self.__dir = dir
self.__filelist=[] #save filepath in list.txt
def __dirwalk(self,topdown=True):
"""traverse the documents of self.__dir and save in self.__filelist
"""
sum=0
self.__filelist.clear() for root,dirs,files in os.walk(self.__dir,topdown):
for name in files:
sum+=1
temp=os.path.join(root,name)
self.__filelist.append(temp)
print(sum) #insert image
def insert(self):
"""insert images in mongodb
"""
self.__dirwalk() tStart = time.time()
for fi in self.__filelist:
with open (fi,'rb') as myimage:
data=myimage.read()
self.__imgfs.put(data, content_type = "jpg", filename =fi) tEnd =time.time ()
print ("It cost %f sec" % (tEnd - tStart)) #get image by filename
def getbyname(self,filename,savepath):
"""get img from mongdb by filename
"""
if len(savepath) < 1:
raise TypeError("dir must be an string of directory")
dataout=self.__imgfs.get_version(filename)
try:
imgout=open(savepath,'wb')
data=dataout.read()
imgout.write(data)
finally:
imgout.close()

使用示例:也可以将数据库连接写在类内部

 from pymongo import Connection
import mongoImg filedir=r'D:\image'
con = Connection()
db = con.imgdb
imgmongo=mongoImg.mongoImg(db,filedir)
imgmongo.insert()

感觉mongodb存储影像切片还是蛮快的,1w多个图片,大约100-200秒左右。

tip:

gridfs.GridFS.put 函数

put(data, **kwargs)
Put data in GridFS as a new file. Equivalent to doing: try:
f = new_file(**kwargs)
f.write(data)
finally
f.close()

在存储读取图像时,犯了低级错误,将open得到的file实例当做数据存储,读取的时候怎么也读不出数据。。。囧

另外以字节流形式读取图像数据比较适合。

pipe = open('/dev/input/js0','rb')

如果以str形式存储的话,可能会出现UnicodeDecodeError错误,貌似是因为图像数据有些超出了python默认编码的存储区间。

ps:初学python 数据库操作也忘得差不多 欢迎大家批评和指正~

mongodb python image 图像存储读取的更多相关文章

  1. mysql python image 图像存储读取

    最近做一些数据库调研的工作,目标是实现影像更快的入库.出库.查询,并实现并行访问等操作. 将结果总结成一个mysqlImg类. 关于mongodb的图像存储,参见http://www.cnblogs. ...

  2. python编码与存储读取数据(数组字典)

    Camp时在python2的编码上坑了不少. 理解pyhon2的编码 python2字符串类型只有两种: str类型:b'xxx'即是str类型, 是编码后的类型,len()按字节计算 unicode ...

  3. Python下opencv使用笔记(一)(图像简单读取、显示与储存)

    写在之前 从去年開始关注python这个软件,途中间间断断看与学过一些关于python的东西.感觉python确实是一个简单优美.easy上手的脚本编程语言,众多的第三方库使得python异常的强大. ...

  4. Scala与Mongodb实践2-----图片、日期的存储读取

    目的:在IDEA中实现图片.日期等相关的类型在mongodb存储读取 主要是Scala和mongodb里面的类型的转换.Scala里面的数据编码类型和mongodb里面的存储的数据类型各个不同.存在类 ...

  5. 浅析MongoDB数据库的海量数据存储应用

    [摘要]当今已进入大数据时代,特别是大规模互联网web2.0应用不断发展及云计算所需要的海量存储和海量计算发展,传统的关系型数据库已无法满足这方面的需求.随着NoSQL数据库的不断发展和成熟,可以较好 ...

  6. VTK序列图像的读取[转][改]

    医学图像处理的应用程序中,经常会碰到读取一个序列图像的操作.比如CT.MR等所成的图像都是一个切面一个切面地存储的,医学图像处理程序要处理这些数据,第一步当然是把这些数据从磁盘等外部存储介质中导入内存 ...

  7. MongoDB的地埋空间数据存储、空间索引以及空间查询

    一.关于MongoDB 在众多NoSQL数据库,MongoDB是一个优秀的产品.其官方介绍如下: MongoDB (from "humongous") is a scalable, ...

  8. Python 基于Python从mysql表读取千万数据实践

    基于Python 从mysql表读取千万数据实践   by:授客 QQ:1033553122 场景:   有以下两个表,两者都有一个表字段,名为waybill_no,我们需要从tl_waybill_b ...

  9. mongoDB python 操作

    mongoDB python 操作 import pymongo mongo_client = pymongo.MongoClient(host="127.0.0.1",port= ...

随机推荐

  1. api get

    http://ibi.imim.es/befree/ http://disgenet.org/ http://rest.ensembl.org/ { "variantSetId": ...

  2. quartz_jobs.xml标准配置

    <?xml version="1.0" encoding="UTF-8"?><job-scheduling-data xmlns=" ...

  3. android studio中ListView与SQLite的结合使用

    Da.java public class Db extends SQLiteOpenHelper { public Db(Context context) { super(context, " ...

  4. tp中附件上传文件,表单提交

    public function tianjia(){ $goods=D('Goods'); if(!empty($_POST)){ if($_FILES['f_goods_image']['error ...

  5. win7安装virtualbox

    1.下载软件 VirtualBox-4.3.24-98716-Win.1425444683.exe 2.修改安装路径 3.确定选择下一步 4.下一步 5.yes 6.安装 7.安装完成 到此win7 ...

  6. 爬虫5 html下载器 html_downloader.py

    #coding:utf8 import urllib2 __author__ = 'wang' class HtmlDownloader(object): def download(self, url ...

  7. CentOS6.5 安装Sphinx 配置MySQL数据源

      前提安装完mysql,并创建测试表和数据 DROP TABLE IF EXISTS `documents`; CREATE TABLE IF NOT EXISTS `documents` ( `i ...

  8. 9月23日JavaScript作业----日期时间选择

    作业二:日期时间选择 <div style="width:600px; height:100px;"> <select id="year"&g ...

  9. Java 9.10习题

    <1>设计4个线程对象,两个线程执行减操作,两个线程执行加操作 //================================================= // File Na ...

  10. Nginx报错403 forbidden (13: Permission denied)的解决办法

    由于开发需要,在本地环境中配置了LNMP环境,使用的是Centos 6.5 的yum安装,安装一切正常,但是由于默认网站文件夹比较奇葩,于是把网站文件用mv命令移动到了新的目录,并相应修改了配置文件, ...