使用Python和OpenCV将捕获的图像存储在MySQL数据库中 [英] store captured image in MySQL database with Python and OpenCV

查看:77
本文介绍了使用Python和OpenCV将捕获的图像存储在MySQL数据库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我这里有一段代码,可以从笔记本电脑上的内部网络摄像头捕获图像.有了这个图像,我想直接将其发送到我的MySQL数据库.这是代码.

I have a piece of code here which captures an image from my internal webcam on my laptop. With this image, i would like to directly send it to my MySQL database. here is the code.

import numpy as np
import cv2
import mysql.connector
from mysql.connector import errorcode
from time import sleep
import serial

# Obtain connection string information from the portal
config = {
  'host':'oursystem.mysql.database.azure.com',
  'user':'user',
  'password':'pass',
  'database':'projectdb'
}

try:
   conn = mysql.connector.connect(**config)
   print("Connection established")
except mysql.connector.Error as err:
  if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
    print("Something is wrong with the user name or password")
  elif err.errno == errorcode.ER_BAD_DB_ERROR:
    print("Database does not exist")
  else:
    print(err)

cursor = conn.cursor()
cursor.execute("CREATE TABLE if not exists Camera (img BLOB);")
cap = cv2.VideoCapture(0)

# Check if the webcam is opened correctly
if not cap.isOpened():
    raise IOError("Cannot open webcam")

frame = cap.read()[1]
cursor.execute("INSERT INTO Camera (img) VALUES %s",frame)
cap.release()

正如你们所看到的,我试图将捕获并存储在变量'frame'中的图像直接发送到我的数据库,但是它不起作用.有什么想法吗?

As you guys can see, I am trying to directly send the image that is captured and stored in the variable 'frame' to my database, but it isn't working. Any ideas?

推荐答案

您要:

cursor.execute("INSERT INTO Camera (img) VALUES(%s)",(frame,))

话虽如此,将图像存储在SQL数据库中很少是一个好主意-但是,如果您确实想这样做,则至少要在表中添加一个主键.

This being said, storing images in a SQL database is seldom a good idea - but if you really want to do so, at least add a primary key to your table.

根据您的评论,看起来 frame numpy.ndarray .您的数据库连接器不知道如何将每种python类型转换为数据库可以理解的内容,因此您必须手动将 frame 转换为字节字符串(其中的 bytes Python3,Python2中的 str ).

EDIT : from your comments, it looks like frame is a numpy.ndarray. Your database connector does not know how to convert each and any python type to something the database will understand, so you have to manually convert your frame to a byte string (bytes in Python3, str in Python2).

这篇关于使用Python和OpenCV将捕获的图像存储在MySQL数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆