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 recognise(image: str) -> str: """ Args: image(str): Image path Returns: Plate number string """ # TODO: To find a way to merge open_alpr with open_alpr_window by making the config paths platform independent # Change this paths correspondingly config_file = 'C:\\Users\\Ani\\Downloads\\openalpr\\openalpr-2.3.0\\config\\openalpr.conf.defaults' runtime_dir = "C:\\Users\\Ani\\Downloads\\openalpr\\openalpr-2.3.0\\runtime_data" alpr = Alpr('eu', config_file, runtime_dir) if not alpr.is_loaded(): print("Error loading OpenALPR") sys.exit(1) alpr.set_top_n(1) results = alpr.recognize_file(image) plate_number = results['results'][0]['plate'][-7:] if plate_number: return plate_number return "Plate number not found"
def process(): alpr = Alpr(REGION, OPENALPR_CONF, RUNTIME_DIR) if not alpr.is_loaded(): LOGGER.info("Error loading OpenALPR") sys.exit(1) # 5 cikarimda bulun alpr.set_top_n(5) results = alpr.recognize_file(ARGS['image']) i = 0 for plate in results['results']: i += 1 print("Plaka #%d" % i) print(" %12s %12s" % ("Plaka", "Dogruluk")) 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 pipeline(foto): alpr = Alpr("us", "/etc/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("md") results = alpr.recognize_ndarray(foto) 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 = "*" if len(candidate["plate"] ) == 6 and candidate["confidence"] >= 50.0: print("Plate: " + str(candidate["plate"]) + " Confidence:" + str(candidate["confidence"])) # print(" %s %12s%12f" % (prefix, candidate['plate'], candidate['confidence'])) # Call when completely done to release memory alpr.unload()
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 numplate(image_path, num_coincidence=10): ''' Retorna los patrones encontrados en la imagen que se ingresa y que concuerdan con el archivo de patrones que configuramos anteriormente. Parameters ---------- image_path: Recibe el path de la imagen a procesar (obligatorio) num_coincidence: El numero de patrones posibles que deseamos analizar (no es obligatorio, por default es 10) Returns ------- De salida nos entrega una lista con diccionarios con los patrones posibles y su porcentaje de coincidencia ''' alpr = Alpr(COUNTRY_CODE, CONF_PATH, RUNTIME_PATH) if not alpr.is_loaded(): print('Error cargando openALPR') sys.exit(1) alpr.set_top_n(num_coincidence) alpr.set_default_region(REGION_CODE) results = alpr.recognize_file(image_path) correct_plates = [] for plate in results['results']: correct_plates = get_candidates(plate) alpr.unload() return correct_plates
class LicenseDetector: def __init__(self, runtime_data='/usr/share/openalpr/runtime_data/'): self.runtime_data = runtime_data self.cache = ExpiringDict(max_len=100, max_age_seconds=5) self.init_alpr() def license_detect(self, image): results = self.alpr.recognize_ndarray(image) i = 0 for plate in results['results']: for candidate in plate['candidates']: if 90 <= candidate['confidence']: self.cache[candidate['plate']] = self.cache.get( candidate['plate'], 0) + 1 sort_orders = sorted(self.cache.items(), key=lambda itm: itm[1], reverse=True) return (sort_orders[0][0] if sort_orders else None) def init_alpr(self): self.alpr = Alpr("us", "/etc/openalpr/openalpr.conf", self.runtime_data) if not self.alpr.is_loaded(): print("Error loading OpenALPR") sys.exit(1) self.alpr.set_top_n(20) self.alpr.set_default_region("md")
def coordRetrv(conf, runtime, image_location): # configure ALPR setting according to config file alpr = Alpr("us", conf, runtime) # Tests if ALPR is able to open if not alpr.is_loaded(): print("Error loading OpenALPR") sys.exit(1) # Gets the top result from ALPR for each plate alpr.set_top_n(1) alpr.set_default_region("tx") # Loads results from the openALPR library # jpeg_bytes = open(image_location, "rb").read() # img_bytes = image_location.tobytes() success, img_numpy = cv2.imencode('.jpg', image_location) img_binary = img_numpy.tostring() results = alpr.recognize_array(img_binary) result = results['results'] # print(result) # Prints the number of license plates # print(len(result)) # TODO: Figure out why this isnt working(maybe needs to be called at end of main # alpr.unload() # return list of all license plates in picture according to ALPR return result
def openALPR(): #reading the picture print('STARTED: ALPR') try: global database alpr = None alpr = Alpr('gb', '/etc/openalpr/openalpr.conf', '/home/pi/openalpr/runtime_data') if not alpr.is_loaded(): print("Error loading OpenALPR") return False else: database = [] alpr.set_top_n(7) alpr.set_default_region("gb") alpr.set_detect_region(False) jpeg_bytes = open('Plates/Plate.jpg', "rb").read() #testing results = alpr.recognize_array(jpeg_bytes) i = 0 for plate in results['results']: i += 1 for candidate in plate['candidates']: plate = [candidate['plate'], candidate['confidence']] database.append(plate) if database == []: remove(filepath) print('FINISHED: ALPR unsucessful') return False else: print(database) print('FINISHED: ALPR sucessful') return True except AttributeError: print()
class MariaBack: def __init__(self): self.alpr = Alpr("mx", "/etc/openalpr/openalpr.conf", "/usr/share/openalpr/runtime_data") if not self.alpr.is_loaded(): print("Error loading OpenALPR") sys.exit(1) self.alpr.set_top_n(3) def startWatchingaBack(self): cap = cv2.VideoCapture(0) while(True): ret, frame = cap.read() filename = "temp2.jpg" time.sleep(5) cv2.imwrite(filename, frame) results = self.alpr.recognize_file("./temp2.jpg") if len(results['results']) != 0: yield results['results'] if cv2.waitKey(1) & 0xFF == ord('q'): break def sendRecognizedPlateBack(self, plate): r = requests.post("http://192.168.0.10:80/maria/recognize-plate/?username=BenjaminGuzman&password=MariaUribe&plate={}".format(plate), auth=("BenjaminGuzman", "MariaUribe")) print(r.status_code) print("Esta es la respuesta del servido "+str(r.text)) if r.text != "true": return 0 return 1
def detect(path): alpr = Alpr("us", "/etc/openalpr/openalp.conf", "/usr/share/openalpr/runtime_data") if not alpr.is_loaded(): print("Error loading OpenALPR") sys.exit(1) alpr.set_top_n(20) #top candidates alpr.set_default_region("ca") #default region results = alpr.recognize_file(path) largestPlate = None largestArea = 0 for plate in results['results']: coords = plate['coordinates'] topLeft = coords[0] bottomRight = coords[2] w = bottomRight['x'] - topLeft['x'] h = bottomRight['y'] - topLeft['y'] prevArea = largestArea largestArea = max(w * h, largestArea) if (prevArea != largestArea): largestPlate = plate # Call when completely done to release memory alpr.unload() if largestPlate == None: return [] return largestPlate['candidates']
class NplateExtraction: def __init__(self, confgpath): self.confgpath = confgpath config = ConfigParser() config.read(self.confgpath) self.confsect = config['NPEConfig'] self.alprconfig = self.confsect['alprconfig'] self.alprruntime = self.confsect['alprruntime'] self.imagepath = self.confsect['objImage'] self.alpr = Alpr("us", self.alprconfig, self.alprruntime) self.alpr.set_top_n(4) #self.alpr.set_default_region("us") print(self.alpr.is_loaded()) if not self.alpr.is_loaded(): print("Error loading OpenALPR") sys.exit(1) #print(self.alprconfig) def getplate(self, imagepath): results = self.alpr.recognize_file(imagepath) xtop = results['results'][0]['coordinates'][0]['x'] ytop = results['results'][0]['coordinates'][0]['y'] width = int(results['results'][0]['coordinates'][1]['x']) - int(xtop) height = int(results['results'][0]['coordinates'][3]['x']) - int(ytop) retresult = { "plate": results['results'][0]['candidates'][0]['plate'], "confidence": results['results'][0]['candidates'][0]['confidence'], "xtop": xtop, "ytop": ytop, "width": width, "height": height } return json.dumps( retresult, indent=4 ) #(results['results'][0]['candidates'][0],results['results'][0]['coordinates'])
class Plate: def __init__(self): self.alpr = Alpr("eu", "/etc/openalpr/conf", "/usr/share/openalpr/runtime_data") if not self.alpr.is_loaded(): print("Erro ao carregar o ALPR..") sys.exit(1) self.alpr.set_top_n(10) self.alpr.set_default_region("") def plate_ocr(self, placa): results = self.alpr.recognize_file(placa) i = 0 plate = "" for plate in results['results']: i += 1 for candidate in plate['candidates']: if candidate['matches_template']: prefix = "*" teste = candidate['plate'] x = re.search('^[A-Z]{3}[0-9]{1}[A-Z]{1}[0-9]{2}', teste) if (x): plate = candidate['plate'] #return plate break self.alpr.unload() if (plate != ""): print(plate) return plate
def recognize(): global first_plate alpr = Alpr("auwide", "openalpr/config/openalpr.conf", "openalpr/runtime_data") if not alpr.is_loaded(): print("Error loading OpenALPR") sys.exit(1) alpr.set_top_n(1) #alpr.set_default_region("vic") results = alpr.recognize_file("test_out.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'])) first_plate = candidate['plate'] # Call when completely done to release memory alpr.unload()
def recognize_license_plate(image, obj_meta, confidence): #silly way to detect license plates if (obj_meta.class_id == 1): #Importing openalpr print('Importing alpr') alpr_engine = Alpr("eu", "/etc/openalpr/openalpr_rai.conf", "/usr/share/openalpr/runtime_data") if not alpr_engine.is_loaded(): print("Error loading OpenALPR") sys.exit(1) alpr_engine.set_top_n(10) alpr_engine.set_default_region("fi") frame_number = random.randint(0, 100) rect_params = obj_meta.rect_params top = int(rect_params.top) left = int(rect_params.left) width = int(rect_params.width) height = int(rect_params.height) lp_cutout = image[top:top + height, left:left + width, :] cv2.imwrite( "/opt/nvidia/deepstream/deepstream-5.0/sources/python/apps/deepstream-test10-helloworld6/" + str(frame_number) + "_lpcut.jpg", lp_cutout) cv2.imwrite( "/opt/nvidia/deepstream/deepstream-5.0/sources/python/apps/deepstream-test10-helloworld6/" + str(frame_number) + "_image.jpg", image) results = alpr_engine.recognize_ndarray(lp_cutout) print(results) alpr_engine.unload()
class AlprPredict: def __init__(self, task_queue, result_queue): self.alpr = Alpr('eu', '/usr/share/openalpr/config/openalpr.defaults.conf', '/usr/share/openalpr/runtime_data') self.alpr.set_top_n(1) self.alpr.set_default_region('lt') self.task_queue = task_queue self.result_queue = result_queue self.run() def run(self): while True: self.predict() def predict(self): image = self.task_queue.get() result = None try: recog_results = self.alpr.recognize_array(image)['results'] if len(recog_results) != 0: result = recog_results[0]['plate'] except Exception as e: logging.error(e) result['status'] = 0 self.result_queue.put(result)
def Alpr_run(): camera = PiCamera() camera.resolution = (1920, 1080) # TODO: change these depending on platform alpr = Alpr("us", "/home/zib/Senior-Design-ALPR/src/build/config/openalpr.conf", "/home/zib/Senior-Design-ALPR/runtime_data") if not alpr.is_loaded(): print("Error loading OpenALPR") foundmatch[0] = 7 sys.exit(1) alpr.set_top_n(10) try: while True: camera.capture('/home/zib/plates/image.jpg') results = alpr.recognize_file("/home/zib/plates/image.jpg") if foundmatch[0] == 8: alpr.unload() #print "Thead exitted" sys.exit() for plate in results['results']: if foundmatch[0] == 8: alpr.unload() #print "Thead exitted" sys.exit() for candidate in plate['candidates']: if candidate['confidence'] >= 85: # hit_index will be used by the gui to fill in the desired info for display when a match occurs # May or may not be useful if separate processes between gui and this hit_index = 0 for entry in dBase: if candidate['plate'] == entry['plate']: # XXX: Location to add logging, like copy picture, or add to a log file #Conditional works as both a lock and the signal to wake the thread back up alprwake.acquire() foundmatch[0] = 1 foundindex[0] = hit_index alprwake.wait() #Sleeps till notified alprwake.release() break else: hit_index += 1 if foundmatch[0] == 8: alpr.unload() #print "Thead exitted" sys.exit() alpr.unload() #print "Thead exitted" except KeyboardInterrupt: alprwake.acquire() foundmatch[0] = 7 alprwake.release() alpr.unload() #print "Thread exitted" sys.exit()
def faceDetection(self, frame): global value global percentage alpr = Alpr("pak", "path/config/openalpr.conf", "path/openalpr/runtime_data") frame = cv2.resize(frame, (740, 480)) faces = plateCascade.detectMultiScale(frame, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30)) self.allfaces = faces for (x, y, w, h) in faces: cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 4) cv2.putText(frame, str(value) + "-" + str(percentage) + "%", (x - 10, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2) 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) cv2.imwrite("1.png", frame) jpeg_bytes = open("1.png", "rb").read() results = alpr.recognize_array(jpeg_bytes) print("Image size: %dx%d" % (results['img_width'], results['img_height'])) print("Processing Time: %f" % results['processing_time_ms']) #print(str(results['results'][0][0]['candidates']['plate'])) i = 0 count = 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 = "*" if count >= 1: break print( " %s %12s%12f" % (prefix, candidate['plate'], candidate['confidence'])) value = candidate['plate'] percentage = candidate['confidence'] count = count + 1 self.bbFrame = frame
def main(): global license_plates alpr = Alpr( 'us', 'C:/Users/dhruv/Desktop/Git/openalpr-2.3.0-win-64bit/openalpr_64/openalpr.conf', 'C:/Users/dhruv/Desktop/Git/openalpr-2.3.0-win-64bit/openalpr_64/runtime_data' ) if not alpr.is_loaded(): print("Error loading OpenALPR") sys.exit(1) alpr.set_top_n(10) alpr.set_default_region("on") cap = cv2.VideoCapture(0) if not cap.isOpened(): alpr.unload() sys.exit('Failed to open video file!') curr_plate = '' while cap.isOpened(): ret, frame = cap.read() cv2.imshow('frame', frame) frame = cv2.resize(frame, (1280, 780)) cv2.imwrite('temp.png', frame) results = alpr.recognize_file("temp.png") array_of_plates = [] for plate in results['results']: for candidate in plate['candidates']: if candidate['matches_template']: array_of_plates.append( [candidate['plate'], candidate['confidence']]) if len(array_of_plates) > 0: plate = array_of_plates[0][0] max_confidence = array_of_plates[0][1] for i in array_of_plates: if i[1] > max_confidence: print("MAX") max_confidence = i[1] plate = i[0] license_plates.append(plate) print("{} {}".format(plate, max_confidence)) if len(license_plates) >= 36: print("License Plate Detected: {}".format( most_frequent(license_plates))) license_plates = [] if cv2.waitKey(1) == 27: break cv2.destroyAllWindows() cap.release() 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, id): alpr = Alpr("eu", "/etc/openalpr/openalpr.conf", "../runtime_data") if not alpr.is_loaded(): print("Error loading OpenALPR") exit() alpr.set_top_n(20) self.alpr = alpr self.notifier = Notifier() self.id = id self.source = DataSource(self)
class ManFirebase(): global url, write_data, accuracy, lpn, region, topn, plate_link, config, child def __init__(self): self.config = config self.child = child #### self.firebase = pyrebase.initialize_app(self.config) self.db = self.firebase.database() self.write_data = write_data self.accuracy = accuracy self.lpn = lpn self.post_date = strftime("%a, %d %b %Y %H:%M:%S", gmtime()) self.region = region self.topn = topn self.plate_link = plate_link self.start = 0 self.alpr = Alpr(self.region, './conf/def_one.defaults', './openalpr/runtime_data') self.alpr.set_top_n(self.topn) self.alpr.set_default_region('md') def get_data(self): self.data = self.db.child(self.child).get() print(self.data) def write(self): new_car = { 'accuracy': self.accuracy, 'date': self.post_date, 'lpn': self.lpn } self.db.child(self.child).push(new_car) print(new_car) def recognize_plates(self): self.plate_result = self.alpr.recognize_file(self.plate_link) for plate_number in self.plate_result['results']: self.start += 1 for candiate in plate_number['candidates']: self.lpn = candiate['plate'] self.accuracy = candiate['confidence'] self.alpr.unload() if self.lpn == '': print("No plates recognozed") sys.exit(1) self.write()
def add_shot_by_creenj(number, image, current_plate): setlocale(0, "C") db = Database() logger.info('So, here we get vals from queue at creenj') logger.info(number + '\n' + current_plate + '\n' + image) logging.info('from gf_sqlite_creenj, so number is %s' % number) if number == '': try: alpr = Alpr('eu', '/usr/share/openalpr/config/openalpr.defaults.conf', '/usr/share/openalpr/runtime_data') print("Camed to ALPR") if not alpr.is_loaded(): print("Error loading OpenALPR") sys.exit(1) alpr.set_top_n(20) alpr.set_default_region("lt") results = alpr.recognize_file(image) answer = results['results'][0]['plate'] alpr.unload() except Exception as e: print('Couldn\'t load ALPR') answer = 'Unsolved' return if answer == '': return print('creenj Answer is ', answer) json_obj = { 'number': answer, 'image': image, 'current_plate': current_plate } conn = sqlite3.connect(config.DB_PATH) c = conn.cursor() query = 'INSERT INTO ' + db.SHOTS_TABLE_NAME + ' VALUES (?,?,?)' values = [json_obj['number'], json_obj['current_plate'], json_obj['image']] values = list(map( str, values)) # conversion of int (values[0]) to str is ok here c.executemany(query, [values]) # actually executes only once conn.commit() # apply changes c.close() conn.close() logger.info('So, it should be in DB')
def start_capture_plates(rtsp): cap = cv2.VideoCapture(rtsp) global lastPlate alpr = Alpr("mx", "openalpr.conf", "runtime_data") if not alpr.is_loaded(): print("Error al Cargar Librería: OpenALPR") alpr.set_top_n(20) alpr.set_default_region("mx") if alpr.is_loaded(): while cap.isOpened(): ret, img = cap.read() img_str = cv2.imencode('.jpg', img)[1].tostring() # cv2.imshow('img', img) results = alpr.recognize_array(img_str) print(results) for plate in results['results']: len_plate = len(plate['plate']) if len_plate == 7: cv2.putText(img, plate['plate'], (plate['coordinates'][0]['x'], plate['coordinates'][0]['y']), 0, 2, (255, 0, 0), 3) cv2.rectangle(img, (plate['coordinates'][0]['x'], plate['coordinates'][0]['y']), (plate['coordinates'][2]['x'], plate['coordinates'][2]['y']), (255, 0, 0), 3) cv2.imshow('img', img) report_plate = black_list(plate['plate']) if report_plate.status == 200: access_tagger(plate['plate']) lastPlate = plate['plate'] response_json = { 'message': 'Acceso Permitido', 'payload': { 'plate': lastPlate, 'description': 'Lorem Ipsum Dolor' } } alpr.unload() cv2.destroyAllWindows() return jsonify(response_json) else: alpr.unload() cv2.destroyAllWindows() response_json = report_plate return response_json
def main(): try: print("Starting...") alpr = Alpr(country, config, runtime_data) if not alpr.is_loaded(): print("Error loading OpenALPR") else: print("Using OpenALPR " + alpr.get_version()) alpr.set_top_n(1) alpr.set_detect_region(False) # initialize the video stream and allow the cammera sensor to warmup video_source = (0 if options["videosource"] == None else options["videosource"]) vs = VideoStream(usePiCamera=options["picamera"] > 0, src=video_source).start() time.sleep(2.0) _frame_number = 0 print("Running...") # loop over the frames from the video stream while True: frame = vs.read() #frame = imutils.resize(frame) #frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) _frame_number += 1 if _frame_number % FRAME_SKIP == 0: frame_array = (cv2.imencode(".jpg", frame)[1]).tostring() results = alpr.recognize_array(frame_array) if len(results["results"]) > 0: pool.apply_async(_validate, args=[frame_array, results, device, iot, storage]) if options["imshow"]: # show the frame cv2.imshow("Frame", frame) key = cv2.waitKey(1) & 0xFF # if the `q` key was pressed, break from the loop if key == ord("q"): break except: print("[main] Unexpected error:", sys.exc_info()) finally: if alpr: alpr.unload() pool.close() cv2.destroyAllWindows() vs.stop()
def plate_detection(self, frame): alpr = Alpr('eu', '/etc/openalpr/openalpr.conf', '/usr/share/openalpr/runtime_data') if not alpr.is_loaded(): raise AlprException("Error loading openALPR") alpr.set_top_n(1) results = alpr.recognize_ndarray(frame) if results['results'] != []: self.plate_as_text(results)
def recognizePlate(self): self.camera.capture('images/1.jpg') 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(20) alpr.set_default_region("md") results = alpr.recognize_file("images/1.jpg") nPos = 2 sepPos = [259, 480] tmpPlate = {} i = 0 for plate in results['results']: i += 1 x = plate['coordinates'][0]['x'] number = plate['candidates'][0]['plate'] tmpPlate[x] = number print( "Plate #%d, (%d,%d)(%d,%d)" % (i, plate['coordinates'][0]['x'], plate['coordinates'][0]['y'], plate['coordinates'][1]['x'], plate['coordinates'][1]['y'])) print(" %12s %12s" % ("Plate", "Confidence")) for candidate in plate['candidates']: print(" %12s%12f" % (candidate['plate'], candidate['confidence'])) sortedKey = sorted(tmpPlate) res = {1: "", 2: "", 3: ""} nPlate = len(tmpPlate) pos = 0 keyIndex = 0 while pos < nPos and keyIndex < nPlate: if sepPos[pos] > sortedKey[keyIndex]: res[pos + 1] = tmpPlate[sortedKey[keyIndex]] keyIndex += 1 pos += 1 while keyIndex < nPlate: res[pos + 1] = tmpPlate[sortedKey[keyIndex]] keyIndex += 1 pos += 1 # alpr.unload() print(res) return res
def init_detector(): vn_detector = Alpr("vn", "openalpr.conf", "runtime_data") vn2_detector = Alpr("vn2", "openalpr.conf", "runtime_data") if not (vn_detector.is_loaded() or vn2_detector.is_loaded()): print("Error loading OpenALPR") raise Exception("Error loading OpenALPR") vn_detector.set_top_n(5) vn_detector.set_default_region("base") vn2_detector.set_top_n(5) vn2_detector.set_default_region("base") return vn_detector, vn2_detector
def identifica_us_eu(str_padrao): autorizado = False alpr = Alpr(str_padrao, "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("md") results = alpr.recognize_file( "/home/marcos/Desktop/prototipo 3/placas mercosul/4.jpg") i = 0 for plate in results['results']: i += 1 for candidate in plate['candidates']: prefix = "-" if candidate['matches_template']: prefix = "*" licPlate = results print(" %s %12s%12f" % (prefix, candidate['plate'], candidate['confidence'])) obj = json.load(open("cadastros.json")) for i in xrange(len(obj)): if obj[i]["id"] == candidate[ 'plate']: # se encontrar no cadastro grava entrada autorizado = True with open('entradas.json') as data_file: old_data = json.load(data_file) data = [{ "placa": candidate['plate'], "dia": time.strftime("%d/%m/%Y"), "hora": time.strftime("%H:%M:%S"), "liberadopor": "Open VCR" }] data = old_data + data path = '/home/marcos/Desktop/prototipo 3' filePathNameWExt = path + '/' + 'entradas' + '.json' with open(filePathNameWExt, 'w') as fp: json.dump(data, fp) break if autorizado: print(" %12s %12s" % ("Placa", "Certeza")) print(" %s %12s%12f" % (prefix, candidate['plate'], candidate['confidence'])) # printa dentro da funcao, so para demonstrar que identifica a placa, no final nao ira precisar desse print return autorizado
def get_alpr(region, path): """Return Alpr object with the specified region of license plate""" alpr = Alpr( region, "/etc/openalpr/openalpr.conf", path + "/runtime_data", ) if not alpr.is_loaded(): print("Error loading OpenALPR") raise Exception("Invalid OpenALPR config") alpr.set_top_n(20) alpr.set_default_region("md") return alpr
def lp_detect(): parser = argparse.ArgumentParser( description='Arguments for inside or outside camera.') parser.add_argument('--threaded', action='store_true', help='Put each frame on it\'s own thread') args = parser.parse_args() alpr = Alpr("us", "./tx2.conf", "/usr/share/openalpr/runtime_data") if not alpr.is_loaded(): print("Error loading OpenALPR") sys.exit(1) alpr.set_top_n(2) cap = cv2.VideoCapture(gstreamer_pipeline(flip_method=2), cv2.CAP_GSTREAMER) if cap.isOpened(): frame = 0 cv2.namedWindow('License Plate Detect', cv2.WINDOW_AUTOSIZE) while cv2.getWindowProperty('License Plate Detect', 0) >= 0: ret, img = cap.read() if ret: frame += 1 try: if args.threaded: t = threading.Thread(target=look_at_plate, args=(alpr, img)) t.start() else: look_at_plate(alpr, img) except Exception as e: print('App error: {0}'.format(e)) cv2.imshow('License Plate Detect', img) keyCode = cv2.waitKey(30) & 0xff # Stop the program on the ESC key if keyCode == 27: print('Escape key was pressed') time.sleep(1) break print('Closing cap') cap.release() print('Closing windows') cv2.destroyAllWindows() time.sleep(1) print('Closing alpr') alpr.unload() else: print("Unable to open camera")
def find_images(Filename, car_where): #while(True): alpr = Alpr("kr", "/etc/openalpr/openalpr.conf", "/usr/local/share/openalpr/runtime_data") print("find_image arrive") 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(Filename) i = 0 car_info = [] if (results['results'] == []): return for plate in results['results']: i += 1 print("Plate #%d" % i) print(" %12s %12s" % ("Plate", "Confidence")) #print plate for candidate in plate['candidates']: #plate의 갯수대로 #print"plate",plate['candidates'] prefix = "-" if candidate['matches_template']: prefix = "*" print(" %s %12s%12f" % (prefix, candidate['plate'], candidate['confidence'])) #max =candidate['confidence'] car_info.append(candidate['plate'].encode("UTF-8")) print "car_info", str(car_info[0]) #print(accuracy) #print(car_full_info) car_1st_info = str(car_info[0]) car_string = car_1st_info[:5] car_number = car_1st_info[5:] print car_string, car_number, car_where send_data.send_server(Filename, car_1st_info, car_string, car_number, car_where) # Call when completely done to release me mory alpr.unload()
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"
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) 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
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):
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),
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() #[item for item in plates_list if item[0] == src] #resX = 240 #resY = 180 #fourcc = cv2.VideoWriter_fourcc(*'XVID') #out = cv2.VideoWriter('test.avi',fourcc, 20.0, (resX, resY))
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()
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 while True: ret, frame = cap.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
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")