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面向对象类编写细节分析【类,方法,继承,超类,接口等】

本文实例讲述了Python面向对象类编写技术细节。分享给大家供大家参考,具体如下: 类代码编写细节 继续学习类、方法和继承。 class语句 以下是class语句的一般形式: cla...

对python3中pathlib库的Path类的使用详解

对python3中pathlib库的Path类的使用详解

用了很久的os.path,今天发现竟然还有这么好用的库,记录下来以便使用。 1.调用库 from pathlib import 2.创建Path对象 p = Path('D:...

Django model序列化为json的方法示例

本文环境 Python 3.6.5 Django 2.0.4 fix(2018.5.19):最近得知Django 的model基类需要声明为abstract,故在原来的代码加...

利用pyinstaller打包exe文件的基本教程

前言 PyInstaller可以用来打包python应用程序,打包完的程序就可以在没有安装Python解释器的机器上运行了。PyInstaller支持Python 2.7和Python...

Python用 KNN 进行验证码识别的实现方法

Python用 KNN 进行验证码识别的实现方法

前言 之前做了一个校园交友的APP,其中一个逻辑是通过用户的教务系统来确认用户是一名在校大学生,基本的想法是通过用户的账号和密码,用爬虫的方法来确认信息,但是许多教务系统都有验证码,当时...