使用Python和OpenCV将捕获的图像保存到MySQL数据库

时间:2019-09-27 19:56:20

标签: python mysql opencv

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

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”变量中的图像,但是它不起作用。

请有人帮助我

错误

mysql.connector.errors.ProgrammingError: Failed processing format-parameters; Python 'ndarray' cannot be converted to a MySQL type

1 个答案:

答案 0 :(得分:0)

您可以将图像转换为base64字符串,并将其作为文本字段存储到mysql数据库中。在显示时,您可以base64_decode图像并显示。

https://www.php.net/manual/en/function.base64-decode.php