pageauc / speed-camera

A Unix, Windows, Raspberry Pi Object Speed Camera using python, opencv, video streaming, motion tracking. Includes a Standalone Web Server Interface, Image Search using opencv template match and a whiptail Admin Menu Interface Includes picam and webcam Plugins for motion track security camera configuration including rclone sync script. watch-app allows remotely controller camera configuration from a remote storage service name. Uses sqlite3 and gnuplot for reporting. Recently added openalpr license plate reader support.
Apache License 2.0
985 stars 172 forks source link

larger imgae and hight resolution #40

Closed ZIKO94ZIKO closed 5 years ago

ZIKO94ZIKO commented 5 years ago

Hi sir, i hope you are doing well, my problem it about the resolution , when i use my laptop camera the red area of detecting is large Screenshot from 2019-09-24 12-27-04 but when i use me camera IP the area very small : Screenshot from 2019-09-24 12-25-27

pageauc commented 5 years ago

What is the resolution of the IP camera. The boundaries of the motion rectangle may have to be changed. x_left = 25 x_right = 295 y_upper =75 y_lower =185

eg increase x_right and y_lower. Just don't make dimensions too big since opencv uses this area for motion tracking and larger dimensions means more processing and slower fps

or change the resolution of the IP camera to reduced it.

Are all the other settings for both the same?

On Tue, Sep 24, 2019 at 7:33 AM ZIKO94ZIKO notifications@github.com wrote:

Hi sir, i hope you are doing well, my problem it about the resolution , when i use my laptop camera the red area of detecting is large [image: Screenshot from 2019-09-24 12-27-04] https://user-images.githubusercontent.com/52079137/65507961-01b4e000-dec7-11e9-8c6b-cc03976ae26c.png but when i use me camera IP the area very small : [image: Screenshot from 2019-09-24 12-25-27] https://user-images.githubusercontent.com/52079137/65508017-227d3580-dec7-11e9-9a00-19d7b2203500.png

— You are receiving this because you are subscribed to this thread. Reply to this email directly, view it on GitHub https://github.com/pageauc/speed-camera/issues/40?email_source=notifications&email_token=ABNPKZBMD3CD4DSTMWWVQCTQLH3INA5CNFSM4IZ6NT6KYY3PNVWWK3TUL52HS4DFUVEXG43VMWVGG33NNVSW45C7NFSM4HNJHFJA, or mute the thread https://github.com/notifications/unsubscribe-auth/ABNPKZBSLOOCKRX4U4KVSL3QLH3INANCNFSM4IZ6NT6A .

-- See my YouTube Channel at http://www.youtube.com/user/pageaucp

ZIKO94ZIKO commented 5 years ago

` import numpy as np import cv2 from openalpr import Alpr

RTSP_SOURCE = 'rtsp://face:Face12345@10.15.19.201:554/live.sdp' WINDOW_NAME = 'openalpr' FRAME_SKIP = 15

def open_cam_rtsp(uri, width=1280, height=720, latency=2000): gst_str = ('rtspsrc location={} latency={} ! ' 'rtph264depay ! h264parse ! omxh264dec ! nvvidconv ! ' 'video/x-raw, width=(int){}, height=(int){}, format=(string)BGRx ! ' 'videoconvert ! appsink').format(uri, latency, width, height) return cv2.VideoCapture(gst_str, cv2.CAP_GSTREAMER)

def main(): 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')

cap = open_cam_rtsp(RTSP_SOURCE)
if not cap.isOpened():
    alpr.unload()
    sys.exit('Failed to open video file!')
cv2.namedWindow(WINDOW_NAME, cv2.WINDOW_AUTOSIZE)
cv2.setWindowTitle(WINDOW_NAME, 'OpenALPR video test')

_frame_number = 0
while True:
    ret_val, frame = cap.read()
    if not ret_val:
        print('VidepCapture.read() failed. Exiting...')
        break

    _frame_number += 1
    if _frame_number % FRAME_SKIP != 0:
        continue
    cv2.imshow(WINDOW_NAME, frame)

    results = alpr.recognize_ndarray(frame)
    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']))

    if cv2.waitKey(1) == 27:
        break

cv2.destroyAllWindows()
cap.release()
alpr.unload()

if name == "main": main() `

ZIKO94ZIKO commented 5 years ago

yes its work sir , please tell me how can be integrate this code with your project :its about detection in time real the ALPR .

pageauc commented 5 years ago

speed camera has a sqlite database that stores results of each image taken. This database can be queried to find unprocessed images. I have updated speed-cam.py to version 9.91 to alter the speed table in data/speed_cam.db to add a status column. This can be used to process speed camera images using another eg ALPR script that updates the speed_cam.db speed table status field with something like date/time or just text like done. Then you can query for status is null to get a list of image_paths that have not been processed.

In the ALPR script you would just need to query the speed_cam.db for status null periodically and process those images and change status to 'done' or any text as desired.

Should work OK

Note use menubox.sh UPGRADE feature to upgrade to release 9.91 that will add the status column to the existing database

You will need to learn a little about sqlite3 but this approach should work and everything can be handled by your ALPR script by setting the query to check for a null status and put into a list, then process the list using the image_path and once completed update the status field to 'done' or any other text you prefer, for the idx key of the image

hope this helps Claude ...

On Tue, Sep 24, 2019 at 10:23 AM ZIKO94ZIKO notifications@github.com wrote:

yes its work sir , please tell me how can be integrate this code with your project :its about detection in time real the ALPR .

— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/pageauc/speed-camera/issues/40?email_source=notifications&email_token=ABNPKZGUAOXZNV6JZN2XNMDQLIPHTA5CNFSM4IZ6NT6KYY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOD7ORNIQ#issuecomment-534582946, or mute the thread https://github.com/notifications/unsubscribe-auth/ABNPKZCYC52WPAYXLWVLG7DQLIPHTANCNFSM4IZ6NT6A .

-- See my YouTube Channel at http://www.youtube.com/user/pageaucp

pageauc commented 5 years ago

The code below might help you out. I have tested it but don't have alpr installed but the sql commands work and you should be able to do what you are trying to do. Not much error checking but this can be added as necessary. I recommend you write licence plates to a database table or to a file. Let me know how you make out Note you will need the latest copy of speed_cam.py that adds the status field to the data/speed_cam.db speed table Regards Claude ...

#!/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()
ZIKO94ZIKO commented 5 years ago

Hello Sir ،، All words are not enough to thank you 😀 :+1: , i followed your reply , step by step and :
1) I put your script in last comment https://github.com/pageauc/speed-camera/issues/40#issuecomment-534801357 in function_name=main1() and filename=openalper_camera.py 2)i put this function in script speed_cam.py like that: image

3)after running speed_ cam.py : python speed_cam.py i find this results:

image

results:

---> the openalper_camera.py (ALPR program ) work and show the result in the console , ---> the camera is working , but the show gui_windows doesn't work ---> i can't stop the program when i tap (Ctrl+c) , at every turn i should kill the process by the command kill PID ---> i didn't found the result of alpr in data base speed_cam.db

please help me if you have a suggestion for resolving this issues, Best regards

pageauc commented 5 years ago

I cannot see the code that you supplied. Do NOT combine the two scripts into one. Run the speed-cam.py as supplied (latest 9.91 version). This can run in the background or separate terminal session. In a second terminal session Run the alpr script I supplied. This will get information from the speed-cam.py database and process for plate info. This will allow speed-cam.py to run in a separate process from the alpr script I supplied and avoid conflicts.

On Thu, Sep 26, 2019 at 6:36 AM ZIKO94ZIKO notifications@github.com wrote:

Hello Sir ،، All words are not enough to thank you 😀 👍 , i followed your reply , step by step and :

  1. I put your script in last comment https://github.com/pageauc/speed-camera/issues/40#issuecomment-534801357 http://url in function_name=main1() and filename=openalper_camera.py 2)i put this function in script speed_cam.py like that: [image: image] https://user-images.githubusercontent.com/52079137/65680349-aca3d600-e04e-11e9-983b-ea8021c08e78.png

3)after running speed_ cam.py : python speed_cam.py i find this results:

[image: image] https://user-images.githubusercontent.com/52079137/65680668-53887200-e04f-11e9-95bb-b1eec2d0b086.png

results:

---> the openalper_camera.py (ALPR program ) work and show the result in the console , ---> the camera is working , but the show gui_windows doesn't work ---> i can't stop the program when i tap (Ctrl+Z) , at every turn i should kill the process by the command kill PID ---> i didn't found the result of alpr in data base speed_cam.db

please help me if you have a suggestion for resolving this issues, Best regards

— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/pageauc/speed-camera/issues/40?email_source=notifications&email_token=ABNPKZHJHGALA2RRH4JPXYTQLSGCRA5CNFSM4IZ6NT6KYY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOD7VDZKA#issuecomment-535444648, or mute the thread https://github.com/notifications/unsubscribe-auth/ABNPKZBLMLNWYE2ZN7KZGN3QLSGCRANCNFSM4IZ6NT6A .

-- See my YouTube Channel at http://www.youtube.com/user/pageaucp

pageauc commented 5 years ago

Looks like your webcam cannot connect. Not sure if you are trying to connect to your rtsp IP camera or not. Check connection. Also you may need to add the rtsp connection code per function open_cam_rtsp

There are two while loops in the code I provided. I suggest you put a try except KeyboardInterrupt around the code to trap ctrl-c and allow easier exit. The code I provided was just a sample. You will need to work with it to add error checking and other features. Claude ...

ZIKO94ZIKO commented 5 years ago

hi Sir ; i hope you are very well. thank u for your clearly answer,Unfortunately I still have problems: 1)I want running your program in the background by bash menubox.sh ( after UPGRADE) click START i found this issue:
image 2) i want to change status="done" by status=Result_ALPR i mean each image with ALPR in the case status i insert this line in script openalpr_camera.py as below but it doesn't work :

import sys import numpy as np import cv2 from openalpr import Alpr import csv import time import sqlite3 import os from threading import Thread from time import sleep

RTSP_SOURCE = 'rtsp://admin:admin12345@192.168.1.64:554/live.sdp'

WINDOW_NAME = 'openalpr'

FRAME_SKIP = 15

DB_FILE = '/home/zakaria/Desktop/speed_camera/data/speed_cam.db' SPEED_DIR = '/home/zakaria/Desktop/speed_camera' # path to speed-camera folder def main1(): alpr = Alpr('us', 'Tx2.conf', '/home/zakaria/Desktop/speed_camera/openalpr/runtime_data') if not alpr.is_loaded(): print('Error loading OpenALPR') sys.exit(1) alpr.set_top_n(3)

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]
            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= "%s" WHERE idx="{}"'''.format(row_index)
        status =results
        db_conn.execute(sql_cmd)`

db_conn.close()
alpr.unload()

if name == "main": try: main1() except KeyboardInterrupt: print('Interrupted') try: sys.exit(0) except SystemExit: os._exit(0)

pageauc commented 5 years ago

upgrade to the latest version of speed-camera using the menubox.sh UPGRADE menu pick. This should upgrade to ver 9.97 There is NO message in speed-cam.py that shows Failed to start message. Make sure speed-cam.py is running and saving images.

Once that is working Code you show seems to be confusing and not indented properly so it will not work. Try this code in a second terminal session with speed camera running in another terminal session or in the background.

Run attached code. It will read the speed_cam.db file default is '/home/pi/speed-camera/data/speed_cam.db' change the DB_FILE path location if necessary. and also SPEED_DIR. Just make sure they match your setup

run the attached alpr-speed.py file. It will read the specified sqlite3 speed_cam.db and query speed table status = '' and return inx and path to speed image. This will then be processed by alpr per your alpr parameters.

Note alpr-speed.py is just sample code so you will need to add extra error checking or logic as required for you needs. You will need to be familiar with python programming.

If this does not work the recheck that speed camera is working OK. You may want to delete speed-camera folder and do a fresh install.

You can install alpr-speed.py in the speed-camera folder. Make sure alpr is working OK and settings in alpr-speed.py are correct.

Regards Claude ...

Just in case there is an attachment problem here is the alpr-speed.py code below

!/usr/bin/env python

import numpy as np import cv2 from openalpr import Alpr import sqlite3 import sys import time import os

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() try: 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 on 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']))

        # Set speed_cam.db speed table status field to '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) except KeyboardInterrupt: print("User exited with ctr-c") finally: db_conn.close() alpr.unload()

On Fri, Sep 27, 2019 at 7:23 AM ZIKO94ZIKO notifications@github.com wrote:

hi Sir ; i hope you are very well. thank u for your clearly answer,Unfortunately I still have problems: 1)I want running your program in the background by bash menubox.sh ( after UPGRADE) click START i found this issue: [image: image] https://user-images.githubusercontent.com/52079137/65765112-358a4280-e11f-11e9-850f-d08e6bc786a8.png 2) i want to change status="done" by status=Result_ALPR i mean each image with ALPR in the case status i insert this line in script openalpr_camera.py as below but it doesn't work :

import sys import numpy as np import cv2 from openalpr import Alpr import csv import time import sqlite3 import os from threading import Thread from time import sleep

RTSP_SOURCE = 'rtsp://admin:admin12345@192.168.1.64:554/live.sdp'

WINDOW_NAME = 'openalpr'

FRAME_SKIP = 15

DB_FILE = '/home/zakaria/Desktop/speed_camera/data/speed_cam.db' SPEED_DIR = '/home/zakaria/Desktop/speed_camera' # path to speed-camera folder def main1(): alpr = Alpr('us', 'Tx2.conf', '/home/zakaria/Desktop/speed_camera/openalpr/runtime_data') if not alpr.is_loaded(): print('Error loading OpenALPR') sys.exit(1) alpr.set_top_n(3)

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]
        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= "%s" WHERE idx="{}"'''.format(row_index)
    status =results
    db_conn.execute(sql_cmd)`

db_conn.close() alpr.unload()

if name == "main": try: main1() except KeyboardInterrupt: print('Interrupted') try: sys.exit(0) except SystemExit: os._exit(0)

— You are receiving this because you modified the open/close state. Reply to this email directly, view it on GitHub https://github.com/pageauc/speed-camera/issues/40?email_source=notifications&email_token=ABNPKZGRKWJVRAFJDYSA3ZTQLXULJA5CNFSM4IZ6NT6KYY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOD7YS57Y#issuecomment-535899903, or mute the thread https://github.com/notifications/unsubscribe-auth/ABNPKZBLYRH7OADLKHIGVFLQLXULJANCNFSM4IZ6NT6A .

-- See my YouTube Channel at http://www.youtube.com/user/pageaucp

!/usr/bin/env python

import numpy as np import cv2 from openalpr import Alpr import sqlite3 import sys import time import os

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() try: 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 on 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']))

        # Set speed_cam.db speed table status field to '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)

except KeyboardInterupt: print("User exited with ctr-c") finally: db_conn.close() alpr.unload()

pageauc commented 5 years ago

I installed openalpr on one of my RPI's

sudo apt-get install openalpr
sudo apt-get install python-openalpr

Also needed to create symbolic link per below

sudo ln -s /usr/share/openalpr/runtime_data/ocr/tessdata/lus.traineddata /usr/share/openalpr/runtime_data/ocr/lus.traineddata

Had to use results = alpr.recognize_file(image_path) This was easier and works OK. I used the default openalpr.conf and runtime_data per alpr = line in code below

Give this a try. Regards Claude ...

#!/usr/bin/env python
from openalpr import Alpr
import sqlite3
import sys
import time
import os

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

alpr = Alpr("us", "/etc/openalpr/openalpr.conf", "/usr/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()
try:
    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)
            # This may have to be tweaked since image is from a file.
            # Do ALPR processing on selected image
            print('Processing %s' % image_path)
            results = alpr.recognize_file(image_path)

            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']))

            # Set speed_cam.db speed table status field to '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)
except KeyboardInterrupt:
    print("User exited with ctr-c")
finally:
    db_conn.close()
    alpr.unload()
ZIKO94ZIKO commented 5 years ago

Hi sir thanks for reply , my issue is just about how put the result of print in database ( column status ) , i know its basic question because i have no idea about sql. when i tried this lines 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'])) sql_cmd = '''UPDATE speed SET status="''' + best_candidate['plate'].upper() + '''" WHERE idx="{}"'''.format(row_index) db_conn.execute(sql_cmd) db_conn.commit() its work its scan the ALPR and put it in status , but doesn't scan all data , this image represent display of data set after running a program

image

pageauc commented 5 years ago

Try downloading this version of script. Make a backup of any previous copy that you do not want to loose. I don't have any images with license plates to test. Also not sure how multiple plate entries will be handled or just last entry. results data is stored in a python dictionary structure.

wget -O alpr-speed.py https://raw.githubusercontent.com/pageauc/speed-camera/master/alpr-speed.py
pageauc commented 5 years ago

here is sample dictionary structure from sample alpr image

{
    "data_type": "alpr_results",
    "epoch_time": 1569613729719,
    "img_height": 358,
    "img_width": 636,
    "results": [
        {
            "plate": "EA7THE",
            "confidence": 91.05777,
            "region_confidence": 0,
            "region": "",
            "plate_index": 0,
            "processing_time_ms": 72.657066,
            "candidates": [
                {
                    "matches_template": 0,
                    "plate": "EA7THE",
                    "confidence": 91.05777
                },
                {
                    "matches_template": 0,
                    "plate": "EA7TBE",
                    "confidence": 84.132973
                },
                {
                    "matches_template": 0,
                    "plate": "EA7T8E",
                    "confidence": 83.008331
                },
                {
                    "matches_template": 0,
                    "plate": "EA7TRE",
                    "confidence": 82.786911
                },
                {
                    "matches_template": 0,
                    "plate": "EA7TE",
                    "confidence": 82.596092
                },
                {
                    "matches_template": 0,
                    "plate": "EA7TME",
                    "confidence": 80.29081
                },
                {
                    "matches_template": 0,
                    "plate": "EA7TH6",
                    "confidence": 77.004456
                },
                {
                    "matches_template": 0,
                    "plate": "EA7THB",
                    "confidence": 75.577858
                },
                {
                    "matches_template": 0,
                    "plate": "EA7TH",
                    "confidence": 74.657646
                },
                {
                    "matches_template": 0,
                    "plate": "EA7TB6",
                    "confidence": 70.079651
                },
                {
                    "matches_template": 0,
                    "plate": "EA7T86",
                    "confidence": 68.955009
                },
                {
                    "matches_template": 0,
                    "plate": "EA7TR6",
                    "confidence": 68.733589
                },
                {
                    "matches_template": 0,
                    "plate": "EA7TBB",
                    "confidence": 68.653069
                },
                {
                    "matches_template": 0,
                    "plate": "EA7T6",
                    "confidence": 68.54277
                },
                {
                    "matches_template": 0,
                    "plate": "EA7TB",
                    "confidence": 67.732849
                },
                {
                    "matches_template": 0,
                    "plate": "EA7T8B",
                    "confidence": 67.528419
                },
                {
                    "matches_template": 0,
                    "plate": "EA7TRB",
                    "confidence": 67.306992
                },
                {
                    "matches_template": 0,
                    "plate": "EA7T8",
                    "confidence": 66.6082
                },
                {
                    "matches_template": 0,
                    "plate": "EA7TR",
                    "confidence": 66.38678
                },
                {
                    "matches_template": 0,
                    "plate": "EA7TM6",
                    "confidence": 66.237488
                },
                {
                    "matches_template": 0,
                    "plate": "EA7T",
                    "confidence": 66.195961
                },
                {
                    "matches_template": 0,
                    "plate": "EA7TMB",
                    "confidence": 64.810905
                },
                {
                    "matches_template": 0,
                    "plate": "EA7TM",
                    "confidence": 63.890686
                }
            ],
            "coordinates": [
                {
                    "y": 157,
                    "x": 208
                },
                {
                    "y": 157,
                    "x": 393
                },
                {
                    "y": 245,
                    "x": 393
                },
                {
                    "y": 245,
                    "x": 208
                }
            ],
            "matches_template": 0,
            "requested_topn": 25
        }
    ],
    "version": 2,
    "processing_time_ms": 431.208374,
    "regions_of_interest": []
pageauc commented 5 years ago

I have updated alpr-speed.py to release ver 1.3. Mostly python format and constant naming changes but more pythonic. You can update using speed-camera menubox.sh and UPGRADE menu pick. alpr-speed.py script still needs to be tested since I am not sure how multiple plates are handled to put them in status column. I know none is put in status if there is no plate data. I guess I will have to see if I can collect some speed-cam.py plate images with multiple plates so I can do some testing. Hopefully this will be useful for others. I know I learned a few things doing this script. Please provide feedback on your testing. Thanks Claude ....

pageauc commented 5 years ago

I have release alpr-speed.py ver 1.5 that is much improved. Can you see if you can test this new version. It should handle multiple plates and post to status field in speed_cam.db. I am planning on adding argparse and putting in parameters to run queries for alpr status data. eg select/sort/where all entries that have plates, all plates for time period, plates that match specific string Etc.

If you can test ver 1.5 and let me know status it would be greatly appreciated. Regards Claude ....

ZIKO94ZIKO commented 5 years ago

Hello Sir , Forgive me for the delay, i tested your code alpr-speed.py version 1.5 its work , I believe it's very helpful also for the others :D . after running dome times give me this error Traceback (most recent call last): File "alpr-speed.py", line 147, in <module> DB_CONN.execute(SQL_CMD) sqlite3.OperationalError: database is locked , i tried to add the timeout = 5 in this line : DB_CONN = sqlite3.connect(DB_FILE , timeout=5) and its work very well, People like you are rare. To have someone loves to help other people like you do is amazing ,Thank you Sir again for everything you’ve done.

pageauc commented 5 years ago

Yes problem is due to db lockout. I put a try except around the execute code that avoids traceback but does not resolve lockout so I am making mods to speed-cam.py to open and close database when the execute sql command is done. This avoids db staying open all the time. Also doing the same for openalpr. This should avoid or reduce instances of db lockout due to two processes writing to same db. Another option is to write alrp data to another table or database and avoid any conflict. If you want you can work on coding this and learn more about python programming. What do you think. Claude ....

On Mon, Sep 30, 2019 at 5:26 AM ZIKO94ZIKO notifications@github.com wrote:

Hello Sir , Forgive me for the delay, i tested your code alpr-speed.py version 1.5 its work , I believe it's very helpful also for the others :D . after running dome times give me this error Traceback (most recent call last): File "alpr-speed.py", line 147, in

DB_CONN.execute(SQL_CMD) sqlite3.OperationalError: database is locked , i tried to add the timeout = 5 in this line : DB_CONN = sqlite3.connect(DB_FILE , timeout=5) and its work very well, People like you are rare. To have someone loves to help other people like you do is amazing ,Thank you Sir again for everything you’ve done. — You are receiving this because you modified the open/close state. Reply to this email directly, view it on GitHub , or mute the thread .

-- See my YouTube Channel at http://www.youtube.com/user/pageaucp

pageauc commented 5 years ago

See ver 1.6 that traps error so avoids trackback but speed-camera still needs work to open db only when writing new row. Currently it keeps db open continuously. Other than that missed records will get processed on another pass of alpr-speed.py Claude ...

On Mon, Sep 30, 2019 at 7:47 AM Claude Pageau pageauc@gmail.com wrote:

Yes problem is due to db lockout. I put a try except around the execute code that avoids traceback but does not resolve lockout so I am making mods to speed-cam.py to open and close database when the execute sql command is done. This avoids db staying open all the time. Also doing the same for openalpr. This should avoid or reduce instances of db lockout due to two processes writing to same db. Another option is to write alrp data to another table or database and avoid any conflict. If you want you can work on coding this and learn more about python programming. What do you think. Claude ....

On Mon, Sep 30, 2019 at 5:26 AM ZIKO94ZIKO notifications@github.com wrote:

Hello Sir , Forgive me for the delay, i tested your code alpr-speed.py version 1.5 its work , I believe it's very helpful also for the others :D . after running dome times give me this error Traceback (most recent call last): File "alpr-speed.py", line 147, in

DB_CONN.execute(SQL_CMD) sqlite3.OperationalError: database is locked , i tried to add the timeout = 5 in this line : DB_CONN = sqlite3.connect(DB_FILE , timeout=5) and its work very well, People like you are rare. To have someone loves to help other people like you do is amazing ,Thank you Sir again for everything you’ve done. — You are receiving this because you modified the open/close state. Reply to this email directly, view it on GitHub , or mute the thread .

-- See my YouTube Channel at http://www.youtube.com/user/pageaucp

-- See my YouTube Channel at http://www.youtube.com/user/pageaucp

ZIKO94ZIKO commented 5 years ago

Sir hope you are doing well , Yes of cause i will try to coding this part to write alrp data to another database .i will do it: for you to Meet your request , and to improve my skill in python programming as you say. about ver 1.6 its work very well thanks .Thank you for your Time^_^

pageauc commented 5 years ago

I have updated speed-cam.py to ver 9.98 and alpr-speed.py to ver 1.7 These changes should greatly reduce db lock issues since I am opening and closing database only when doing transaction and commit.

See changed logic for alpr-speed.py that does a fetchall into a list to minimize time db is open. Please test and let me know. Show output when license plates are found. I would be interested
Thanks Claude.

ZIKO94ZIKO commented 5 years ago

Hello Sir alpr-speed.py ver 1.7 work perfectly ^_^ reading and writing from Database in real time without any bugs or errors, :D about speed-cam.py i have do an update but its give me just version 9.97 : Screenshot from 2019-10-01 11-26-26

pageauc commented 5 years ago

Try upgrade again Also this may be just install version.

Run speed-cam.py with verbose = True and check version displayed when you start

Claude ...

On Tue, Oct 1, 2019 at 6:29 AM ZIKO94ZIKO notifications@github.com wrote:

Hello Sir alpr-speed.py ver 1.7 work perfectly ^_^ reading and writing from Database in real time without any bugs or errors, :D about speed-cam.py i have do an update but its give me just version 9.97 : [image: Screenshot from 2019-10-01 11-26-26] https://user-images.githubusercontent.com/52079137/65954666-6380c700-e43e-11e9-88ce-46f7d27e8a42.png

— You are receiving this because you modified the open/close state. Reply to this email directly, view it on GitHub https://github.com/pageauc/speed-camera/issues/40?email_source=notifications&email_token=ABNPKZHDWMA4BS6PEQEPC3TQMMRCPA5CNFSM4IZ6NT6KYY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOEAAZMBI#issuecomment-536974853, or mute the thread https://github.com/notifications/unsubscribe-auth/ABNPKZGR6BCQCPMYRXOB6NLQMMRCPANCNFSM4IZ6NT6A .

-- See my YouTube Channel at http://www.youtube.com/user/pageaucp

jgandhi19 commented 5 years ago

Where do I go to change the motion detection boundaries that you mention? I don't see a location where I can update the x/y axis to adjust the detection window.

pageauc commented 5 years ago

Motion detection image crop boundaries are now calculated automatically at approx 1568 of speed-cam.py depending on the size of the images. Image stream size is detected (since image can come from an rtsp stream and not from a webcam or picam.

Claude ...

On Thu, Oct 17, 2019 at 8:14 PM jgandhi19 notifications@github.com wrote:

Where do I go to change the motion detection boundaries that you mention?

— You are receiving this because you modified the open/close state. Reply to this email directly, view it on GitHub https://github.com/pageauc/speed-camera/issues/40?email_source=notifications&email_token=ABNPKZGUOKTBN272GUXUS4TQPD5U5A5CNFSM4IZ6NT6KYY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOEBR67LQ#issuecomment-543420334, or unsubscribe https://github.com/notifications/unsubscribe-auth/ABNPKZAY4CRFY7J7VLPY273QPD5U5ANCNFSM4IZ6NT6A .

-- See my YouTube Channel at http://www.youtube.com/user/pageaucp

jgandhi19 commented 5 years ago

Excellent - thank you Claude! Modifying those variables did the trick for me...

pageauc commented 5 years ago

I have released speed-cam.py ver 10.0 including new config.py with comments for overriding motion tracking crop detection area on images. It will be the users responsibility to make sure custom values are within image size.

You can upgrade using menubox.sh UPGRADE menu option. The updated config.py will be named config.py.new See instructions at end of upgrade regarding backup and copy of new config.py

Please test and let me know if OK Claude ...

On Sat, Oct 19, 2019 at 9:31 AM jgandhi19 notifications@github.com wrote:

Excellent - thank you Claude! Modifying those variables did the trick for me...

— You are receiving this because you modified the open/close state. Reply to this email directly, view it on GitHub https://github.com/pageauc/speed-camera/issues/40?email_source=notifications&email_token=ABNPKZEBSO5HVJAUE6LRTI3QPMD2RA5CNFSM4IZ6NT6KYY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOEBXPVRI#issuecomment-544144069, or unsubscribe https://github.com/notifications/unsubscribe-auth/ABNPKZCDHA4B5MFQ7PL2X2LQPMD2RANCNFSM4IZ6NT6A .

-- See my YouTube Channel at http://www.youtube.com/user/pageaucp