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)