class ALPR(ContextEngineBase): # Trained classifier alpr = None; # Top n highest confidence predictions n = 5 def __init__(self, complexity, numInputs, outputClassifier, inputClassifiers, appFieldsDict): ContextEngineBase.__init__(self,complexity, numInputs, outputClassifier, inputClassifiers, appFieldsDict) self.alpr = Alpr("us", "/etc/openalpr/openalpr.conf", "/home/pi/openalpr/runtime_data") if not self.alpr.is_loaded(): print("Error loading OpenALPR") sys.exit(1) self.alpr.set_top_n(self.n) self.alpr.set_default_region("va") # Execute the trained classifier against the given test sample # inputObsVector is a path to the video file def execute(self, inputObsVector): if(len(inputObsVector) == self.numInputs): y_Test = self.predict(inputObsVector); return y_Test; else: print("Wrong dimensions, fail to execute"); return None; # Grabs frames and returns top n predictions per frame. def predict(self, x_Test): cap = cv2.VideoCapture(x_Test[0]) if not cap.isOpened(): print("vid open error") cap.open() fps = 25 timedelta = 0 detectCounter = [0] detectCounter[0] = 0 plates_list = np.empty([0, self.n]) while(cap.isOpened()): ret, frame = cap.read() if (detectCounter[0] < fps*timedelta): detectCounter[0] += 1 continue detectCounter[0] = 0 if ret: pretime = time.time() ret, enc = cv2.imencode("*.bmp", frame) results = self.alpr.recognize_array(bytes(bytearray(enc))) posttime = time.time() plates = np.empty([1,self.n], dtype='a5') for s in range(0, self.n): plates[0][s] = "" for plate in results['results']: i = 0 for candidate in plate['candidates']: platenum = candidate['plate'].encode('ascii','ignore') plates[0][i] = platenum i += 1 timedelta = posttime - pretime # in seconds plates_list = np.vstack((plates_list, plates)) else: break return plates_list;
def initNumPlateRecognizer(region="eu"): alpr = Alpr("eu", "nplate_train/openalpr.conf.in", "nplate_train/runtime_data") if not alpr.is_loaded(): print ("Error loading OpenALPR") sys.exit(1) alpr.set_default_region(region) return alpr
def get_alpr(): alpr = Alpr("us", "/etc/openalpr/openalpr.conf", "/usr/share/openalpr/runtime_data") if not alpr.is_loaded(): print("Error loading OpenALPR") return None print("Using OpenALPR" + alpr.get_version()) return alpr
def __init__(self, complexity, numInputs, outputClassifier, inputClassifiers, appFieldsDict): ContextEngineBase.__init__(self,complexity, numInputs, outputClassifier, inputClassifiers, appFieldsDict) self.alpr = Alpr("us", "/etc/openalpr/openalpr.conf", "/home/pi/openalpr/runtime_data") if not self.alpr.is_loaded(): print("Error loading OpenALPR") sys.exit(1) self.alpr.set_top_n(self.n) self.alpr.set_default_region("va")
def pred_alpr(image1): #### SHould add the region alpr = Alpr("us", "C:\\Users\\shobeir.mazinani\\Desktop\\BasharsALPR\\OpenALPR-Python\\openalpr_64\\openalpr.conf", "C:\\Users\\shobeir.mazinani\\Desktop\\BasharsALPR\\OpenALPR-Python\\openalpr_64\\runtime_data") if not alpr.is_loaded(): print("Error loading OpenALPR") sys.exit(1) else: print("OpenALPR was loaded correctly") alpr.set_top_n(1) alpr.set_default_region("ca") results = alpr.recognize_file(image1) #print(results) i = 0 for plate in results['results']: i += 1 print("Plate #%d" % i) print(" %12s %12s" % ("Plate", "Confidence")) for candidate in plate['candidates']: prefix = "-" if candidate['matches_template']: prefix = "*" #print(" %s %12s%12f" % (prefix, candidate['plate'], candidate['confidence'])) # Call when completely done to release memory # alpr.unload() #print("Sleep for some time") #time.sleep(5) #print("I am done") return candidate['plate'], candidate['confidence']
def alpr(): start_time = time.time(); try: print 'recieved image, processing...' alpr = Alpr("us", "/etc/openalpr/openalpr.conf", "/usr/share/openalpr/runtime_data") alpr.set_top_n(20) mid1_time = time.time(); if 'image' not in request.files: print "image was not in files" return 'Image parameter not provided' jpeg_bytes = request.files['image'].read() if len(jpeg_bytes) <= 0: print "there are no bytes!" return False mid2_time = time.time(); results = alpr.recognize_array(jpeg_bytes) print "got results!" end_time = time.time(); print("total_time: " + str(end_time-start_time)); print("alpr_time: " + str(mid1_time-start_time)); print("jpeg_time: " + str(mid2_time-mid1_time)); print("processing_time: " + str(end_time-mid2_time)); return jsonify(results) except Exception, e: print e raise e
def license_read(filenames=[]): alpr = None #tell alpr which country license plate to use and where to find the openalpr.conf file and the #runtime_data folder alpr = Alpr("us", "/etc/openalpr/openalpr.conf", "/home/baus/Documents/openalpr/runtime_data/") #Ensures that the alpr is loaded and can be used if not alpr.is_loaded(): print("Error loading OpenALPR") return "Error" elif(alpr.is_loaded()): alpr.set_top_n(1) alpr.set_default_region('md') license_plates=[] #for all the images that was sent, check if license plate exists for x in range(5): results = alpr.recognize_file(filenames[x]) for plate in results["results"]: for candidate in plate["candidates"]: #Appends the license plate to the list #Appends nothing if it didnt find any license plate license_plates.append(candidate["plate"]) return license_plates return "Error"
from openalpr import Alpr alpr = Alpr("us", "/path/to/openalpr.conf", "/path/to/runtime_data") if not alpr.is_loaded(): print("Error loading OpenALPR") sys.exit(1) alpr.set_top_n(20) alpr.set_default_region("md") results = alpr.recognize_file("./image/DSCN0416.jpg") i = 0 for plate in results['results']: i += 1 print("Plate #%d" % i) print(" %12s %12s" % ("Plate", "Confidence")) for candidate in plate['candidates']: prefix = "-" if candidate['matches_template']: prefix = "*" print(" %s %12s%12f" % (prefix, candidate['plate'], candidate['confidence'])) # Call when completely done to release memory alpr.unload()
import numpy as np import cv2 from openalpr import Alpr alpr = Alpr("eu", "/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(20) alpr.set_default_region("md") cap = cv2.VideoCapture("rtsp://*****:*****@10.8.0.7:5544") cv2.namedWindow('image', cv2.WINDOW_NORMAL) ret, frame = cap.read() cv2.namedWindow('image', cv2.WINDOW_NORMAL) while (True): ret, frame = cap.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) cv2.imshow('image', gray) if cv2.waitKey(1) & 0xFF == ord('q'): break results = alpr.recognize_ndarray(gray) print(results['results']) cv2.destroyAllWindows()
# apt install openalpr # apt install python3-openalpr from openalpr import Alpr import cv2 import sys import json if len(sys.argv)!=2: print('Usage:',sys.argv[0],'<car image>') sys.exit(2) 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(10) alpr.set_default_region("md") results = alpr.recognize_file(sys.argv[1]) if results is not None: print('Found plate',len(results['results'])) # load iamge img = cv2.imread(sys.argv[1]) for plate in results['results']: print('Plate match coordinates:') print(plate['coordinates'][0]['x'],plate['coordinates'][0]['y'])
def scriptADetectingObjects(): alpr = Alpr("eu", "openalpr.conf", "runtime_data") if not alpr.is_loaded(): print("Error loading OpenALPR") sys.exit(1) alpr.set_top_n(1) alpr.set_default_region("eu") #cap = cv2.VideoCapture('videoa.mp4') # cap = cv2.VideoCapture('numPlates.mpg') # cap = cv2.VideoCapture('sheeriff.mp4') # cap = cv2.VideoCapture(0) # This is needed since the notebook is stored in the object_detection folder. sys.path.append("..") # ## Object detection imports # Here are the imports from the object detection module. from utils import label_map_util from utils import visualization_utils as vis_util # # Model preparation # ## Variables # # Any model exported using the `export_inference_graph.py` tool can be loaded here simply by changing `PATH_TO_FROZEN_GRAPH` to point to a new .pb file. # # By default we use an "SSD with Mobilenet" model here. See the [detection model zoo](https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md) for a list of other models that can be run out-of-the-box with varying speeds and accuracies. # What model to download. MODEL_NAME = 'ssd_mobilenet_v1_coco_2017_11_17' MODEL_FILE = MODEL_NAME + '.tar.gz' DOWNLOAD_BASE = 'http://download.tensorflow.org/models/object_detection/' # Path to frozen detection graph. This is the actual model that is used for the object detection. PATH_TO_FROZEN_GRAPH = MODEL_NAME + '/frozen_inference_graph.pb' # List of the strings that is used to add correct label for each box. PATH_TO_LABELS = os.path.join('data', 'mscoco_label_map.pbtxt') # ## Download Model # ## Load a (frozen) Tensorflow model into memory. detection_graph = tf.Graph() with detection_graph.as_default(): od_graph_def = tf.GraphDef() with tf.gfile.GFile(PATH_TO_FROZEN_GRAPH, 'rb') as fid: serialized_graph = fid.read() od_graph_def.ParseFromString(serialized_graph) tf.import_graph_def(od_graph_def, name='') # ## Loading label map # Label maps map indices to category names, so that when our convolution network predicts `5`, we know that this corresponds to `airplane`. Here we use internal utility functions, but anything that returns a dictionary mapping integers to appropriate string labels would be fine category_index = label_map_util.create_category_index_from_labelmap( PATH_TO_LABELS, use_display_name=True) # # Detection # For the sake of simplicity we will use only 2 images: # image1.jpg # image2.jpg # If you want to test the code with your images, just add path to the images to the TEST_IMAGE_PATHS. PATH_TO_TEST_IMAGES_DIR = 'test_images' TEST_IMAGE_PATHS = [ os.path.join(PATH_TO_TEST_IMAGES_DIR, 'image{}.jpg'.format(i)) for i in range(1, 3) ] # Size, in inches, of the output images. IMAGE_SIZE = (12, 8) # In[10]: with detection_graph.as_default(): with tf.Session(graph=detection_graph) as sess: while True: ret, image_np = cap.read() # Expand dimensions since the model expects images to have shape: [1, None, None, 3] image_np_expanded = np.expand_dims(image_np, axis=0) image_tensor = detection_graph.get_tensor_by_name( 'image_tensor:0') # Each box represents a part of the image where a particular object was detected. boxes = detection_graph.get_tensor_by_name('detection_boxes:0') # Each score represent how level of confidence for each of the objects. # Score is shown on the result image, together with the class label. scores = detection_graph.get_tensor_by_name( 'detection_scores:0') classes = detection_graph.get_tensor_by_name( 'detection_classes:0') num_detections = detection_graph.get_tensor_by_name( 'num_detections:0') # Actual detection. (boxes, scores, classes, num_detections) = sess.run( [boxes, scores, classes, num_detections], feed_dict={image_tensor: image_np_expanded}) # Visualization of the results of a detection. vis_util.visualize_boxes_and_labels_on_image_array( image_np, np.squeeze(boxes), np.squeeze(classes).astype(np.int32), np.squeeze(scores), category_index, use_normalized_coordinates=True, line_thickness=8) cv2.imwrite('img.jpg', image_np) results = alpr.recognize_file('img.jpg') i = 0 # Recognizing from every frame of the video by incrementing by one for plate in results['results']: i += 1 print("Plate #%d" % i) print(" %12s %12s" % ("Plate", "Confidence")) for candidate in plate['candidates']: prefix = "-" # If character matches the one we have from pre-trained model then it marks "matches template" if candidate['matches_template']: prefix = "*" print(" %s %12s%12f" % (prefix, candidate['plate'], candidate['confidence'])) cv2.imshow('object detection', cv2.resize(image_np, (800, 600))) if cv2.waitKey(25) & 0xFF == ord('q'): cv2.destroyAllWindows() break
from os import environ from openalpr import Alpr alpr_dir = 'C:/Users/DavidHerrera/AppData/Local/Programs/Python/Python37/openalpr' environ['PATH'] = alpr_dir + ';' + environ['PATH'] alpr = Alpr('us', alpr_dir + '/openalpr.conf', alpr_dir + '/runtime_data') if not alpr.is_loaded(): print("Error loading OpenALPR") sys.exit(1) results = alpr.recognize_file("car.jpg") print(results["results"][0]["plate"]) alpr.unload()
class VehicleID: region, configuration, runtime = 'us', 'C:\\OpenALPR\\Agent\\etc\\openalpr\\openalpr.conf', 'C:\\OpenALPR\\Agent\\usr\\share\\openalpr\\runtime_data' frame, small_frame, detect, authorized_users, plate, queue = None, None, True, dict( ), None, queue.Queue(1000) def __init__(self): super().__init__() self.alpr = Alpr(self.region, self.configuration, self.runtime) # init alpr engine # self.camera = cv2.VideoCapture("D:\\others\\20191125_141145.mp4") # record frames from video source self.camera = cv2.VideoCapture(1) # record frames from video source def main(self): while True: self.get_frame() self.license_plate_recognition() def get_frame(self): _, frame = self.camera.read() # read from video source self.frame = cv2.UMat(frame).get() # use tapi to take advantage of gpu self.small_frame = cv2.UMat( cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)).get() # 1/4 scale for faster processing def license_plate_recognition(self): if self.small_frame is not None: result = self.alpr.recognize_ndarray(self.small_frame).get( 'results') # use alpr engine to detect license plate if self.detect and result: self.plate, confidence, _, _, _, _, _, _, coordinates, vehicle_region, _ = result[ 0].values( ) # deserialize results of license plate recognition tl, tr, br, bl = coordinates cv2.UMat( cv2.rectangle( self.frame, (tl['x'] * 4, tl['y'] * 4), (br['x'] * 4, br['y'] * 4), (0, 255, 255), 8)) # plot coordinates of license plate onto frame cv2.UMat( cv2.rectangle(self.frame, (bl['x'] * 4, bl['y'] * 4), (br['x'] * 4, br['y'] * 4 + 25), (0, 255, 255), cv2.FILLED)) cv2.UMat( cv2.putText(self.frame, self.plate, (bl['x'] * 4 + 40, bl['y'] * 4 + 15), cv2.QT_FONT_NORMAL, 0.7, (0, 0, 0), 2)) self.authorize_vehicle( ) # search database for vehicle plate and obtain registered owner if present def authorize_vehicle(self): user = User.query.filter_by( license_plate=self.plate).first() # query user that owns vehicle if user: self.authorized_users[user.id] = [ user.id, user.name, user.license_plate ] # load user ont authorized list on gate entry socketio.emit('message', self.authorized_users) def print_frame(self): while True: if self.frame is not None: yield b'--frame\r\n' b'Content-Type: text/plain\r\n\r\n' + cv2.imencode( '.jpg', self.frame)[1].tostring() + b'\r\n'
#!/usr/bin/env python3 import sys import uuid from time import sleep from typing import List from openalpr import Alpr from picamera import PiCamera # TODO: replace writing to a file with writing to an in memory bytearray/numpy array ALPR = Alpr("eu", "/etc/openalpr/openalpr.conf", "/usr/share/openalpr/runtime_data/") if not ALPR.is_loaded(): print("Error loading OpenALPR") sys.exit(1) def take_picture() -> str: file_path = f"/tmp/{uuid.uuid4()}.jpg" with PiCamera() as camera: camera.start_preview() sleep(3) # Give time to focus camera.capture(file_path) camera.stop_preview() return file_path
class Lector(): OPEN_ALPR_CONF_PATH = '/opt/openalpr/config/openalpr.conf.user' RUNTIME_DATA_PATH = '/opt/openalpr/runtime_data' estado = None alpr = None estado_config = None def __init__(self): self.estado = 'off' self.alpr = Alpr("us", self.OPEN_ALPR_CONF_PATH, self.RUNTIME_DATA_PATH) self.alpr.set_top_n(1) def iniciar(self, cam_socket): if self.estado == 'off': self.estado = 'on' placas_candidatas = [] tiempo_post_lectura = 1 tiempo_ultima_lectura = 0 # camara = cv2.VideoCapture(0) camara = cv2.VideoCapture( '/home/stalinscj/_dux_test/test/vehiculoTest/portonOriginalSinBorde_640x360.mp4' ) leyendo = False success = True # video = cv2.VideoWriter("output.avi", cv2.VideoWriter_fourcc(*'MJPG'), 20, (640,360)) while self.estado == 'on' and success == True: success, frame = camara.read() if not success: break if time.time() - tiempo_ultima_lectura > tiempo_post_lectura: if leyendo == True: video.release() threading.Thread(target=self.guardar_video, args=(video_nombre, )).start() leyendo = False else: if leyendo == False: video_nombre = "media/{0}.mp4".format(uuid.uuid4().int & (1 << 64) - 1) #MP4V # 0x7634706d # video = cv2.VideoWriter(video_nombre, cv2.VideoWriter_fourcc(*'MP4V'), 20, (640,360)) video = cv2.VideoWriter(video_nombre, 0x7634706d, 20, (640, 360)) leyendo = True video.write(frame) if not leyendo and placas_candidatas: placa = self.get_placa(placas_candidatas) threading.Thread(target=self.procesar_envio, args=( placa, cam_socket, video_nombre, )).start() del placas_candidatas[:] placa_candidata = self.buscar_placa(frame) if placa_candidata: placas_candidatas.append(placa_candidata) tiempo_ultima_lectura = time.time() cam_socket.send( text_data=json.dumps({ 'tipo': 'frame', 'img_src': self.img_to_base64(frame) })) def detener(self, cam_socket): if self.estado == 'on': self.estado = 'off' frame = cv2.imread( os.path.join(settings.STATIC_ROOT, 'core/img/live.png')) time.sleep(2) cam_socket.send( text_data=json.dumps({ 'tipo': 'frame', 'img_src': self.img_to_base64(frame) })) def img_to_base64(self, img): success, img_codificada = cv2.imencode('.png', img) if success: b64_src = 'data:image/png;base64,' img_src = b64_src + base64.b64encode(img_codificada).decode() return img_src return '' def buscar_placa(self, frame): buscador = self.alpr.recognize_ndarray(frame) resultado = buscador['results'] if (resultado): placa = resultado[0]['plate'] if self.validar_placa(placa): confianza = resultado[0]['confidence'] coordenadas = resultado[0]['coordinates'] x0 = coordenadas[0]['x'] y0 = coordenadas[0]['y'] x2 = coordenadas[2]['x'] y2 = coordenadas[2]['y'] img_placa = frame[y0:y2, x0:x2] placa_candidata = (placa, confianza, img_placa, frame) cv2.rectangle(frame, (x0 - 5, y0 - 5), (x2 + 5, y2 + 5), (0, 255, 0), 3) return placa_candidata return None def validar_placa(self, placa): if len(placa) > 5 and len(placa) < 8: return True else: return False def filtrar_placas(self, placas_candidatas): flag = False for placa in placas_candidatas: if len(placa[0]) > 6: flag = True break if flag: for placa in placas_candidatas: if len(placa[0]) < 7: placas_candidatas.remove(placa) def get_placa(self, placas_candidatas): self.filtrar_placas(placas_candidatas) max_confianza = 0 for i in range(0, len(placas_candidatas)): confianza = placas_candidatas[i][1] if (confianza > max_confianza): max_confianza = confianza placa = placas_candidatas[i] return placa def procesar_envio(self, placa, cam_socket, video_nombre): placa_str = placa[0] placa_img = placa[3] placa_img_mini = placa[2] config = ConfigParser() config.read('dux/config.ini') peaje = Peaje.objects.filter(pk=config.get('peaje', 'id')).first() lectura = Lectura.objects.create( peaje=peaje, matricula=placa_str, direccion=config.get('camaras', '0'), imagen=self.img_to_base64(placa_img), imagen_mini=self.img_to_base64(placa_img_mini), video=video_nombre) solicitud = MatriculaSolicitada.objects.filter(matricula=placa_str, activo=True).first() avisos = 0 idAlerta = '' if solicitud: alerta = Alerta.nueva(solicitud, lectura) idAlerta = alerta.pk avisos = alerta.notificacion_set.all().count() cam_socket.send( text_data=json.dumps({ 'tipo': 'tupla', 'fecha': time.strftime("%d/%m/%Y %H:%M:%S"), 'placa': placa_str, 'img_src': self.img_to_base64(placa_img_mini), 'avisos': avisos, 'alerta_id': idAlerta })) def iniciar_config(self, cam_socket): self.estado_config = 'on' camara = cv2.VideoCapture(0) success = True while self.estado_config == 'on' and success == True: success, frame = camara.read() if not success: break cam_socket.send( text_data=json.dumps({'img_src': self.img_to_base64(frame)})) def terminar_config(self, cam_socket): if self.estado_config == 'on': self.estado_config = 'off' frame = cv2.imread( os.path.join(settings.STATIC_ROOT, 'core/img/live.png')) time.sleep(2) cam_socket.send( text_data=json.dumps({'img_src': self.img_to_base64(frame)})) def guardar_video(self, video_nombre): os.system( "ffmpeg -i {0}.mp4 -loglevel quiet -an -vcodec libx264 -crf 23 {0}tmp.mp4" .format(video_nombre[:-4])) os.system("rm -f " + video_nombre) os.system("mv {0}tmp.mp4 {0}.mp4".format(video_nombre[:-4]))
from openalpr import Alpr from picamera import PiCamera from time import sleep import pushover # Pushover settings PUSHOVER_USER_KEY = "<REPLACE WITH USER KEY>" PUSHOVER_APP_TOKEN = "<REPLACE WITH APP TOKEN>" # 'gb' means we want to recognise UK plates, many others are available alpr = Alpr("gb", "/etc/openalpr/openalpr.conf", "/usr/share/openalpr/runtime_data") camera = PiCamera() pushover.init(PUSHOVER_APP_TOKEN) last_seen = None try: # Let's loop forever: while True: # Take a photo print('Taking a photo') camera.capture('/home/pi/latest.jpg') # Ask OpenALPR what it thinks analysis = alpr.recognize_file("/home/pi/latest.jpg") # If no results, no car! if len(analysis['results']) == 0: print('No number plate detected')
import locale locale.setlocale(locale.LC_ALL, 'C') import tesserocr from openalpr import Alpr import sys import cv2 import time video = "../../Images/vid1.mp4" alpr = Alpr("in", "/usr/local/share/openalpr/config/openalpr.defaults.conf", "./openalpr/runtime_data") if not alpr.is_loaded(): print("Error loading OpenALPR") sys.exit(1) # select top 10 results alpr.set_top_n(10) alpr.set_default_region("in") cap = cv2.VideoCapture(video) # for smooth termination after video ends frame_counter = 0 length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) print(length) start_time = time.time() while(frame_counter < length):
from openalpr import Alpr import os import glob import datetime import logging alpr = Alpr("br", "/usr/share/openalpr/config/openalpr.defaults.conf", "/usr/share/openalpr/runtime_data") if not alpr.is_loaded(): print("Error loading OpenALPR") sys.exit(1) alpr.set_top_n(40) alpr.set_default_region("md") logging.basicConfig(filename='/home/opt/out/plate_log.log', level=logging.DEBUG) dataAtual = datetime.datetime.now().strftime("%d-%m-%Y") list_of_files = glob.glob( '/home/opt/ftp/192.168.255.72/' + dataAtual + '/*') # * means all if need specific format then *.csv if not list_of_files: print "Diretorio Vazio" arq_foto = "" dir_saida = "" else: arq_foto = max(list_of_files, key=os.path.getctime) dir_saida = "/home/opt/out/placa.txt" #print list_of_files
class AlprDetector: def __init__(self, name, config, video_source, event_callback=None, save_images=False): self.__name = name self.__alpr_instance = Alpr(config.region, config.config_file, config.runtime_data_file) if not self.__alpr_instance.is_loaded(): print('Alpr instance could not be created') self.__frame_skip = config.frame_skip self.event_callback = event_callback self.__video_source = video_source self.__cap = cv2.VideoCapture(video_source) self.__running = False self.__save_image = save_images import os self.__directory = os.getcwd() def is_working(self): return self.__cap.isOpened() and self.__running def video_source_properties(self): data = dict() data['source'] = self.__video_source data['fps'] = self.__cap.get(cv2.CAP_PROP_FPS) data['width'] = self.__cap.get(cv2.CAP_PROP_FRAME_WIDTH) data['height'] = self.__cap.get(cv2.CAP_PROP_FRAME_HEIGHT) data['codec'] = self.__cap.get(cv2.CAP_PROP_FOURCC) return @staticmethod def __extract_results(alpr_result): if alpr_result is None: return None if not alpr_result['results']: return None else: result = [] for plate in alpr_result['results']: for candidate in plate['candidates']: result.append( [candidate['plate'], candidate['confidence']]) return result @staticmethod def __extract_best_candidate(alpr_result): return alpr_result['results'][0]['plate'] if alpr_result[ 'results'] else None def __handle_results(self, extracted_results): if self.event_callback is not None: callback_data = dict() # object is list of dict containing 'plate' and 'confidence' callback_data['candidates'] = extracted_results callback_data['detector'] = self.__name print('calling callback , ', extracted_results) self.event_callback(callback_data) def run(self): if self.__running: print(self.__name, ' Detector is already running') return False else: self.__running = True if not self.is_working(): print(self.__name, ' Video capture not working.') self.__running = False return False frame_number = 0 last_recognized_plate = None error_state = False try: print(self.__name, ' starting detector loop for: ', self.__video_source) while self.__running: a = datetime.datetime.now() last_read_status, frame = self.__cap.read() if not last_read_status: print('Video capture.read() failed. Stopping the work') self.__running = False error_state = True break frame_number += 1 if frame_number % self.__frame_skip == 0: frame_number = 0 continue if cv2.waitKey(1) == 27: break # cv2.imshow(self.__name, frame) # todo: use recognize_ndarray when updated to at least 2.3.1 # alpr.recognize_ndarray(frame) ret, enc = cv2.imencode("*.bmp", frame) results = self.__alpr_instance.recognize_array( bytes(bytearray(enc))) best_candidate = self.__extract_best_candidate(results) if best_candidate is not None and best_candidate != last_recognized_plate: last_recognized_plate = best_candidate print(best_candidate) # send first recognized plate and all candidates extracted_results = self.__extract_results(results) if extracted_results: self.__handle_results(extracted_results) if self.__save_image: print(self.__directory) import os.path cv2.imwrite( os.path.join( self.__directory, self.__name, ''.join( (best_candidate, '_', self.__name, '_', datetime.datetime.now().strftime( "%Y_%m_%d_%H_%M_%S"), '.jpeg'))), frame) except cv2.error as e: print("OpenCV Exception caught: ", e) error_state = True except Exception as e: print("Exception caught: ", e) error_state = True finally: self.__alpr_instance.unload() self.__running = False print(self.__name, " is stopping") return not error_state def stop(self): self.__running = False
import json from openalpr import Alpr alpr = Alpr("us", "/etc/openalpr/openalpr.conf", "/usr/share/openalpr/runtime_data") results = alpr.recognize_file("/home/pi/ea7the.jpg") print(json.dumps(results, indent=4)) alpr.unload()
from openalpr import Alpr import sys alpr = Alpr("us", "C:\openalpr_64\openalpr.conf", "C:\openalpr_64\\runtime_data\\") if not alpr.is_loaded(): print("Error loading OpenALPR") sys.exit(1) alpr.set_top_n(5) alpr.set_default_region("md") results = alpr.recognize_file("C:\openalpr_64\samples\us-1.jpg") i = 0 for plate in results['results']: i += 1 print("Plate #%d" % i) print(" %12s %12s" % ("Plate", "Confidence")) for candidate in plate['candidates']: prefix = "-" if candidate['matches_template']: prefix = "*" print(" %s %12s%12f" % (prefix, candidate['plate'], candidate['confidence'])) # Call when completely done to release memory alpr.unload()
def main(webpage_to_scrape, database_config): alpr = Alpr("eu", "/config/alprd.conf.defaults", "/Users/matejsamler/Downloads/openalpr-master/runtime_data") if not alpr.is_loaded(): print "Error loading OpenALPR" return -1 con = mysql.connector.connect(**database_config) cursor = con.cursor() alpr.set_top_n(20) alpr.set_default_region("md") results = alpr.recognize_file(sys.argv[1]) most_likely_plate = "" for plate in results['results']: for candidate in plate['candidates']: if candidate['confidence'] == plate['confidence']: most_likely_plate = candidate['plate'] webpage_to_scrape = webpage_to_scrape + most_likely_plate try: soup = BeautifulSoup(urllib2.urlopen(webpage_to_scrape), "html.parser") except urllib2.HTTPError: con.commit() cursor.close() con.close() alpr.unload() return -1 else: information_table = soup.findAll("div", class_="col1") indatabasequerry = "SELECT * FROM cars WHERE Plate = '" + most_likely_plate + "'" querry = "INSERT INTO `cars` (`Plate`, `Region`, `Insurance`, `Duration`, `Type`, `Brand`) VALUES ('" + most_likely_plate + "'" cursor.execute(indatabasequerry) rows = cursor.fetchall() if len(rows) > 0: return rows[0][0] else: for information in make_information_list(information_table): querry = querry + " ,'" + information + "'" querry = querry + ");" cursor.execute(querry) con.commit() cursor.execute(indatabasequerry) rows = cursor.fetchall() if len(rows) > 0: return rows[0][0] # Call when completely done to release memory cursor.close() con.close() alpr.unload()
def __init__(self): self.estado = 'off' self.alpr = Alpr("us", self.OPEN_ALPR_CONF_PATH, self.RUNTIME_DATA_PATH) self.alpr.set_top_n(1)
from openalpr import Alpr import json import tornado.ioloop import tornado.web import os alpr = Alpr("eu", "/etc/openalpr/openalpr.conf", "/usr/share/openalpr/runtime_data") alpr.set_top_n(5) class MainHandler(tornado.web.RequestHandler): def post(self): print('Printing request files') print(self.request.files) if 'image' not in self.request.files: self.finish('Image parameter not provided') fileinfo = self.request.files['image'][0] jpeg_bytes = fileinfo['body'] if len(jpeg_bytes) <= 0: return False results = alpr.recognize_array(jpeg_bytes) self.finish(json.dumps(results)) def get(self):
class License(): def __init__(self): super() self.country = 'kr' self.config = 'openalpr.conf' self.runtime_data = 'runtime_data' self.alpr = Alpr(self.country, self.config, self.runtime_data) if not self.alpr.is_loaded(): print("Error loading OpenALPR") print("Using OpenALPR " + self.alpr.get_version()) self.number = '-1' def imgProcessing(self, file): _file = self.capture() if (_file == None): _file = file results = self.alpr.recognize_file(_file) print("Image size: %dx%d" % (results['img_width'], results['img_height'])) print("Processing Time: %f" % results['processing_time_ms']) i = 0 for plate in results['results']: i += 1 print("Plate #%d" % i) print(" %12s %12s" % ("Plate", "Confidence")) self.number = plate['candidates'][0]['plate'] for candidate in plate['candidates']: prefix = "-" if candidate['matches_template']: prefix = "*" print(" %s %12s%12f" % (prefix, candidate['plate'], candidate['confidence']) + "%") #번호판 문자열을 찾지 못햇을경우 12자1234 if (self.number == '-1' or len(results) == 0): self.number = '00허7777' return self.number return self.number def capture(self): filepath = './take.jpg' _cap = cv2.VideoCapture(1) if not _cap.isOpened(): return None ret, frame = _cap.read() ret, frame = _cap.read() ret, frame = _cap.read() ret, frame = _cap.read() ret, frame = _cap.read() ret, frame = _cap.read() dst = cv2.flip(frame, 1) dst2 = cv2.resize(dst, dsize=(0, 0), fx=1.3, fy=1, interpolation=cv2.INTER_LINEAR) cv2.imwrite(filepath, dst2) _cap.release() return filepath def __del__(self): print("license class del")
logger = logging.getLogger(__name__) country_code = os.getenv('OCV_COUNTRY_CODE', "us") top_n = os.getenv('OCV_TOP_N', "5") mxnet_model = os.getenv('OCV_MXNET_MODEL', "squeezenet_v1.1") logger.info('Initialization params:') logger.info('country_code: ' + country_code) logger.info('top_n: ' + top_n) logger.info('mxnet_model: ' + mxnet_model) # openface vars pickleLocation = '/root/data/data.pickle' pickleJsonLocation = '/root/data/data.json' # create an alpr alpr = Alpr(country_code, "/etc/openalpr/openalpr.conf", "/usr/share/openalpr/runtime_data") alpr.set_top_n(int(top_n)) # create a reader scanner = zbar.ImageScanner() scanner.parse_config('enable') # create the imagenet instance squeezenet = ImagenetModel(synset_path='synset.txt', network_prefix='squeezenet_v1.1', label_names=['prob_label']) vgg19 = ImagenetModel(synset_path='synset.txt', network_prefix='vgg19', label_names=['prob_label'])
from openalpr import Alpr import sys import cv2 alpr = Alpr('us', 'openalpr.conf', 'runtime_data') if not alpr.is_loaded(): print("Error loading OpenALPR") sys.exit(1) alpr.set_top_n(20) alpr.set_default_region("ca") #img1 = cv2.imread("us-4.jpg",1) #cv2.imshow('Image',img1) #cv2.waitKey(0) results = alpr.recognize_file('us-3.jpg') i = 0 print results if len(results['results']) == 0: print "No results found" sys.exit() for plate in results['results']: i += 1 print("Plate #%d" % i) print(" %12s %12s" % ("Plate", "Confidence")) for candidate in plate['candidates']: prefix = "-" if candidate['matches_template']:
import cv2 debug = True #Sets options to output to console, should normally be False #OpenCV Video capture (get webcam feed) cap = cv2.VideoCapture(0) #Set height cap.set(3, 640) #Set width cap.set(4, 640) #Set exposure/shutter speed (Only some cameras) cap.set( 15, 200 ) #Not sure what the values mean yet for this option, is it 1/200th of a second or 200ms? alpr = Alpr("eu", "openalpr.conf", "runtime_data/") alpr.set_top_n(1) #Only output one plate guess per plate alpr.set_default_region("gb") #Good old british plates while (True): ret, frame = cap.read() ret, enc = cv2.imencode( "*.bmp", frame ) #Convert to bitmap because I don't know how to recognise other formats in realtime results = alpr.recognize_array(bytes(bytearray(enc))) for plate in results['results']: cord = 0 #Needs to be set to zero for wach unique plate, unless you want a large possibly messy shape pts = np.array( [[10, 5], [20, 30], [70, 20], [50, 10]],
parser.add_argument('thrsArea', help='Threshold pixel area for moving vehicle detcetion') options = parser.parse_args() dst = os.getcwd() + '\cropedImages' # destination to save the images if not os.path.exists(dst): os.makedirs(dst) fieldnames = ['ID', 'Plate number', 'Image Path', 'Date', 'Time'] fileID = open('file.csv', 'w') # file to save the data newFileWriter = csv.writer(fileID) newFileWriter.writerow(fieldnames) alpr = Alpr(options.country, options.config, options.runtime_data) #alpr = Alpr("mx", "C:/openALPR_1/openalpr_64/openalpr.conf", "C:/openALPR_1/openalpr_64/runtime_data") #alpr.set_top_n(10) alpr.set_default_region("md") if not alpr.is_loaded(): sys.exit(1) print("Using OpenALPR " + alpr.get_version()) cap = cv2.VideoCapture(options.Video_Source) bg_subtractor = cv2.createBackgroundSubtractorMOG2(history=500, detectShadows=True) print('Training BG Subtractor...') cv2.namedWindow('op', cv2.WINDOW_NORMAL) cnt = 0
from openalpr import Alpr alpr = Alpr("ph", "openalpr/openalpr.conf", "openalpr/runtime_data/") if not alpr.is_loaded(): print("Error loading OpenALPR") sys.exit(1) alpr.set_top_n(7) alpr.set_default_region("ph") results = alpr.recognize_file("lp4.jpg") i = 0 for plate in results['results']: i += 1 print("Plate #%d" % i) print(" %12s %12s" % ("Plate", "Confidence")) for candidate in plate['candidates']: prefix = "-" if candidate['matches_template']: prefix = "*" print(" %s %12s%12f" % (prefix, candidate['plate'], candidate['confidence'])) # Call when completely done to release memory alpr.unload()
from openalpr import Alpr import json import tornado.ioloop import tornado.web alpr = Alpr("eu", "/etc/openalpr/openalpr.conf", "/usr/share/openalpr/runtime_data") alpr.set_top_n(20) class MainHandler(tornado.web.RequestHandler): def post(self): if 'image' not in self.request.files: self.finish('Image parameter not provided') fileinfo = self.request.files['image'][0] jpeg_bytes = fileinfo['body'] if len(jpeg_bytes) <= 0: return False results = alpr.recognize_array(jpeg_bytes) self.finish(json.dumps(results)) application = tornado.web.Application([ (r"/alpr", MainHandler),
def plater(image_paths) -> bool: alpr = None found_count = 0 image_dir = "./images/" try: alpr = Alpr("us", "./baller.alpr.config", "/usr/share/openalpr/runtime_data") if not alpr.is_loaded(): print("Error loading OpenALPR") else: print("Using OpenALPR " + alpr.get_version()) alpr.set_top_n(5) alpr.set_default_region("tx") alpr.set_detect_region(True) for entry in image_paths: jpeg_bytes = open(os.path.join(image_dir, entry), "rb").read() results = alpr.recognize_array(jpeg_bytes) # print ("kakakak \n\n\n") # print (results['results']) # for plate in results['results']: # i += 1 # print("Plate #%d" % i) # print(" %12s %12s" % ("Plate", "Confidence")) # for candidate in plate['candidates']: # prefix = "-" # if candidate['matches_template']: # prefix = "*" # print(" %s %12s%12f" % (prefix, candidate['plate'], candidate['confidence'])) if len(results['results']) > 0: found_count += 1 return found_count > 0 finally: if alpr: alpr.unload()
import cv2 from openalpr import Alpr from pprint import pprint import sys import time v = cv2.VideoCapture( 'rtsp://192.168.88.172:554/user=admin&password=user&channel=1&stream=0.sdp?') width = 800 skip = 10 a = Alpr("eu", "/etc/openalpr/openalpr.conf", "/usr/share/openalpr/runtime_data") n = 0 def convert2pnm(im): # get image dimensions height, width, depth = (im.shape + (1,))[0:3] # P5 and P6 are the numbers for PGM and PPM formats, respectively if depth == 3: # convert image from BRG to RGB (pnm uses RGB) im2 = cv2.cvtColor(im, cv2.COLOR_BGR2RGB) format_ = "P6" elif depth == 1: # GRAY image, do nothing im2 = im format_ = "P5" else: return return "%s %d %d 255 " % (format_, width, height) + im2.tostring()
MY_PATH = os.path.abspath(__file__) # get the path location only (excluding script name) BASE_DIR = MY_PATH[0:MY_PATH.rfind("/") + 1] # BASE_FILE_NAME is This script name without extension BASE_FILE_NAME = MY_PATH[MY_PATH.rfind("/") + 1:MY_PATH.rfind(".")] PROG_NAME = os.path.basename(__file__) HORZ_LINE = "----------------------------------------------------------------------" if VERBOSE_ON: print(HORZ_LINE) print("%s %s written by Claude Pageau" % (PROG_NAME, PROG_VER)) print("ALPR license plate search speed_cam.py Images") print(HORZ_LINE) print("Loading Wait ...") ALPR = Alpr(ALPR_COUNTRY, ALPR_CONF_PATH, ALPR_RUNTIME_DATA_PATH) if not ALPR.is_loaded(): print('ERROR : Problem loading OpenALPR') sys.exit(1) ALPR.set_top_n(ALPR_TOP_N) # max plates expected per image ALPR.set_default_region(ALPR_REGION) # State/Prov Etc per ALPR docs try: RETRY = 0 while True: try: # Connect to sqlite3 database file DB_CONN = sqlite3.connect(DB_FILE) except sqlite3.Error as err_msg: print("ERROR: Failed sqlite3 Connect to DB %s" % DB_FILE)
"""Detects plates from webcam.""" import cv2 from openalpr import Alpr import sys import os import requests import json # import paho.mqtt.client as client headers = {'content-type': 'application/json'} url = "http://requestb.in/vd5wylvd" 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(1) alpr.set_default_region("us") cap = cv2.VideoCapture(0) # mqttc = client.Client() # mqttc.connect("localhost", 1883, 60) probablePlates = {} wasPlate = False numEx = 5 count = 0
from openalpr import Alpr import cv2 import re import os alpr = Alpr("eu", "/etc/openalpr/openalpr.conf", "/home/pi/openalpr/runtime_data") if not alpr.is_loaded(): print('Erro ao carregar ALPR') sys.exit(1) alpr.set_top_n(200) #alpr.set_default_region('md') #Trabalhando com imagens img = ('/home/pi/Pictures/celular01.jpg') print('Started...') cap = cv2.VideoCapture(0) cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1024) cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 1280) if cap.isOpened(): ret, frame = cap.read() else: ret = False cv2.imwrite(img, frame) cap.release() print("Finish") #seleciona a imagem results = alpr.recognize_file(img) i = 0 placa = ""
# -*- coding: utf-8 -*- """ Created on Fri Sep 28 15:34:02 2018 @author: DELL """ from openalpr import Alpr import sys alpr = Alpr("us", "/path/to/openalpr.conf", "/path/to/runtime_data") if not alpr.is_loaded(): print("Error loading OpenALPR") sys.exit(1) else alpr.set_top_n(20) alpr.set_default_region("md") results = alpr.recognize_file("/path/to/image.jpg") i = 0 for plate in results['results']: i += 1 print("Plate #%d" % i) print(" %12s %12s" % ("Plate", "Confidence")) for candidate in plate['candidates']: prefix = "-" if candidate['matches_template']: prefix = "*" print(" %s %12s%12f" % (prefix, candidate['plate'], candidate['confidence'])) # Call when completely done to release memory
def f(data): parser = ArgumentParser(description='OpenALPR Python Test Program') parser.add_argument("-c", "--country", dest="country", action="store", default="us", help="License plate Country" ) OpenALPR_path = "C:/Users/Franco/Documents/Github/control-vehicular/Otros/Deteccion/openalpr_32bit/" parser.add_argument("--config", dest="config", action="store", default=OpenALPR_path+"openalpr.conf", help="Path to openalpr.conf config file" ) parser.add_argument("--runtime_data", dest="runtime_data", action="store", default=OpenALPR_path+"runtime_data", help="Path to OpenALPR runtime_data directory" ) #parser.add_argument('plate_image', help='License plate image file') options = parser.parse_args() print(options.country, options.config, options.runtime_data) alpr = None try: alpr = Alpr(options.country.encode('ascii'), options.config.encode('ascii'), options.runtime_data.encode('ascii')) if not alpr.is_loaded(): print("Error loading OpenALPR") else: print("Using OpenALPR " + alpr.get_version().decode('ascii')) alpr.set_top_n(7) alpr.set_default_region(b"wa") alpr.set_detect_region(False) # jpeg_bytes = open(options.plate_image, "rb").read() # results = alpr.recognize_array(jpeg_bytes) jpeg_bytes = data results = alpr.recognize_array(bytes(bytearray(data))) # Uncomment to see the full results structure # import pprint # pprint.pprint(results) print("Image size: %dx%d" %(results['img_width'], results['img_height'])) print("Processing Time: %f" % results['processing_time_ms']) i = 0 if results['results']: print("%12s%12f" % (results['results'][0]['plate'], results['results'][0]['confidence'])) for plate in results['results']: i += 1 print("Plate #%d" % i) print(" %12s %12s" % ("Plate", "Confidence")) for candidate in plate['candidates']: prefix = "-" if candidate['matches_template']: prefix = "*" print(" %s %12s%12f" % (prefix, candidate['plate'], candidate['confidence'])) finally: if alpr: alpr.unload()
# ---------------- # Find the full path of this python script MY_PATH = os.path.abspath(__file__) # get the path location only (excluding script name) BASE_DIR = MY_PATH[0:MY_PATH.rfind("/") + 1] # BASE_FILE_NAME is This script name without extension BASE_FILE_NAME = MY_PATH[MY_PATH.rfind("/") + 1:MY_PATH.rfind(".")] PROG_NAME = os.path.basename(__file__) HORZ_LINE = "----------------------------------------------------------------------" if VERBOSE_ON: print(HORZ_LINE) print("%s %s written by Claude Pageau" % (PROG_NAME, PROG_VER)) print(HORZ_LINE) print("Connecting to %s Wait ..." % DB_FILE) ALPR = Alpr("us", "/etc/openalpr/openalpr.conf", "/usr/share/openalpr/runtime_data") if not ALPR.is_loaded(): print('ERROR : Problem loading OpenALPR') sys.exit(1) ALPR.set_top_n(3) # Set max plates expected per image ALPR.set_default_region('on') # Ontario Canada # Connect to sqlite3 file database file speed_cam.db try: DB_CONN = sqlite3.connect(DB_FILE) except sqlite3.Error as err_msg: print("ERROR: Failed sqlite3 Connect to DB %s" % DB_FILE) print(" %s" % err_msg) sys.exit(1)
from openalpr import Alpr plate_db = open('plates.txt').read() try: alpr = Alpr("us", "/usr/share/openalpr/openalpr.default.conf", "/usr/share/openalpr/runtime_data") #laods alpr if not alpr.is_loaded(): print("Error loading library (openalpr)") alpr.set_top_n(1) #determines which text to display with most confidence results = alpr.recognize_file("image.jpg") for plate in results['results']: #preliminary data to post canidate plate number for candidate in plate['candidates']: prefix = "-" if candidate['matches_template']: prefix = "*" plate_text = str(candidate['plate']) if plate_text not in plate_db:#logic to test if number is database. print ("NOT IN LIST! NO PASSAGE!") alert = "Plate number is: " + plate_text print (alert) question = raw_input("Would you like to add to the database? ") if question == "Yes" or question == "y" or question == "yes": plate_db = open('plates.txt', 'a'); appendage = str(' ' + plate_text) plate_db.write(appendage) print ("Okay added")
import sys import numpy as np import cv2 from openalpr import Alpr import json alpr = Alpr("us", "openalpr.conf", "runtime_data") if not alpr.is_loaded(): print("Error loading OpenALPR") sys.exit(1) alpr.set_top_n(1) alpr.set_default_region("us") #cap = cv2.VideoCapture("http://91.190.227.198/mjpg/video.mjpg") cap = cv2.VideoCapture("numPlates.mpg") count = 0 countNumber = 4 while (True): #ret, frame = cap.read() if True: #cv2.imshow('frame', frame) #if cv2.waitKey(1) & 0xFF == ord('q'): # break #cv2.imwrite("img.jpg", frame) results = alpr.recognize_file("namcd/img" + str(countNumber) + ".jpg") i = 0
VIDEO_OUTPUT = sys.argv[2] BLUR_FACTOR = 40 RESIZE_SIZE = (1280, 720) THREADS = 8 # how many threads to run the program in GHOST_FRAME_COUNT = 8 segments = [] frames_before = [] # Instantiate an Alpr class alpr = Alpr("us", "/usr/share/openalpr/config/openalpr.defaults.conf", "/usr/share/openalpr/runtime_data") # Exit if it is not ready if not alpr.is_loaded(): exit(-1) # Define the opencv capture for the video cap = cv2.VideoCapture(VIDEO_TO_TEST) # Make it smoler cap.set(3, 1280) cap.set(4, 720) # Retrieve the amount of frames in the video (for progress) length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
def __init__(self): super().__init__() self.alpr = Alpr(self.region, self.configuration, self.runtime) # init alpr engine # self.camera = cv2.VideoCapture("D:\\others\\20191125_141145.mp4") # record frames from video source self.camera = cv2.VideoCapture(1) # record frames from video source
call = "ffmpeg -rtsp_transport tcp -r 25 -y -i rtsp://108.45.109.111:9209/live0.264 -updatefirst 1 -r 2 cam09.bmp" ############################################### # Load the baseline image bfilename = 'cam09_bg.bmp' bim = cv2.imread(bfilename) bimgray = cv2.cvtColor(bim, cv2.COLOR_BGR2GRAY) team = ['*****@*****.**'] # Init status occupied = [False, False, False] alpr = Alpr("us","/etc/openalpr/openalpr.conf","/usr/share/openalpr/runtime_data") bad_count = 0 for timer in range(int(n_checks)): # By default, no one is there now_occupied = [False, False, False] # Load test image fname = 'cam09.bmp' #fname = 'cam09.bmp' #fname = '/home/acp/work/camera_testing/hosafe/cam9/just_lx.bmp' #fname = '/home/acp/work/camera_testing/hosafe/cam9/lx.bmp' #fname = '/home/acp/work/camera_testing/hosafe/cam9/tess.bmp' #fname = '/home/acp/work/camera_testing/hosafe/cam9/bg.bmp' try:
parser.add_argument("--config", dest="config", action="store", default="/etc/openalpr/openalpr.conf", help="Path to openalpr.conf config file" ) parser.add_argument("--runtime_data", dest="runtime_data", action="store", default="/usr/share/openalpr/runtime_data", help="Path to OpenALPR runtime_data directory" ) parser.add_argument('plate_image', help='License plate image file') options = parser.parse_args() alpr = None files = [] try: __location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__))) alpr = Alpr("eu", options.config, options.runtime_data) if not alpr.is_loaded(): print("Error loading OpenALPR") else: #print("Using OpenALPR " + alpr.get_version()) files += [each for each in os.listdir('.') if each.endswith('.png')] print("<table>"); for file in files: alpr.set_top_n(7) alpr.set_default_region("eu") alpr.set_detect_region(True) jpeg_bytes = open(__location__+file, "rb").read() results = alpr.recognize_array(jpeg_bytes) # Uncomment to see the full results structure
parser.add_argument("-c", "--country", dest="country", action="store", default="us", help="License plate Country" ) parser.add_argument("--config", dest="config", action="store", default="/etc/openalpr/openalpr.conf", help="Path to openalpr.conf config file" ) parser.add_argument("--runtime_data", dest="runtime_data", action="store", default="/usr/share/openalpr/runtime_data", help="Path to OpenALPR runtime_data directory" ) parser.add_argument('plate_image', help='License plate image file') options = parser.parse_args() alpr = None try: alpr = Alpr(options.country, options.config, options.runtime_data) if not alpr.is_loaded(): print("Error loading OpenALPR") else: print("Using OpenALPR " + alpr.get_version()) alpr.set_top_n(7) alpr.set_default_region("wa") alpr.set_detect_region(False) jpeg_bytes = open(options.plate_image, "rb").read() results = alpr.recognize_array(jpeg_bytes) # Uncomment to see the full results structure # import pprint # pprint.pprint(results)
from openalpr import Alpr import sys alpr = Alpr("eu", "nplate_train/openalpr.conf.in", "nplate_train/runtime_data") if not alpr.is_loaded(): print("Error loading OpenALPR") sys.exit(1) #alpr.set_top_n(20) alpr.set_default_region("eu") results = alpr.recognize_file("/home/riaz/Desktop/hack/2009_09_08_drive_0010/I1_000388.png") for plate in results['results']: if len(plate['candidates']) > 0: print "Found: %12s %12f" % ( plate['candidates'][0]['plate'],plate['candidates'][0]['confidence']) # Call when completely done to release memory alpr.unload()
from multiprocessing import Process from multiprocessing.sharedctypes import Value from ctypes import c_double import threading import argparse import time import numpy as np import cv2 import sys import Levenshtein import csv with open('VQ_KT_AGH_PARKING_LOT.csv', 'rb') as f: reader = csv.reader(f) plates_list = map(tuple, reader) alpr = Alpr("us", "/etc/openalpr/openalpr.conf", "/home/pi/openalpr/runtime_data") if not alpr.is_loaded(): print("Error loading OpenALPR") sys.exit(1) n = 5 alpr.set_top_n(n) alpr.set_default_region("va") filepath = "/media/pi/F794-4B38/agh_src1_hrc0.avi" src = filepath[24:28] cap = cv2.VideoCapture(filepath) #cap = cv2.VideoCapture("/media/pi/F794-4B38/agh_src1_hrc11.flv") if not cap.isOpened(): print("vid open error") cap.open()