python中SQLite数据库opencv处理图片的保存与导出

python中SQLite数据库opencv处理图片的保存与导出

1.建立数据库连接
下面的代码都以函数形式展示:

#创建
def creat():
    #创建或者连接数据库
    conn = sqlite3.connect('myInfo.db')
    #在数据库中创建一个表(序号,图片)
    sql = '''Create table students(id int,img blob)'''
    cursor = conn.cursor()
    #执行sql指令
    cursor.execute(sql)
    cursor.close()
    conn.close()#关闭数据库连接

2.在数据库中保存opencv处理的图片
opencv中的图片类型为<class ‘numpy.ndarray’>,保存到数据库中为<class ‘bytes’>。

#增加SQLite数据库表记录
def addsql():
    #添加两张Lena的图
    img1 = cv2.imread('D:/image_process/image_process/Lena1.jpg')
    img2 = cv2.imread('D:/image_process/image_process/Lena2.jpg')
    # 创建或者连接数据库
    conn = sqlite3.connect('myInfo.db')
    cursor = conn.cursor()    # 增加SQLite数据库表记录
    x1 = (1,img1)
    x2 = (2,img2)
    sql = '''INSERT into students values(?,?)'''
    cursor.execute(sql, x1)
    cursor.execute(sql, x2)
    conn.commit()  # 更新数据库
    cursor.close()
    conn.close()  # 关闭数据库连接

3.查看数据库中图片并导出保存到本地文件夹
下面的函数主要是通过np.frombuffer与reshape将<class ‘bytes’>转换回<class ‘numpy.ndarray’>并保持源图片尺寸大小。

#查询(转换为元组)
def select_tuple():
    # 连接数据库
    conn = sqlite3.connect('myInfo.db')
    cursor = conn.cursor()
    results = cursor.execute('SELECT img from students')
    allstudents = results.fetchall()
    print('查询开始')
    i=0
    for record in allstudents:
        #将字节转换为图片
        image = record[0]
        #格式转换
        img_new = np.frombuffer(image, dtype=np.uint8)
        #数组转换
        img_new1 = img_new.reshape((512, 512, 3))
        #导出保存图片
        cv2.imwrite('D:/image_process/img/{}.jpg'.format(i),img_new1)
        i+=1
    cursor.close()
    conn.close()  # 关闭数据库连接
    print('查询结束')

4.最后附上一个小demo

#定义图片显示函数
def cv_show(name,img):
    cv2.imshow(name,img)
    cv2.waitKey(0)#等待时间
    cv2.destroyAllWindows()
def test():
    #源图
    img = cv2.imread('D:/image_process/image_process/Lena1.jpg')
    print('图片形状:',img.shape)
    print('图片类型:',type(img))
    cv_show('img',img)
    #转换为字节串
    byte = img.tobytes()
    print('数据库类型:',type(byte))
    #再转回图片格式
    img_new = np.frombuffer(byte, dtype=np.uint8)
    img_new1 = img_new.reshape((512, 512,3))
    print('新图片类型:',type(img_new))
    cv_show('img_new',img_new1)
  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值