Python实现批量读取图片并存入mongodb数据库的方法示例

yipeiwu_com5年前Python基础

本文实例讲述了Python实现批量读取图片并存入mongodb数据库的方法。分享给大家供大家参考,具体如下:

我的图片放在E:\image\中,然后使用python将图片读取然后,显示一张,存入取一张(可以注释掉显示图片的语句),通过Gridfs的方式存入图片。代码如下:

# --* coding=utf-8 *--
from cStringIO import StringIO
from pymongo import MongoClient
import gridfs
import os
import matplotlib.pyplot as plt
import matplotlib.image as iming
import bson.binary
import numpy as np
if __name__ == '__main__':
  connect = MongoClient('127.0.0.1', 27017) # 创建连接点
  db = connect.mydb
  print db.collection_names()
  imgput = gridfs.GridFS(db)
  dirs = 'G:\image'
  files = os.listdir(dirs)
  for file in files:
    filesname = dirs + '\\' + file
    print filesname
    imgfile=iming.imread(filesname)
    # iming.imsave('s.jpg',imgfile)
    # print type(imgfile),imgfile
    # imgfile.shape()
    plt.imshow(imgfile)
    plt.axis('off')
    plt.show()
    f=file.split('.')
    print f
    datatmp=open(filesname,'rb')
    data=StringIO(datatmp.read())
    content=bson.binary.Binary(data.getvalue())
    # print content
    insertimg=imgput.put(data,content_type=f[1],filename=f[0])
    datatmp.close()

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python常见数据库操作技巧汇总》、《Python数学运算技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

python判断数字是否是超级素数幂

如果一个数字能表示成 p^q,且p是一个素数,q为大于1的正整数,则此数字就是超级素数幂。 param number: 测试该数字是否是超级素数幂 return: 如果不是就返回 F...

你应该知道的python列表去重方法

前言 列表去重是写Python脚本时常遇问题,因为不管源数据来自哪里,当我们转换成列表的方式时,有可能预期的结果不是我们最终的结果,最常见的就是列表中元素有重复,这时候第一件事我们就要做...

Python自动化测试工具Splinter简介和使用实例

Splinter 快速介绍官方网站:http://splinter.cobrateam.info/官方介绍:Splinter is an open source tool for tes...

python算法演练_One Rule 算法(详解)

这样某一个特征只有0和1两种取值,数据集有三个类别。当取0的时候,假如类别A有20个这样的个体,类别B有60个这样的个体,类别C有20个这样的个体。所以,这个特征为0时,最有可能的是类别...

在Django的URLconf中进行函数导入的方法

看下这个 URLconf: from django.conf.urls.defaults import * from mysite.views import hello, curre...