store captured image in MySQL database with Python and OpenCV

半腔热情 提交于 2021-02-08 11:10:51

问题


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()

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?


回答1:


You want:

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

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.

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).



来源:https://stackoverflow.com/questions/47906056/store-captured-image-in-mysql-database-with-python-and-opencv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!