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()
import sys alpr = Alpr("us", "/usr/local/src/openalpr/src/config/openalpr.conf", "/usr/local/src/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("/home/pi/ea7the.jpg") i = 0 for plate in results['results']: i += 1 #print("Plate #%d" % i) #print(" %12s %12s b" % ("Plate", "Confidence")) for candidate in plate['candidates']: prefix = "-" if candidate['matches_template']: prefix = "*" #print(" %s %12s%12f " % (prefix, candidate['plate'], candidate['confidence'])) break break print(candidate['plate']) # 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()
class recognizer(threading.Thread): min_conf_patternmatch = 75.0 min_conf_nopatternmatch = 85.0 lock = None def __init__(self, source_dir, postproc_hit_dir, postproc_nohit_dir, postproc_nohit_lowconf_dir=None, output_json_dir=None, output_csv_file=None, default_region=None, lock=None): threading.Thread.__init__(self) ## save the lock (if specified) ## passing in a lock object allows ## multiple recognizer threads to run ## without bumping into each other self.lock = lock ## check and clean up config ## TODO: use os.path to test files and directories, then raise appropriate errors self.source_dir = source_dir.rstrip("/") self.postproc_hit_dir = postproc_hit_dir.rstrip("/") self.postproc_nohit_dir = postproc_nohit_dir if (self.postproc_nohit_dir): self.postproc_nohit_dir = self.postproc_nohit_dir.rstrip("/") self.postproc_nohit_lowconf_dir = postproc_nohit_lowconf_dir if (self.postproc_nohit_lowconf_dir): self.postproc_nohit_lowconf_dir = self.postproc_nohit_lowconf_dir.rstrip( "/") else: self.postproc_nohit_lowconf_dir = self.postproc_nohit_dir if not (output_json_dir) and not (output_csv_file): raise (TypeError( 'must specify output_csv_file and/or output_json_dir')) self.output_json_dir = output_json_dir.rstrip("/") self.output_csv_file = output_csv_file print "recognizer:init - initializing alpr" self.alpr = Alpr("us", "/etc/openalpr/openalpr.conf", "/usr/share/openalpr/runtime_data") if not self.alpr.is_loaded(): print("recognizer:init - error loading OpenALPR") sys.exit(1) self.alpr.set_top_n(10) if (default_region): self.alpr.set_default_region(default_region) self.running = True print "recognizer:init - done initializing alpr" def __del__(self): print "recognizer:del - unloading alpr" self.alpr.unload() print "recognizer:del - done" def stop(self): print "recognizer:stop - waiting for recognizer thread to finish" self.running = False self.join() print "recognizer:stop - recognizer thread finished" def run(self): tid = self.ident while (self.running): sys.stdout.flush() time.sleep(0.05) files = sorted(os.listdir(self.source_dir)) # if (len(files) > 0): # print "recognizer:run[{}] - found {} files in {}".format(tid, len(files), self.source_dir) for file in files: # if we're supposed to be shutting down, then break out of the file processing loop if (self.running == False): break matches = [] lowconf_hit = False # make sure it looks like one of ours if (not (re.match('^\d+(.*)\.jpg$', file))): if file == "README" or file.startswith(".") or re.search( '.lock$', file): pass # silently ignore lock files and hidden files else: print "recognizer:run - ignoring file with bad name {}".format( file) else: # to be thread safe, create a lock file while we process img_file = self.source_dir + "/" + file lock_file = img_file + ".lock" # set up file lock while blocking other threads try: if (self.lock): self.lock.acquire() # does the file still exist? if not, skip it silently -- another thread processed already if not (os.path.exists(img_file)): continue # is the file already locked? if so, skip it and say something -- could be another thread working on it or could be a stale lock ## TODO: auto remove old locks try: lock_stat = os.stat(lock_file) if lock_stat: # lock file exists lock_age = time.time() - lock_stat.st_mtime if (lock_age > STALE_LOCK_AGE): print "recognizer:run - removing stale lock file ({:.0f}s) for {}".format( lock_age, file) os.unlink(lock_file) else: continue # file recently locked -- skip it silently except OSError: pass # ignore this error -- indicates lock file doesn't exist # create the lock file with open(lock_file, "w") as f: f.write("{}".format(self.ident)) finally: if (self.lock): self.lock.release() # do plate recognition start_time = time.time() results = self.alpr.recognize_file(self.source_dir + "/" + file) recognize_secs = time.time() - start_time print "recognizer:run - recognized {:s} in {:.4f}s found {:2d} possible plates".format( self.source_dir + "/" + file, recognize_secs, len(results['results'])) # remove lock file os.remove(lock_file) # review results for plate in results['results']: best_match_plate = None best_match_template = None best_match_confidence = 0.0 for candidate in plate['candidates']: if (candidate['matches_template']): if (candidate['confidence'] > self.min_conf_patternmatch and candidate['confidence'] > best_match_confidence): best_match_plate = candidate['plate'] best_match_confidence = candidate[ 'confidence'] best_match_template = True else: if (candidate['confidence'] > self.min_conf_nopatternmatch and candidate['confidence'] > best_match_confidence): best_match_plate = candidate['plate'] best_match_confidence = candidate[ 'confidence'] best_match_template = False if (best_match_plate): print "recognizer:run - best match: {} (confidence: {:.3f}, template: {})".format( best_match_plate, best_match_confidence, "yes" if best_match_template else "no") match = { 'recognize_time': time.strftime("%Y-%m-%d %H:%M:%S"), 'recognize_epoch_time': "{:.0f}".format(start_time), 'recognize_secs': "{:0.4f}".format(recognize_secs), 'plate': best_match_plate, 'confidence': "{:0.2f}".format(best_match_confidence), 'matches_template': best_match_template, 'file': file } matches.append(match) else: lowconf_hit = True print "recognizer:run - insufficient confidence" # record matches (if any) and move the file away if (len(matches) > 0): # extract GPS and other EXIF data, append to match record, then write output with open(self.source_dir + "/" + file, 'rb') as jpgfile: tags = exifread.process_file(jpgfile, details=False) # extract the image capture date and time if (tags['EXIF DateTimeOriginal']): exif_datetimeoriginal = time.strptime( "{}".format(tags['EXIF DateTimeOriginal']), '%Y:%m:%d %H:%M:%S') # extract the GPS coordinates (convert from DMS to DD) and altitude exif_gpslongitude = 0.0 exif_gpslatitude = 0.0 exif_gpsaltitude = 0 tag_lat = tags['GPS GPSLatitude'] if (tag_lat and len(tag_lat.values) == 3 and tag_lat.values[0].den > 0): exif_gpslatitude = ( float(tag_lat.values[0].num) / float(tag_lat.values[0].den)) + ( (float(tag_lat.values[1].num) / float(tag_lat.values[1].den)) / 60.0 ) + ((float(tag_lat.values[2].num) / float( tag_lat.values[2].den)) / 3600.0) exif_gpslatitude *= -1 if (str( tags['GPS GPSLatitudeRef']) == "S") else 1 tag_lon = tags['GPS GPSLongitude'] if (tag_lon and len(tag_lon.values) == 3 and tag_lon.values[0].den > 0): exif_gpslongitude = ( float(tag_lon.values[0].num) / float(tag_lon.values[0].den)) + ( (float(tag_lon.values[1].num) / float(tag_lon.values[1].den)) / 60.0 ) + ((float(tag_lon.values[2].num) / float( tag_lon.values[2].den)) / 3600.0) exif_gpslongitude *= -1 if (str( tags['GPS GPSLongitudeRef']) == "W") else 1 tag_altitude = tags['GPS GPSAltitude'] if (tag_altitude and tag_altitude.values[0].den > 0): exif_gpsaltitude = float( tag_altitude.values[0].num) / float( tag_altitude.values[0].den) # store EXIF data in match records for match in (matches): if (exif_datetimeoriginal): match[ 'capture_epoch_time'] = '{:.0f}'.format( time.mktime(exif_datetimeoriginal)) match['capture_time'] = time.strftime( "%Y-%m-%d %H:%M:%S", exif_datetimeoriginal) else: match['capture_epoch_time'] = 0 match['capture_time'] = '' match['capture_longitude'] = "{:0.7f}".format( exif_gpslongitude) match['capture_latitude'] = "{:0.7f}".format( exif_gpslatitude) match['capture_altitude_m'] = "{:0.2f}".format( exif_gpsaltitude) # write matches to CSV if (self.output_csv_file): write_header = False if os.access( self.output_csv_file, os.F_OK) else True try: # only one thread can write to the CSV at a time if (self.lock): self.lock.acquire() with open(self.output_csv_file, "a") as csvfile: writer = csv.DictWriter( csvfile, [ "recognize_time", "recognize_epoch_time", "plate", "confidence", "matches_template", "file", "recognize_secs", 'capture_time', 'capture_epoch_time', 'capture_latitude', 'capture_longitude', 'capture_altitude_m' ]) if (write_header): writer.writeheader() writer.writerow(match) finally: if (self.lock): self.lock.release() # write JSON (each file is unique, so no thread locking needed) if (self.output_json_dir): json_file = self.output_json_dir + "/" + file[:file.index( ".jpg")] + ".json" with open(json_file, "w") as jsonfile: jsonfile.write(json.dumps(matches)) # move the file os.rename(self.source_dir + "/" + file, self.postproc_hit_dir + "/" + file) elif (lowconf_hit): #insufficient confidence if (self.postproc_nohit_lowconf_dir): os.rename( self.source_dir + "/" + file, self.postproc_nohit_lowconf_dir + "/" + file) else: os.unlink(self.source_dir + "/" + file) else: #no hit if (self.postproc_nohit_dir): os.rename(self.source_dir + "/" + file, self.postproc_nohit_dir + "/" + file) else: os.unlink(self.source_dir + "/" + file)
def Alpr_run(): #camera = Camera() #camera = PiCamera() #camera.resolution = (1920,1080) # TODO: change these depending on platform alpr = Alpr( "us", "/home/blake/workspace/openalpr/src/build/config/openalpr.conf", "/home/blake/workspace/openalpr/runtime_data") if not alpr.is_loaded(): print("Error loading OpenALPR") foundmatch[0] = 7 sys.exit(1) alpr.set_top_n(10) # Do we want to specify md? #alpr.set_default_region("md") 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() #print(" %s %12s%12f%12s" % (prefix, candidate['plate'], candidate['confidence'],matched)) alpr.unload() #print "Thead exitted" except KeyboardInterrupt: alprwake.acquire() foundmatch[0] = 7 alprwake.release() alpr.unload() #print "Thread exitted" sys.exit()
def __init__(self, num_streams, step, resolution, thres, gpu=False, runtime=None, config=None, quiet=False): # Transfer parameters to attributes self.quiet = quiet self.message('Initializing...') self.num_streams = num_streams self.step = step if isinstance(resolution, str): if resolution == 'all': self.resolution = ['vga', '720p', '1080p', '4k'] else: self.resolution = [resolution] elif isinstance(resolution, list): self.resolution = resolution else: raise ValueError('Expected list or str for resolution, but received {}'.format(resolution)) self.thres = thres self.gpu = gpu # Detect operating system and alpr version if platform.system().lower().find('linux') == 0: self.operating = 'linux' self.cpu_model = get_cpu_model('linux') elif platform.system().lower().find('windows') == 0: self.operating = 'windows' self.cpu_model = get_cpu_model('windows') else: raise OSError('Detected OS other than Linux or Windows') self.message('\tOperating system: {}'.format(self.operating.capitalize())) self.message('\tCPU model: {}'.format(self.cpu_model)) alpr = Alpr('us', '', '') self.message('\tOpenALPR version: {}'.format(alpr.get_version())) alpr.unload() # Prepare other attributes if self.operating == 'linux': self.downloads = '/tmp/alprbench' else: self.downloads = os.path.join(os.environ['TEMP'], 'alprbench') if not os.path.exists(self.downloads): os.mkdir(self.downloads) self.cpu_usage = {r: [] for r in self.resolution} self.threads_active = False self.frame_counter = 0 self.mutex = Lock() self.streams = [] self.round_robin = cycle(range(self.num_streams)) self.results = PrettyTable() self.results.field_names = ['Resolution', 'Total FPS', 'CPU (Avg)', 'CPU (Max)', 'Frames'] # Define default runtime and config paths if not specified if runtime is not None: self.runtime = runtime else: self.runtime = '/usr/share/openalpr/runtime_data' if self.operating == 'windows': self.runtime = 'C:/OpenALPR/Agent' + self.runtime if config is not None: self.config = config else: self.config = '/usr/share/openalpr/config/openalpr.defaults.conf' if self.operating == 'windows': self.config = 'C:/OpenALPR/Agent' + self.config self.message('\tRuntime data: {}'.format(self.runtime)) self.message('\tOpenALPR configuration: {}'.format(self.config)) # Enable GPU acceleration if self.gpu: with open(self.config, 'r') as f: lines = [l.strip() for l in f.read().split('\n') if l != ''] lines.append('hardware_acceleration = 1') self.config = os.path.join(self.downloads, 'openalpr.conf') with open(self.config, 'w') as f: for l in lines: f.write('{}\n'.format(l))
def main(): lastSaveTime = datetime.now( ) # initialize last-image-save-time to prog. start time alpr = Alpr("us", CFILE, "/usr/share/openalpr/runtime_data/") if not alpr.is_loaded(): print('Error loading OpenALPR') sys.exit(1) alpr.set_top_n(1) cv2.namedWindow(WINDOW_NAME, cv2.WINDOW_AUTOSIZE) cv2.setWindowTitle(WINDOW_NAME, 'OpenALPR video test') # =========== now have a loaded instance of alpr; do stuff here cam = cv2.VideoCapture(vidname) # open a video file or stream img_w = int(cam.get(3)) # input image width img_h = int(cam.get(4)) # input image height print("Image w,h = %d %d" % (img_w, img_h)) prlist = re.compile(r"\L<plates>", plates=[ '7WXY20Z', '7WXYZ02', 'WXY202', '7WXY202', 'WXY20Z', 'WXYZ02', 'WXYZ0Z', '7WXY2Q2' ]) save = True # always save the first image, for reference lastPstring = "" # haven't seen any plates yet lastGarageDoor = True # assume we're starting with door closed lastBright = 0.0 # average brightness of previous frame lastXcent = 0 lastYcent = 0 mvec = 0 # ================== MAIN LOOP ===================================== while (True): ret, img = cam.read() if not ret: print('VidepCapture.read() failed. Exiting...') sys.exit(1) ttnow = datetime.now() # local real time when this frame was received avgbright = img.mean() # average of all pixels (float) # print(avgbright) cv2.imshow(WINDOW_NAME, img) # show camera image results = alpr.recognize_ndarray(img) # print(".",end='') # print(results) jsonRes = (json.dumps(results, indent=2)) jsonS = json.loads(jsonRes) rlist = results['results'] pcount = len(rlist) # how many plates we have found # print("Length = %d" % len(rlist) ) if (pcount < 1): # print("No plates found, bright: %5.2f" % avgbright ) pstring = "" # null plate (nothing found) else: for i, plate in enumerate(rlist): cor1x = int(jsonS["results"][0]["coordinates"][0]["x"]) cor1y = int(jsonS["results"][0]["coordinates"][0]["y"]) cor2x = int(jsonS["results"][0]["coordinates"][2]["x"]) cor2y = int(jsonS["results"][0]["coordinates"][2]["y"]) xcent = (cor1x + cor2x) / 2 ycent = (cor1y + cor2y) / 2 dx = xcent - lastXcent dy = ycent - lastYcent mvec = math.sqrt(dx * dx + dy * dy) # motion vector in pixels pcrop = img[cor1y:cor2y, cor1x:cor2x] # crop of image containing plate cv2.imshow("plate", pcrop) # show just the plate p = plate['candidates'][0] pstring = p['plate'].upper() # characters on license plate # if (pstring != "7WXY202") and (pstring != "WXY202"): if prlist.search(pstring): # is this the usual garage-door view? garageDoor = True else: garageDoor = False # here: pstring holds the LP characters, or "" bRatio = (avgbright + 0.01) / (lastBright + 0.01) if (bRatio < 1.0): bRatio = 1 / bRatio if (bRatio > bRatioThresh): bChange = True else: bChange = False if (mvec > mThresh): motion = True else: motion = False tnows = ttnow.strftime("%Y-%m-%d %H:%M:%S.%f")[:-3] # time to msec if bChange: print("Brightness change: %5.3f , %s" % (avgbright, tnows)) # save = not garageDoor # save image if normal garage-door view not seen save = motion # save image if motion of plate detected if (pstring == ""): save = False # but don't save image if no plate if (pstring != lastPstring): print("# Nothing: brightness %5.3f , %s" % (avgbright, tnows)) if save: print("%d,%d , %d,%d , " % (cor1x, img_h - cor1y, cor2x, img_h - cor2y), end='') print('%s , %5.2f , %5.2f , %5.2f , %s' % (pstring, p['confidence'], avgbright, mvec, tnows)) tnowf = ttnow.strftime( "%Y-%m-%d_%H%M%S_%f")[:-3] # filename time to msec fname3 = fPrefix + tnowf + "_" + str(i) + ".jpg" # full-size image # cv.imwrite(fname3, img) # save current image cv2.imwrite(fname3, pcrop) # save current image # print("saved: " + fname3) tSince = (ttnow - lastSaveTime).total_seconds() # print("seconds since last save = %5.3f" % tSince) if (tSince > fullInterval): fname4 = fPrefix2 + tnowf + "_" + str( i) + ".jpg" # full-size image cv2.imwrite(fname4, img) # save full image lastSaveTime = ttnow save = False lastXcent = xcent lastYcent = ycent lastPstring = pstring # remember what we saw before lastGarageDoor = garageDoor lastBright = avgbright # remember last avg brightness c = cv2.waitKey(1) & 0xFF # get input char if any if c == ord('q'): sys.exit(1) # close up and quit 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") #alpr = Alpr("us","/home/blake/workspace/openalpr/src/build/config/openalpr.conf","/home/blake/workspace/openalpr/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', format='jpeg', quality=100) results = alpr.recognize_file("/home/zib/plates/image.jpg") #results = alpr.recognize_file("ETALLIC.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: #XXX: Plausible spot to implement logging lastseenlock.acquire() if (foundplate[0] == 'None'): foundplate[0] = time.strftime( "%X", time.localtime(time.time()) ) + ' Plate: ' + candidate['plate'] lastseenlock.release() # 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 foundconfidence[0] = candidate['confidence'] 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 process_video(video, license_plate, _id): alpr = Alpr('us', ALPR_CONFIG, RUNTIME_DATA) if not alpr.is_loaded(): print("Error loading OpenALPR") sys.exit(1) alpr.set_top_n(5) alpr.set_default_region("md") def get_output_layers(net): layer_names = net.getLayerNames() output_layers = [ layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers() ] return output_layers def get_info(frame, file_type): if file_type == 'array': results = alpr.recognize_ndarray(frame) else: results = alpr.recognize_file(frame) if results['results']: top_plate = results['results'][0]['candidates'][0]['plate'] confidence = results['results'][0]['candidates'][0]['confidence'] x1 = results["results"][0]["coordinates"][0]["x"] y1 = results["results"][0]["coordinates"][0]["y"] x2 = results["results"][0]["coordinates"][2]["x"] y2 = results["results"][0]["coordinates"][2]["y"] return [x1, y1, x2, y2], top_plate, confidence else: return False def draw_boxes(regions_of_interest, plate_number, confidence, img): x, y, x1, y1 = regions_of_interest[0], regions_of_interest[ 1], regions_of_interest[2], regions_of_interest[3] cv2.rectangle(img, (x, y), (x1, y1), (0, 255, 0), 2) text = "{} {:.1f}%".format(plate_number, confidence) cv2.putText(img, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2) video = cv2.VideoCapture(video) w, h = None, None while True: grabbed, frame = video.read() if not grabbed: break start = time.time() try: regions_of_interest, top_plate, confidence = get_info( frame, 'array') print(regions_of_interest, top_plate, confidence) #confirming license plate if str(top_plate) == license_plate: draw_boxes(regions_of_interest, top_plate, confidence, frame) cv2.imwrite(f'{IMAGE_FOLDER}/confirmation{_id}.png', frame) return f'{IMAGE_FOLDER}/confirmation{_id}.png' except: print('License Plate not Detected') end = time.time() print(f"[INFO] Processing Time - {end-start}") video.release() alpr.unload()
def main(): writer = None VIDEO_SOURCE = '/home/ankita/Downloads/video1.mp4' WINDOW_NAME = 'openalpr' FRAME_SKIP = 15 alpr = Alpr('us', 'us.conf', '/usr/local/share/openalpr/runtime_data') if not alpr.is_loaded(): print('Error loading OpenALPR') # sys.exit(1) alpr.set_top_n(3) # alpr.set_default_region('new') cap = cv2.VideoCapture(VIDEO_SOURCE) if not cap.isOpened(): alpr.unload() print('Failed to load video file') #sys.exit('Failed to open video file!') cv2.namedWindow(WINDOW_NAME, cv2.WINDOW_AUTOSIZE) cv2.setWindowTitle(WINDOW_NAME, 'OpenALPR video test') _frame_number = 0 currentFrame = 0 # Get current width of frame width = cap.get(cv2.CAP_PROP_FRAME_WIDTH) # float # Get current height of frame height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT) # float # Define the codec and create VideoWriter object fourcc = cv2.VideoWriter_fourcc(*"XVID") out = cv2.VideoWriter('color_output.avi', fourcc, 2.0, (int(width), int(height))) while True: ret_val, frame = cap.read() if not ret_val: print('VidepCapture.read() failed. Exiting...') break _frame_number += 1 if _frame_number % FRAME_SKIP != 0: continue results = alpr.recognize_ndarray(frame) for i, plate in enumerate(results['results']): list1 = [] best_candidate = plate['candidates'][0] min_coord = plate['coordinates'][0] max_coord = plate['coordinates'][2] x_min = int(min_coord['x']) y_min = int(min_coord['y']) x_max = int(max_coord['x']) y_max = int(max_coord['y']) cv2.resize(frame, (500, 500), fx=0, fy=0, interpolation=cv2.INTER_CUBIC) cv2.rectangle(frame, (x_min, y_min), (x_max, y_max), (255, 255, 0), 5) #cropimg = cv2.getRectSubPix( # frame, (x_min-10, y_min), (x_min, y_min)) #type(cropimg[0:]) #x = cropimg[0:][0][0] #list1 = x.tolist() #list1 = list(map(int,list1)) #print(list1) #print(type(list1)) #act,pred = get_colour_name(tuple(list1)) #print(pred) cv2.putText(frame, 'NP: '+str(best_candidate['plate']).upper(), (x_min, y_min), cv2.FONT_HERSHEY_SIMPLEX, 0.85, [255, 255, 0], 2) if(best_candidate['confidence'] > 50): print('Plate #{}: {:7s} ({:.2f}%)'.format(i, best_candidate['plate'].upper(), best_candidate['confidence'])) list1 = [] cv2.imshow(WINDOW_NAME, frame) out.write(frame) if cv2.waitKey(1) == 27: break cv2.destroyAllWindows() out.release() cap.release() alpr.unload()