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'])
Esempio n. 2
0
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"
Esempio n. 3
0
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()
Esempio n. 4
0
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()
Esempio n. 5
0
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']
Esempio n. 6
0
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()
Esempio n. 7
0
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
Esempio n. 8
0
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
Esempio n. 9
0
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']
Esempio n. 10
0
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
Esempio n. 11
0
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()
Esempio n. 12
0
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()
Esempio n. 13
0
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 get_license(file_name):
    l = []
    alpr = Alpr('us', '/etc/openalpr/openalpr.conf', '/usr/share/openalpr/runtime_data')
    results = alpr.recognize_file(file_name)
    if len(results['results']) == 0:
        print("Can't find a plate in image:", file_name)
    else:
        for i in range(len(results['results'][0]['candidates'])):
            l.append([results['results'][0]['candidates'][i]['plate'],results['results'][0]['candidates'][i]['confidence']])
    return l
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
Esempio n. 16
0
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
Esempio n. 17
0
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')
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()
Esempio n. 19
0
    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
Esempio n. 20
0
class PlateProcessorThread(threading.Thread):
    def __init__(self, metadata, thread_number=0, total_threads=1):
        global processing_threads
        threading.Thread.__init__(self)
        self.metadata = metadata
        self.thread_number = thread_number
        self.total_threads = total_threads
        self.complete = False

    def run(self):
        global processing_threads

        bench_config = os.path.join(SCRIPT_DIR, "config/bench.conf")
        self.alpr = Alpr(options.country, bench_config,
                         "/usr/share/openalpr/runtime_data/")

        print("Initiating thread #%d" % (self.thread_number))

        counter = 0
        for plate in self.metadata:
            image_path = os.path.join(options.folder, plate['image_file'])

            if counter % self.total_threads != self.thread_number:
                # Skip this because another thread is processing it
                counter += 1
                continue

            counter += 1
            if self.thread_number == 0:
                print "Processing %d / %d" % (counter, len(self.metadata))

            if not os.path.isfile(image_path):
                print "Could not find: %s" % (image_path)
                sys.exit(1)

            results = self.alpr.recognize_file(image_path)

            # print json.dumps(results, indent=2)

            threadLock.acquire()
            for result in results['results']:
                benchstats.add_result(plate['image_file'], result)
            threadLock.release()

        threadLock.acquire()
        processing_thread_status[self.thread_number] = 0
        threadLock.release()
        self.complete = True

        print "Thread %d complete" % (self.thread_number)
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
Esempio n. 22
0
def callback(ch, method, properties, body):
    obj1, obj2, obj3 = pickle.loads(body)
    f = open(obj1, "wb")
    f.write(obj3)
    f.close()
    image = Image.open(obj1)
    exif_data = GetLatLon.get_exif_data(image)
    print(GetLatLon.get_lat_lon(exif_data))
    latlon = GetLatLon.get_lat_lon(exif_data)
    list1.append(latlon)
    alpr = Alpr('us', '/etc/openalpr/openalpr.conf',
                '/usr/share/openalpr/runtime_data')
    results = alpr.recognize_file(obj1)

    if len(results['results']) == 0:
        print("Can't find a plate")
    else:
        count = 0
        #        print(results['results'][0]['candidates'][0])
        licensename = results['results'][0]['candidates'][0]['plate']
        for key in results['results'][0]['candidates']:
            if (count <= 3):
                list1.append((key['plate'], key['confidence']))
                print("Most likely plate is", key['confidence'])
                print("Most likely confidence is", key['plate'])
                count = count + 1

    redisHash = redis.Redis(host="redis", db=1)
    redisHash.set(obj2, pickle.dumps(list1))
    list1.clear()
    print("Redis get by Hash Value")
    print(obj2)
    val1 = pickle.loads(redisHash.get(obj2))
    print(val1)

    redisName = redis.Redis(host="redis", db=2)
    redisName.set(obj1, obj2)
    print("Redis get by Name")
    print(obj1)
    val2 = redisName.get(obj1)
    print(val2)

    if (len(results['results']) != 0):
        redisLicense = redis.Redis(host="redis", db=3)
        redisLicense.set(licensename, obj2)
        print("Redis get by License")
        print(licensename)
        val3 = redisLicense.get(licensename)
        print(val3)
Esempio n. 23
0
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()
Esempio n. 24
0
def get_regions_occupied_by_license_plates(image_path: str, model_region: str="eu") -> List[Polygon]:
    openalpr_recognizer = Alpr(model_region, "/usr/local/etc/openalpr/openalpr.conf",
                               "/usr/local/Cellar/openalpr/HEAD-de93f21_1/share/openalpr/runtime_data/")

    if not openalpr_recognizer.is_loaded():
        print("Error loading OpenALPR")
        sys.exit(1)

    results = openalpr_recognizer.recognize_file(image_path)

    license_plate_regions = [result['coordinates'] for result in results['results']]
    license_plate_regions_as_tuples = [[(point['x'], point['y']) for point in region] for region in
                                       license_plate_regions]

    openalpr_recognizer.unload()  # release memory

    return license_plate_regions_as_tuples
Esempio n. 25
0
def detectPlate():
    alpr = Alpr("eu", "/path/to/openalpr.conf",
                "/home/pi/openalpr/runtime_data")
    if not alpr.is_loaded():
        print "Erro! Verifique se a lib Openalpr foi instalada corretamente."
        sys.exit(1)
    alpr.set_top_n(20)
    alpr.set_default_region("md")
    results = alpr.recognize_file("cart.jpg")
    plate = ""
    acuraccy = ""
    for plate in results['results']:
        for candidate in plate['candidates']:
            plate = candidate['plate']
            acuraccy = candidate['confidence']
            break
    alpr.unload()
    return plate
Esempio n. 26
0
def neiron(img_path):
    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(img_file)
        answer = results['results'][0]['plate']
        alpr.unload()
    except Exception as e:
        print('Couldn\'t load ALPR')
        answer = 'Unsolved'
        return answer
Esempio n. 27
0
def scanImage(imageFilePath):
    alpr = Alpr("gb", "/etc/openalpr/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(imageFilePath)

    alpr.unload()

    if results and results['results'] and results['results'][0] and results['results'][0]['plate']:
        plate = results['results'][0]['plate']
        confidence = results['results'][0]['confidence']
        print("Suspected number plate: " + plate + " - " + str(confidence) + "%")

        return {"plate": plate, "confidence": confidence}
    
    return False
Esempio n. 28
0
def generate_DB_files():	#TODO checking
	start_recognition = time.time()
	ec_elgamal.prepare(pub_key_file, priv_key_file)
	plates = []
	if (args.cars_folder != ""):
		alpr = Alpr("us", "/etc/openalpr/openalpr.conf", "/usr/share/openalpr/runtime_data")
		start_recognition = time.time()	# do not include initialization time
		for root, dirs, files in os.walk(args.cars_folder):
			for img in files:
				results = alpr.recognize_file(os.path.join(root, img))
				if results.values()[5] != []:
					plates.append(results.values()[5][0].values()[0]) # get the result with the best confidence
	elif (args.cars_file != "") :
		if not os.path.isfile(args.cars_file):
			print("generate_DB_files: ERROR! File {} does not exist!".format(args.cars_file))
		with open(args.cars_file) as fp:
			for line in fp:
				plates.append(line)
	else :
		print("generate_DB_files: ERROR! No source file/directory specified")
		exit(0)
	if plates == []:
		print("generate_DB_files: No plates have been detected. Exiting...")
		exit(0)
	encoded_plates = [encode_plate_number(plate) for plate in plates]
	end_recognition = time.time()
	if args.verbose:	print("generate_DB_files: Plates generated in {} ms".format((end_recognition-start_recognition)*1000))
	start_enc = time.time()
	if args.verbose:	print("generate_DB_files: Generating encrypted DB...")
	pool = Pool(processes=args.cpus)
	DB = pool.map(encrypt_for_DB, (encoded_plates[int(i*len(encoded_plates)/args.cpus):int((i+1)*len(encoded_plates)/args.cpus)] for i in range(args.cpus)))
	DB = [ent for sublist in DB for ent in sublist]
	end_enc = time.time()
	if args.verbose:	print("generate_DB_files: Encrypted DB generated in: {} ms, nbr of plates: {}".format((end_enc-start_enc)*1000, len(DB)))
	np.save(DB_file, DB)
	del DB
	results_file = open("server_results.txt", "a+")
	results_file.write("Offline:M= {} CPUs_srvr= {} recog= {} DB_gen= {} storage/off_comm= {}\n"\
		.format(len(encoded_plates), args.cpus, (end_recognition-start_recognition)*1000, (end_enc-start_enc)*1000, plate_size*len(encoded_plates)*128*1.00/1024))
	results_file.close()
Esempio n. 29
0
def main():
    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

    fileName = "snapshot.jpg"

    results = alpr.recognize_file(fileName)
    #file = cv2.imread(fileName)
    #cv2.imshow("test", file)
    i = 0
    print(len(results['results']))
    for plate in results['results']:
        i += 1
        coords = plate['coordinates']
        topLeft = coords[0]
        bottomRight = coords[2]

        w = bottomRight['x'] - topLeft['x']
        h = bottomRight['y'] - topLeft['y']

        print("Plate #%d" % i)
        print("Width: %d" % w)
        print("Height: %d" % h)
        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()
Esempio n. 30
0
class PlateID():

    def __init__(self):
        self.alpr = Alpr("br", "/usr/share/openalpr/config/openalpr.defaults.conf", "/usr/share/openalpr/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("br")

    def getPlate(self, arq='/home/pi/imgteste.jpg'):
        results = self.alpr.recognize_file(arq) 
        plate = None
        pat = re.compile('[A-Z][A-Z][A-Z][0-9][0-9][0-9][0-9]') 
        for plates in results['results']:
            for candidate in plates['candidates']:
                if pat.match(candidate['plate']):
                    plate = candidate['plate']
                    break;
        return plate
Esempio n. 31
0
def find_images(Filename) :

    while(True):
        alpr = Alpr("kr", "/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(Filename)

        i = 0

        for plate in results['results']:
            i += 1
            print("Plate #%d" % i)
            print("   %12s %12s" % ("Plate", "Confidence"))
            for candidate , a in plate['candidates']:
                prefix = "-"
                if candidate['matches_template']:
                    prefix = "*"

                print("  %s %12s%12f" % (prefix, candidate['plate'], candidate['confidence']))

                    car_full_info[a] = candidate['plate'].encode('UTF-8')


            car_String = car_full_info[:5]
            print(type(car_String))
            car_number = car_full_info[5:]
            print (car_String,car_number)
            #send_data.send_data(filename,car_full_info,car_String,car_number)

        # Call when completely done to release me   mory
        alpr.unload()
        sec =10
        time.sleep(sec)
Esempio n. 32
0
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"
Esempio n. 33
0
            with open(log_file,'a+') as sl:
                sl.write('%f        ' % S )
            ci += 1

        # Go to next line in log
        with open(log_file,'a+') as sl:
            sl.write('\n')
        

        # If spot occupation has changed and someone's there...
        if occupied is not now_occupied and np.any(now_occupied):
            # Write image with all biggest contours
            sfname = 'occupied.jpg'
            cv2.imwrite(sfname,ims)
            
            res = alpr.recognize_file(fname)
            lpn = ''
            try:
                lpn = str( res['results'][0]['plate'] )
                print "LPN = %s" % lpn
            except:
                print "no dice with lpr..."
            
            sub = 'Occupation has changed'
            msg = 'Spot Status = %s' % str(now_occupied)
            print '%s\n%s' % (sub,msg)
            msg += '\nLPN = %s' % lpn
            #notify.send_msg_with_jpg( sub, msg, sfname, team )
        
        # Set occupation to current status
        occupied = now_occupied
Esempio n. 34
0
from openalpr import Alpr

alpr = Alpr("us", "/path/to/openalpr.conf", "/path/to/runtime_data")
if not alpr.is_loaded():
    print("Error loading OpenALPR")
    sys.exit(1)

alpr.set_top_n(20)
alpr.set_default_region("md")

results = alpr.recognize_file("./image/DSCN0416.jpg")

i = 0
for plate in results['results']:
    i += 1
    print("Plate #%d" % i)
    print("   %12s %12s" % ("Plate", "Confidence"))
    for candidate in plate['candidates']:
        prefix = "-"
        if candidate['matches_template']:
            prefix = "*"

        print("  %s %12s%12f" % (prefix, candidate['plate'], candidate['confidence']))

# Call when completely done to release memory
alpr.unload()
Esempio n. 35
0
File: test.py Progetto: riaz/Recee
from openalpr import Alpr
import sys

alpr = Alpr("eu", "nplate_train/openalpr.conf.in", "nplate_train/runtime_data")
if not alpr.is_loaded():
    print("Error loading OpenALPR")
    sys.exit(1)

#alpr.set_top_n(20)
alpr.set_default_region("eu")

results = alpr.recognize_file("/home/riaz/Desktop/hack/2009_09_08_drive_0010/I1_000388.png")

for plate in results['results']:

    if len(plate['candidates']) > 0:
        print "Found: %12s %12f" % ( plate['candidates'][0]['plate'],plate['candidates'][0]['confidence']) 
        
# Call when completely done to release memory
alpr.unload()
from 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")
# 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)
    temp = "frame%d.jpg" % ret
    cv2.imwrite(temp, frame)

    results = alpr.recognize_file(temp)

    if not wasPlate:
        count = 0

    if count == numEx:
        items = probablePlates.items()
        mostProbable = items[0]
        for plate in items:
            if plate[1] > mostProbable[1]:
                mostProbable = plate[0]
                data = {"plate": mostProbable}
                data = json.dumps(data)

                r = requests.post(url, params=data, headers=headers)
                # mqttc.publish("plates", payload=data, qos=0, retain=True)