首页 > 解决方案 > 如何通过python在数据库中打印consol的结果

问题描述

我想在我的数据库中添加控制台的结果:

 # Do ALPR processing of selected image
            results = alpr.recognize_ndarray(speed_image)
            for i, plate in enumerate(results['results']):
                best_candidate = plate['candidates'][0]
                print('Plate #{}: {:7s} ({:.2f}%)'.format(i, best_candidate['plate'].upper(), best_candidate['confidence']))


        # update speed_cam.db to indicate image processing has been done
            sql_cmd = '''UPDATE speed SET status=" i need to add ressult of print here " WHERE idx="{}"'''.format(row_index)
            db_conn.execute(sql_cmd)
            db_conn.commit()

标签: pythonsqlpython-3.x

解决方案


#!/usr/bin/env python
import numpy as np
import cv2
from openalpr import Alpr
import sqlite3
import sys
import time
import os

# WINDOW_NAME = 'openalpr'
DB_FILE = '/home/pi/speed-camera/data/speed_cam.db'
SPEED_DIR = '/home/pi/speed-camera'   # path to speed-camera folder

alpr = Alpr('tw', 'tx2.conf', '/usr/local/share/openalpr/runtime_data')
if not alpr.is_loaded():
    print('Error loading OpenALPR')
    sys.exit(1)
alpr.set_top_n(3)
#alpr.set_default_region('new')

# Connect to speed_cam.db
try:
    db_conn = sqlite3.connect(DB_FILE)
except sqlite3.Error as err_msg:
    logging.error("Failed: sqlite3 Connect to DB %s", DB_FILE)
    logging.error("Error Msg: %s", err_msg)
    sys.exit(1)

# setup cursor for processing db query rows
db_conn.row_factory = sqlite3.Row
cursor = db_conn.cursor()
while True:
    # run sql query to select unprocessed images from speed_cam.db
    cursor.execute("SELECT idx, image_path FROM speed WHERE status=''")    
    while True:
        row = cursor.fetchone()
        if row is None:
            break
        row_index = (row["idx"])
        row_path = (row["image_path"])
        # create full path to image file to process        
        image_path = os.path.join(SPEED_DIR, row_path)       
        speed_image = cv2.imread(image_path)
        # This may have to be tweaked since image is from a file.
        print('Processing %s' % image_path)

        # Do ALPR processing of selected image
        results = alpr.recognize_ndarray(speed_image)
        for i, plate in enumerate(results['results']):
            best_candidate = plate['candidates'][0]
            # Could add to a database table eg speed_cam.db plate table image_path, plate columns
            print('Plate #{}: {:7s} ({:.2f}%)'.format(i, best_candidate['plate'].upper(), 
                   best_candidate['confidence']))

       # update speed_cam.db to indicate image processing has been done
        sql_cmd = '''UPDATE speed SET status="done" WHERE idx="{}"'''.format(row_index)
        db_conn.execute(sql_cmd)
        db_conn.commit()
    print('Waiting 30 seconds')
    time.sleep(30)

db_conn.close()
alpr.unload()

推荐阅读