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;
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'])
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 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 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 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 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 scan(): # change definitions to define parameters of openalpr subprocess.call( "fswebcam -r 1920x1080 -S 20 --set brightness=50% --no-banner /home/pi/Desktop/BruinLabsParking/license_plate.jpg", shell=True) alpr = Alpr(location, config_path, runtime_path) if not alpr.is_loaded(): print("Failed to load OpenALPR") sys.exit() plates = alpr.recognize_file("license_plate.jpg") # checks if there is car in frame else returns if len(plates['results']) == 0: return else: # return the top 3 candidates candidates = [ plates['results'][0]['candidates'][i]['plate'] for i in range(0, 3) ] return candidates alpr.unload()
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 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 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 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 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"
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 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']
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 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 main(args): cap, out = get_video(args) # Grab the shape of the input width = int(cap.get(3)) height = int(cap.get(4)) color_state_image = np.zeros((width, height, 3)) alpr = Alpr("eu", "./ALPR/alpr_config/runtime_data/gb.conf", "./ALPR/alpr_config/runtime_data") if not alpr.is_loaded(): print("Error loading OpenALPR") sys.exit(1) lib_merges = [] while True: ret, frame = cap.read() if ret == True: with MPIPoolExecutor(max_workers=3) as executor: results = [] for result in executor.map(mpi_function, range(3), [args]*3, [frame]*3, [cap]*3, [color_state_image]*3): results.append(result) if args.save_video: out.write(output) if args.real_time: cv2.imshow(identifier, output) else: break if out is not None: out.release() if cap is not None: cap.release()
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
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 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 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 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 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 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 init_alpr(): global _alpr do_init = False if _alpr is None: _alpr = Alpr('us', CONFIG, RUNTIME) do_init = True if not _alpr.is_loaded(): raise Exception('Error loading OpenALPR') return do_init
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 scan(): try: print("Starting scan") # Send information over carplateNum = "" carplateList = [] # Take Photo print("Taking picture") cam = PiCamera() cam.start_preview() time.sleep(2) pictime = datetime.datetime.now() picname = pictime.strftime( "/home/pi/Desktop/%Y-%m-%d_%H-%M-%S_pic.jpg") cam.capture(picname) cam.stop_preview() cam.close() # Scan with ALPR print("Scanning picture") result = ["0"] alpr = Alpr("eu", "/etc/openalpr/openalp.conf", "/usr/share/openalpr/runtime_data") if not alpr.is_loaded(): print("Failed to load OpenALPR", "error") result[0] = "-1" return result results = alpr.recognize_file(picname) if os.path.exists(picname): os.remove(picname) else: print("The file does not exist") if len(results['results']) > 0: # Print out carplates for plate in results['results']: for candidate in plate['candidates']: carplateNum = candidate['plate'] # TODO: Filter irrelevant carplate result before sending to note carplateList.append(carplateNum) print(carplateList) response = requests.post(url=endpoint, json={'carplates': carplateList}) # Print out status code print(response) # Print out the information sent over except Exception: print("error") return
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)
def get_plate_alpr(img_path): openalprConf = r"F:\Kerja\PT AGIT\Bootcamp\AGIT Bootcamp Task\OJT\openalpr64-sdk-2.8.101\openalpr.conf" openalprRuntimeData = r"F:\Kerja\PT AGIT\Bootcamp\AGIT Bootcamp Task\OJT\openalpr64-sdk-2.8.101\runtime_data" alpr = Alpr("id", openalprConf, openalprRuntimeData) if not alpr.is_loaded(): print("Error loading OpenALPR") sys.exit(1) results = alpr.recognize_file(img_path) # alpr.unload() return results
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 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 start_capture_plates_blacklist(data): cap = cv2.VideoCapture(data['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) response_json = black_list_insert(data, plate['plate']) print(response_json) lastPlate = plate['plate'] alpr.unload() cv2.destroyAllWindows() return response_json
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 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()
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()