使用Python和OpenCV在MySQL数据库中存储捕获的图像

问题描述 投票:-1回答:1

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

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”中的图像发送到我的数据库,但它无法正常工作。有任何想法吗?

python mysql image opencv
1个回答
0
投票

你要:

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

话虽这么说,将图像存储在SQL数据库中很少是个好主意 - 但如果你真的想这样做,至少要在你的表中添加一个主键。

编辑:从你的评论,它看起来像frame是一个numpy.ndarray。您的数据库连接器不知道如何将每个和任何python类型转换为数据库将理解的内容,因此您必须手动将frame转换为字节字符串(Python3中的bytes,Python2中的str)。

© www.soinside.com 2019 - 2024. All rights reserved.