From cbe965d781cd6eef4599bb7655be15b2f9490835 Mon Sep 17 00:00:00 2001 From: itsFDavid Date: Wed, 2 Oct 2024 19:02:31 -0600 Subject: [PATCH 01/13] add program to compare template with fingerprint folfer --- ...nt_template_folder_compare_with_file.py.py | 312 ++++++++++++++++++ 1 file changed, 312 insertions(+) create mode 100644 examples/fingerprint_template_folder_compare_with_file.py.py diff --git a/examples/fingerprint_template_folder_compare_with_file.py.py b/examples/fingerprint_template_folder_compare_with_file.py.py new file mode 100644 index 0000000..31e0ba6 --- /dev/null +++ b/examples/fingerprint_template_folder_compare_with_file.py.py @@ -0,0 +1,312 @@ +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-License-Identifier: MIT +""" +`fingerprint_template_folder_compare_with_file.py` +==================================================== + +This is an example program to demo storing fingerprint templates in a folder. It also allows +comparing a newly obtained print with one stored in the folder in previous step. This is helpful +when fingerprint templates are stored centrally (not on sensor's flash memory) and shared +between multiple sensors. + +* Author(s): itsFDavid + +Implementation Notes +-------------------- +This program was used on others sensor of fingerprint generics and everything turned out to be as expected, +so this program was tested with Raspsberry Pi Zero 2" + +""" +import time +from PIL import Image +import os + +##################### Settings of serial port + +import serial +import adafruit_fingerprint + +#import board +#import busio + +# import board (if you are using a micropython board) +# uart = busio.UART(board.TX, board.RX, baudrate=57600) + +# If using with a computer such as Linux/RaspberryPi, Mac, Windows with USB/serial converter: +# uart = serial.Serial("COM6", baudrate=57600, timeout=1) + +# If using with Linux/Raspberry Pi and hardware UART: +uart = serial.Serial("/dev/ttyUSB0", baudrate=57600, timeout=1) + +# If using with Linux/Raspberry Pi 3 with pi3-disable-bte +# uart = serial.Serial("/dev/ttyAMA0", baudrate=57600, timeout=1) + +finger = adafruit_fingerprint.Adafruit_Fingerprint(uart) + +################################################## + + +# Carpeta donde se almacenan las plantillas de huellas +FINGERPRINT_FOLDER = "fingerprint/" + +################################################## +# Enrrols and verification functions +################################################## + +def get_fingerprint(): + """get image to fingerprint sensor for search, process for a match""" + print("Wait finger..") + while finger.get_image() != adafruit_fingerprint.OK: + pass + print("Process image...") + if finger.image_2_tz(1) != adafruit_fingerprint.OK: + return False + print("Searching coincidences...") + if finger.finger_search() != adafruit_fingerprint.OK: + return False + return True + +def get_fingerprint_detail(): + """Get image to fingerprint for process and return errors.""" + print("Wait finger..", end="") + i = finger.get_image() + if i == adafruit_fingerprint.OK: + print("Image captured") + else: + print("Error capturing image") + return False + + print("Process image...", end="") + i = finger.image_2_tz(1) + if i == adafruit_fingerprint.OK: + print("Image processed") + else: + print("Error processing image") + return False + + print("Searching coincidences...", end="") + i = finger.finger_fast_search() + if i == adafruit_fingerprint.OK: + print("¡Fingerprint found!") + return True + else: + print("Fingerprint not found") + return False + +def enroll_finger(location): + """Enroll a finger with the fingerprint sensor and store it in the given location specific.""" + for fingerimg in range(1, 3): + if fingerimg == 1: + print("Please put your finger on sensor...", end="") + else: + print("Put same finger...", end="") + + while True: + i = finger.get_image() + if i == adafruit_fingerprint.OK: + print("Image captured") + break + if i == adafruit_fingerprint.NOFINGER: + print(".", end="") + else: + print("Error capturing image") + return False + + print("Process image...", end="") + i = finger.image_2_tz(fingerimg) + if i == adafruit_fingerprint.OK: + print("Imagen procesed") + else: + print("Error processing image") + return False + + if fingerimg == 1: + print("Remove finger") + time.sleep(1) + while i != adafruit_fingerprint.NOFINGER: + i = finger.get_image() + + print("Creating model..", end="") + i = finger.create_model() + if i == adafruit_fingerprint.OK: + print("Model created") + else: + print("Error creating model") + return False + + print("Storing in that location #%d..." % location, end="") + i = finger.store_model(location) + if i == adafruit_fingerprint.OK: + print("Model stored") + else: + print("Error storing model") + return False + + return True + +################################################## +# Save and Compare from File Functions +################################################## + +def save_fingerprint_image(filename): + """Scan your fingerprint and save the image to a file.""" + while finger.get_image(): + pass + + img = Image.new("L", (256, 288), "white") + pixeldata = img.load() + mask = 0b00001111 + result = finger.get_fpdata(sensorbuffer="image") + + x, y = 0, 0 + for i in range(len(result)): + pixeldata[x, y] = (int(result[i]) >> 4) * 17 + x += 1 + pixeldata[x, y] = (int(result[i]) & mask) * 17 + if x == 255: + x = 0 + y += 1 + else: + x += 1 + + if not img.save(filename): + return True + return False + +def enroll_save_to_file(): + """Scan your fingerprint and save the image to a file""" + for fingerimg in range(1, 3): + if fingerimg == 1: + print("Please put your finger on sensor...", end="") + else: + print("Put same finger..", end="") + + while True: + i = finger.get_image() + if i == adafruit_fingerprint.OK: + print("Image captured") + break + if i == adafruit_fingerprint.NOFINGER: + print(".", end="") + else: + print("Error capturing image") + return False + + print("Process image...", end="") + i = finger.image_2_tz(fingerimg) + if i == adafruit_fingerprint.OK: + print("Image processed") + else: + print("Error processing image") + return False + + if fingerimg == 1: + print("Remove finger") + while i != adafruit_fingerprint.NOFINGER: + i = finger.get_image() + + print("Creating model...", end="") + i = finger.create_model() + if i == adafruit_fingerprint.OK: + print("Model create") + else: + print("Error creating model") + return False + + print("Storing template...") + data = finger.get_fpdata("char", 1) + # Guardar la plantilla con un nombre único basado en la hora actual + filename = os.path.join(FINGERPRINT_FOLDER, f"template_{int(time.time())}.dat") + with open(filename, "wb") as file: + file.write(bytearray(data)) + print(f"Template saved on {filename}") + + return True + +def fingerprint_check_folder(): + """Compare fingerprint with all files in the fingerprint folder.""" + print("Wait for fingerprint...") + while finger.get_image() != adafruit_fingerprint.OK: + pass + print("Process image...") + if finger.image_2_tz(1) != adafruit_fingerprint.OK: + return False + + print("Searching coincidences on the template's folder...", end="") + found_match = False + matched_filename = None + + for filename in os.listdir(FINGERPRINT_FOLDER): + if filename.endswith(".dat"): + file_path = os.path.join(FINGERPRINT_FOLDER, filename) + with open(file_path, "rb") as file: + data = file.read() + finger.send_fpdata(list(data), "char", 2) + i = finger.compare_templates() + if i == adafruit_fingerprint.OK: + matched_filename = filename + found_match = True + break # Detener la búsqueda después de encontrar una coincidencia + + if found_match: + print(f"¡Fingerprint match the template in the file {matched_filename}!") + else: + print("Not match found") + + return found_match + +################################################## +# Main cycle of the program +################################################## + +while True: + print("----------------") + if finger.read_templates() != adafruit_fingerprint.OK: + raise RuntimeError("Could not be read the templates") + print("Templates of fingerprints: ", finger.templates) + if finger.count_templates() != adafruit_fingerprint.OK: + raise RuntimeError("Could not be counted the templates") + print("Number of templates found: ", finger.template_count) + if finger.read_sysparam() != adafruit_fingerprint.OK: + raise RuntimeError("Could not be obtained params of system.") + print("Size of template library ", finger.library_size) + print("e) Enrrol fingerprint") + print("f) Search fingerprint") + print("d) Delete fingerprint") + print("s) Store image of fingerprint") + print("cf) Compare template with file") + print("esf) Enrrol and save in file") + print("r) Reset library") + print("q) Exit") + print("----------------") + c = input("> ") + + if c == "e": + enroll_finger(get_num(finger.library_size)) + if c == "f": + if get_fingerprint(): + print("Fingerprint detected with ID #", finger.finger_id, "and confidence", finger.confidence) + else: + print("Fingerprint not found") + if c == "d": + if finger.delete_model(get_num(finger.library_size)) == adafruit_fingerprint.OK: + print("¡Deleted!") + else: + print("Error deleting") + if c == "s": + if save_fingerprint_image("fingerprint.png"): + print("Image of fingerpriint") + else: + print("Error storing an image") + if c == "cf": + fingerprint_check_folder() + if c == "esf": + enroll_save_to_file() + if c == "r": + if finger.empty_library() == adafruit_fingerprint.OK: + print("¡Empty Library!") + else: + print("Error emptying library") + if c == "q": + print("Leavinf of fingerprint program") + raise SystemExit \ No newline at end of file From 19438ee586d4783e2a7812772c31ec6026dcdb8b Mon Sep 17 00:00:00 2001 From: itsFDavid Date: Wed, 2 Oct 2024 19:14:49 -0600 Subject: [PATCH 02/13] update this program for to pass tests --- ...ingerprint_template_folder_compare_with_file.py.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/examples/fingerprint_template_folder_compare_with_file.py.py b/examples/fingerprint_template_folder_compare_with_file.py.py index 31e0ba6..4c535cd 100644 --- a/examples/fingerprint_template_folder_compare_with_file.py.py +++ b/examples/fingerprint_template_folder_compare_with_file.py.py @@ -13,13 +13,15 @@ Implementation Notes -------------------- -This program was used on others sensor of fingerprint generics and everything turned out to be as expected, +This program was used on others sensor of fingerprint, +generics and everything turned out to be as expected, so this program was tested with Raspsberry Pi Zero 2" """ +import os import time from PIL import Image -import os + ##################### Settings of serial port @@ -89,9 +91,7 @@ def get_fingerprint_detail(): if i == adafruit_fingerprint.OK: print("¡Fingerprint found!") return True - else: - print("Fingerprint not found") - return False + return False def enroll_finger(location): """Enroll a finger with the fingerprint sensor and store it in the given location specific.""" @@ -289,6 +289,7 @@ def fingerprint_check_folder(): else: print("Fingerprint not found") if c == "d": + """"get_num is a function that returns a number from 0 to 127""" if finger.delete_model(get_num(finger.library_size)) == adafruit_fingerprint.OK: print("¡Deleted!") else: From 00ac1b99a096f90e0705f9ee75b6d788c5b9c9e0 Mon Sep 17 00:00:00 2001 From: itsFDavid Date: Fri, 4 Oct 2024 22:25:34 -0600 Subject: [PATCH 03/13] Refactor code for improved performance --- ...nt_template_folder_compare_with_file.py.py | 151 +++++++++--------- 1 file changed, 77 insertions(+), 74 deletions(-) diff --git a/examples/fingerprint_template_folder_compare_with_file.py.py b/examples/fingerprint_template_folder_compare_with_file.py.py index 4c535cd..9d33f15 100644 --- a/examples/fingerprint_template_folder_compare_with_file.py.py +++ b/examples/fingerprint_template_folder_compare_with_file.py.py @@ -5,7 +5,7 @@ ==================================================== This is an example program to demo storing fingerprint templates in a folder. It also allows -comparing a newly obtained print with one stored in the folder in previous step. This is helpful +comparing a newly obtained print with one stored in the folder in the previous step. This is helpful when fingerprint templates are stored centrally (not on sensor's flash memory) and shared between multiple sensors. @@ -13,64 +13,68 @@ Implementation Notes -------------------- -This program was used on others sensor of fingerprint, -generics and everything turned out to be as expected, -so this program was tested with Raspsberry Pi Zero 2" - +This program was used on other fingerprint sensors, +and everything worked as expected, including testing with Raspberry Pi Zero 2. """ + import os import time from PIL import Image - -##################### Settings of serial port +##################### Settings for the serial port import serial import adafruit_fingerprint -#import board -#import busio - -# import board (if you are using a micropython board) -# uart = busio.UART(board.TX, board.RX, baudrate=57600) - # If using with a computer such as Linux/RaspberryPi, Mac, Windows with USB/serial converter: # uart = serial.Serial("COM6", baudrate=57600, timeout=1) # If using with Linux/Raspberry Pi and hardware UART: uart = serial.Serial("/dev/ttyUSB0", baudrate=57600, timeout=1) -# If using with Linux/Raspberry Pi 3 with pi3-disable-bte -# uart = serial.Serial("/dev/ttyAMA0", baudrate=57600, timeout=1) - finger = adafruit_fingerprint.Adafruit_Fingerprint(uart) ################################################## - -# Carpeta donde se almacenan las plantillas de huellas +# Folder where fingerprint templates are stored FINGERPRINT_FOLDER = "fingerprint/" ################################################## -# Enrrols and verification functions +# Enroll and verification functions ################################################## +def get_num(max_num): + """ + Prompts the user to enter a valid template number. + Ensures that the number is within the available template range. + """ + while True: + try: + num = int(input(f"Enter a template number (0-{max_num}): ")) + if 0 <= num <= max_num: + return num + else: + print(f"Please enter a number between 0 and {max_num}.") + except ValueError: + print("Invalid input. Please enter a valid number.") + + def get_fingerprint(): - """get image to fingerprint sensor for search, process for a match""" - print("Wait finger..") + """Get an image from the fingerprint sensor for search, process for a match.""" + print("Waiting for finger...") while finger.get_image() != adafruit_fingerprint.OK: pass - print("Process image...") + print("Processing image...") if finger.image_2_tz(1) != adafruit_fingerprint.OK: return False - print("Searching coincidences...") + print("Searching for matches...") if finger.finger_search() != adafruit_fingerprint.OK: return False return True def get_fingerprint_detail(): - """Get image to fingerprint for process and return errors.""" - print("Wait finger..", end="") + """Get an image from the fingerprint sensor and return details/errors.""" + print("Waiting for finger...", end="") i = finger.get_image() if i == adafruit_fingerprint.OK: print("Image captured") @@ -78,7 +82,7 @@ def get_fingerprint_detail(): print("Error capturing image") return False - print("Process image...", end="") + print("Processing image...", end="") i = finger.image_2_tz(1) if i == adafruit_fingerprint.OK: print("Image processed") @@ -86,20 +90,20 @@ def get_fingerprint_detail(): print("Error processing image") return False - print("Searching coincidences...", end="") + print("Searching for matches...", end="") i = finger.finger_fast_search() if i == adafruit_fingerprint.OK: - print("¡Fingerprint found!") + print("Fingerprint found!") return True return False def enroll_finger(location): - """Enroll a finger with the fingerprint sensor and store it in the given location specific.""" + """Enroll a fingerprint and store it in the specified location.""" for fingerimg in range(1, 3): if fingerimg == 1: - print("Please put your finger on sensor...", end="") + print("Please place your finger on the sensor...", end="") else: - print("Put same finger...", end="") + print("Place the same finger again...", end="") while True: i = finger.get_image() @@ -112,10 +116,10 @@ def enroll_finger(location): print("Error capturing image") return False - print("Process image...", end="") + print("Processing image...", end="") i = finger.image_2_tz(fingerimg) if i == adafruit_fingerprint.OK: - print("Imagen procesed") + print("Image processed") else: print("Error processing image") return False @@ -126,7 +130,7 @@ def enroll_finger(location): while i != adafruit_fingerprint.NOFINGER: i = finger.get_image() - print("Creating model..", end="") + print("Creating model...", end="") i = finger.create_model() if i == adafruit_fingerprint.OK: print("Model created") @@ -134,7 +138,7 @@ def enroll_finger(location): print("Error creating model") return False - print("Storing in that location #%d..." % location, end="") + print(f"Storing model in location #{location}...", end="") i = finger.store_model(location) if i == adafruit_fingerprint.OK: print("Model stored") @@ -149,7 +153,7 @@ def enroll_finger(location): ################################################## def save_fingerprint_image(filename): - """Scan your fingerprint and save the image to a file.""" + """Capture a fingerprint and save the image to a file.""" while finger.get_image(): pass @@ -159,27 +163,27 @@ def save_fingerprint_image(filename): result = finger.get_fpdata(sensorbuffer="image") x, y = 0, 0 - for i in range(len(result)): - pixeldata[x, y] = (int(result[i]) >> 4) * 17 + for i, value in enumerate(result): + pixeldata[x, y] = (int(value) >> 4) * 17 x += 1 - pixeldata[x, y] = (int(result[i]) & mask) * 17 + pixeldata[x, y] = (int(value) & mask) * 17 if x == 255: x = 0 y += 1 else: x += 1 - if not img.save(filename): - return True - return False + img.save(filename) + return True + def enroll_save_to_file(): - """Scan your fingerprint and save the image to a file""" + """Capture a fingerprint, create a model, and save it to a file.""" for fingerimg in range(1, 3): if fingerimg == 1: - print("Please put your finger on sensor...", end="") + print("Please place your finger on the sensor...", end="") else: - print("Put same finger..", end="") + print("Place the same finger again...", end="") while True: i = finger.get_image() @@ -192,7 +196,7 @@ def enroll_save_to_file(): print("Error capturing image") return False - print("Process image...", end="") + print("Processing image...", end="") i = finger.image_2_tz(fingerimg) if i == adafruit_fingerprint.OK: print("Image processed") @@ -208,31 +212,31 @@ def enroll_save_to_file(): print("Creating model...", end="") i = finger.create_model() if i == adafruit_fingerprint.OK: - print("Model create") + print("Model created") else: print("Error creating model") return False print("Storing template...") data = finger.get_fpdata("char", 1) - # Guardar la plantilla con un nombre único basado en la hora actual + # Save the template with a unique filename based on the current time filename = os.path.join(FINGERPRINT_FOLDER, f"template_{int(time.time())}.dat") with open(filename, "wb") as file: file.write(bytearray(data)) - print(f"Template saved on {filename}") + print(f"Template saved to {filename}") return True def fingerprint_check_folder(): - """Compare fingerprint with all files in the fingerprint folder.""" - print("Wait for fingerprint...") + """Compare a fingerprint with all files in the fingerprint folder.""" + print("Waiting for fingerprint...") while finger.get_image() != adafruit_fingerprint.OK: pass - print("Process image...") + print("Processing image...") if finger.image_2_tz(1) != adafruit_fingerprint.OK: return False - print("Searching coincidences on the template's folder...", end="") + print("Searching for matches in the template folder...", end="") found_match = False matched_filename = None @@ -246,36 +250,36 @@ def fingerprint_check_folder(): if i == adafruit_fingerprint.OK: matched_filename = filename found_match = True - break # Detener la búsqueda después de encontrar una coincidencia + break # Stop searching after finding a match if found_match: - print(f"¡Fingerprint match the template in the file {matched_filename}!") + print(f"Fingerprint matches the template in the file {matched_filename}!") else: - print("Not match found") + print("No match found") return found_match ################################################## -# Main cycle of the program +# Main program loop ################################################## while True: print("----------------") if finger.read_templates() != adafruit_fingerprint.OK: - raise RuntimeError("Could not be read the templates") - print("Templates of fingerprints: ", finger.templates) + raise RuntimeError("Could not read templates") + print("Stored fingerprint templates: ", finger.templates) if finger.count_templates() != adafruit_fingerprint.OK: - raise RuntimeError("Could not be counted the templates") + raise RuntimeError("Could not count templates") print("Number of templates found: ", finger.template_count) if finger.read_sysparam() != adafruit_fingerprint.OK: - raise RuntimeError("Could not be obtained params of system.") - print("Size of template library ", finger.library_size) - print("e) Enrrol fingerprint") + raise RuntimeError("Could not retrieve system parameters.") + print("Template library size: ", finger.library_size) + print("e) Enroll fingerprint") print("f) Search fingerprint") print("d) Delete fingerprint") - print("s) Store image of fingerprint") + print("s) Save fingerprint image") print("cf) Compare template with file") - print("esf) Enrrol and save in file") + print("esf) Enroll and save to file") print("r) Reset library") print("q) Exit") print("----------------") @@ -285,29 +289,28 @@ def fingerprint_check_folder(): enroll_finger(get_num(finger.library_size)) if c == "f": if get_fingerprint(): - print("Fingerprint detected with ID #", finger.finger_id, "and confidence", finger.confidence) + print("Fingerprint detected with ID#",finger.finger_id,"& confidence",finger.confidence) else: print("Fingerprint not found") if c == "d": - """"get_num is a function that returns a number from 0 to 127""" if finger.delete_model(get_num(finger.library_size)) == adafruit_fingerprint.OK: - print("¡Deleted!") + print("Deleted successfully!") else: print("Error deleting") if c == "s": if save_fingerprint_image("fingerprint.png"): - print("Image of fingerpriint") + print("Fingerprint image saved") else: - print("Error storing an image") + print("Error saving image") if c == "cf": fingerprint_check_folder() if c == "esf": enroll_save_to_file() if c == "r": if finger.empty_library() == adafruit_fingerprint.OK: - print("¡Empty Library!") + print("Library cleared") else: - print("Error emptying library") + print("Failed to clear library") if c == "q": - print("Leavinf of fingerprint program") - raise SystemExit \ No newline at end of file + print("Exiting program") + break \ No newline at end of file From 3ea128c49aca27a944ce476419b80527b749da41 Mon Sep 17 00:00:00 2001 From: itsFDavid Date: Fri, 4 Oct 2024 22:39:34 -0600 Subject: [PATCH 04/13] Refactor code for improved performance and add program to compare template with fingerprint folder --- ...nt_template_folder_compare_with_file.py.py | 140 +++++------------- 1 file changed, 39 insertions(+), 101 deletions(-) diff --git a/examples/fingerprint_template_folder_compare_with_file.py.py b/examples/fingerprint_template_folder_compare_with_file.py.py index 9d33f15..cd60533 100644 --- a/examples/fingerprint_template_folder_compare_with_file.py.py +++ b/examples/fingerprint_template_folder_compare_with_file.py.py @@ -20,9 +20,6 @@ import os import time from PIL import Image - -##################### Settings for the serial port - import serial import adafruit_fingerprint @@ -34,15 +31,10 @@ finger = adafruit_fingerprint.Adafruit_Fingerprint(uart) -################################################## - # Folder where fingerprint templates are stored FINGERPRINT_FOLDER = "fingerprint/" -################################################## # Enroll and verification functions -################################################## - def get_num(max_num): """ Prompts the user to enter a valid template number. @@ -53,8 +45,7 @@ def get_num(max_num): num = int(input(f"Enter a template number (0-{max_num}): ")) if 0 <= num <= max_num: return num - else: - print(f"Please enter a number between 0 and {max_num}.") + print(f"Please enter a number between 0 and {max_num}.") except ValueError: print("Invalid input. Please enter a valid number.") @@ -64,97 +55,55 @@ def get_fingerprint(): print("Waiting for finger...") while finger.get_image() != adafruit_fingerprint.OK: pass + print("Processing image...") if finger.image_2_tz(1) != adafruit_fingerprint.OK: return False - print("Searching for matches...") - if finger.finger_search() != adafruit_fingerprint.OK: - return False - return True - -def get_fingerprint_detail(): - """Get an image from the fingerprint sensor and return details/errors.""" - print("Waiting for finger...", end="") - i = finger.get_image() - if i == adafruit_fingerprint.OK: - print("Image captured") - else: - print("Error capturing image") - return False - print("Processing image...", end="") - i = finger.image_2_tz(1) - if i == adafruit_fingerprint.OK: - print("Image processed") - else: - print("Error processing image") - return False + print("Searching for matches...") + return finger.finger_search() == adafruit_fingerprint.OK - print("Searching for matches...", end="") - i = finger.finger_fast_search() - if i == adafruit_fingerprint.OK: - print("Fingerprint found!") - return True - return False def enroll_finger(location): """Enroll a fingerprint and store it in the specified location.""" for fingerimg in range(1, 3): - if fingerimg == 1: - print("Please place your finger on the sensor...", end="") - else: - print("Place the same finger again...", end="") + action = "Place finger on sensor" if fingerimg == 1 else "Same finger again" + print(action, end="") while True: - i = finger.get_image() - if i == adafruit_fingerprint.OK: + if finger.get_image() == adafruit_fingerprint.OK: print("Image captured") break - if i == adafruit_fingerprint.NOFINGER: - print(".", end="") - else: - print("Error capturing image") - return False + print(".", end="") print("Processing image...", end="") - i = finger.image_2_tz(fingerimg) - if i == adafruit_fingerprint.OK: - print("Image processed") - else: + if finger.image_2_tz(fingerimg) != adafruit_fingerprint.OK: print("Error processing image") return False if fingerimg == 1: print("Remove finger") time.sleep(1) - while i != adafruit_fingerprint.NOFINGER: - i = finger.get_image() + while finger.get_image() != adafruit_fingerprint.NOFINGER: + pass print("Creating model...", end="") - i = finger.create_model() - if i == adafruit_fingerprint.OK: - print("Model created") - else: + if finger.create_model() != adafruit_fingerprint.OK: print("Error creating model") return False print(f"Storing model in location #{location}...", end="") - i = finger.store_model(location) - if i == adafruit_fingerprint.OK: - print("Model stored") - else: + if finger.store_model(location) != adafruit_fingerprint.OK: print("Error storing model") return False + print("Model stored") return True -################################################## -# Save and Compare from File Functions -################################################## def save_fingerprint_image(filename): """Capture a fingerprint and save the image to a file.""" - while finger.get_image(): + while finger.get_image() != adafruit_fingerprint.OK: pass img = Image.new("L", (256, 288), "white") @@ -180,46 +129,32 @@ def save_fingerprint_image(filename): def enroll_save_to_file(): """Capture a fingerprint, create a model, and save it to a file.""" for fingerimg in range(1, 3): - if fingerimg == 1: - print("Please place your finger on the sensor...", end="") - else: - print("Place the same finger again...", end="") + action = "Place finger on sensor" if fingerimg == 1 else "Same finger again" + print(action, end="") while True: - i = finger.get_image() - if i == adafruit_fingerprint.OK: + if finger.get_image() == adafruit_fingerprint.OK: print("Image captured") break - if i == adafruit_fingerprint.NOFINGER: - print(".", end="") - else: - print("Error capturing image") - return False + print(".", end="") print("Processing image...", end="") - i = finger.image_2_tz(fingerimg) - if i == adafruit_fingerprint.OK: - print("Image processed") - else: + if finger.image_2_tz(fingerimg) != adafruit_fingerprint.OK: print("Error processing image") return False if fingerimg == 1: print("Remove finger") - while i != adafruit_fingerprint.NOFINGER: - i = finger.get_image() + while finger.get_image() != adafruit_fingerprint.NOFINGER: + pass print("Creating model...", end="") - i = finger.create_model() - if i == adafruit_fingerprint.OK: - print("Model created") - else: + if finger.create_model() != adafruit_fingerprint.OK: print("Error creating model") return False print("Storing template...") data = finger.get_fpdata("char", 1) - # Save the template with a unique filename based on the current time filename = os.path.join(FINGERPRINT_FOLDER, f"template_{int(time.time())}.dat") with open(filename, "wb") as file: file.write(bytearray(data)) @@ -227,11 +162,13 @@ def enroll_save_to_file(): return True + def fingerprint_check_folder(): """Compare a fingerprint with all files in the fingerprint folder.""" print("Waiting for fingerprint...") while finger.get_image() != adafruit_fingerprint.OK: pass + print("Processing image...") if finger.image_2_tz(1) != adafruit_fingerprint.OK: return False @@ -246,8 +183,7 @@ def fingerprint_check_folder(): with open(file_path, "rb") as file: data = file.read() finger.send_fpdata(list(data), "char", 2) - i = finger.compare_templates() - if i == adafruit_fingerprint.OK: + if finger.compare_templates() == adafruit_fingerprint.OK: matched_filename = filename found_match = True break # Stop searching after finding a match @@ -259,21 +195,22 @@ def fingerprint_check_folder(): return found_match -################################################## -# Main program loop -################################################## +# Main program loop while True: print("----------------") if finger.read_templates() != adafruit_fingerprint.OK: raise RuntimeError("Could not read templates") print("Stored fingerprint templates: ", finger.templates) + if finger.count_templates() != adafruit_fingerprint.OK: raise RuntimeError("Could not count templates") print("Number of templates found: ", finger.template_count) + if finger.read_sysparam() != adafruit_fingerprint.OK: raise RuntimeError("Could not retrieve system parameters.") print("Template library size: ", finger.library_size) + print("e) Enroll fingerprint") print("f) Search fingerprint") print("d) Delete fingerprint") @@ -283,34 +220,35 @@ def fingerprint_check_folder(): print("r) Reset library") print("q) Exit") print("----------------") + c = input("> ") if c == "e": enroll_finger(get_num(finger.library_size)) - if c == "f": + elif c == "f": if get_fingerprint(): print("Fingerprint detected with ID#",finger.finger_id,"& confidence",finger.confidence) else: print("Fingerprint not found") - if c == "d": + elif c == "d": if finger.delete_model(get_num(finger.library_size)) == adafruit_fingerprint.OK: print("Deleted successfully!") else: print("Error deleting") - if c == "s": + elif c == "s": if save_fingerprint_image("fingerprint.png"): print("Fingerprint image saved") else: print("Error saving image") - if c == "cf": + elif c == "cf": fingerprint_check_folder() - if c == "esf": + elif c == "esf": enroll_save_to_file() - if c == "r": + elif c == "r": if finger.empty_library() == adafruit_fingerprint.OK: print("Library cleared") else: print("Failed to clear library") - if c == "q": + elif c == "q": print("Exiting program") - break \ No newline at end of file + break From 890db1db92535618263a91df11fcab4b637b16f9 Mon Sep 17 00:00:00 2001 From: itsFDavid Date: Fri, 4 Oct 2024 23:30:17 -0600 Subject: [PATCH 05/13] Refactor code for improved performance and add program to compare template with fingerprint folder --- ...rint_template_folder_compare_with_file.py} | 182 +++++++++++------- 1 file changed, 110 insertions(+), 72 deletions(-) rename examples/{fingerprint_template_folder_compare_with_file.py.py => fingerprint_template_folder_compare_with_file.py} (60%) diff --git a/examples/fingerprint_template_folder_compare_with_file.py.py b/examples/fingerprint_template_folder_compare_with_file.py similarity index 60% rename from examples/fingerprint_template_folder_compare_with_file.py.py rename to examples/fingerprint_template_folder_compare_with_file.py index cd60533..affcf53 100644 --- a/examples/fingerprint_template_folder_compare_with_file.py.py +++ b/examples/fingerprint_template_folder_compare_with_file.py @@ -14,12 +14,19 @@ Implementation Notes -------------------- This program was used on other fingerprint sensors, -and everything worked as expected, including testing with Raspberry Pi Zero 2. +and everything worked as expected, including testing with Raspberry Pi Zero 2W. + +To run the program: +1. Connect the fingerprint sensor to your Raspberry Pi. +2. Install required libraries. +3. Execute the script using Python. """ import os +import sys import time from PIL import Image + import serial import adafruit_fingerprint @@ -36,10 +43,7 @@ # Enroll and verification functions def get_num(max_num): - """ - Prompts the user to enter a valid template number. - Ensures that the number is within the available template range. - """ + """Prompts the user to enter a valid template number within the available range.""" while True: try: num = int(input(f"Enter a template number (0-{max_num}): ")) @@ -49,7 +53,6 @@ def get_num(max_num): except ValueError: print("Invalid input. Please enter a valid number.") - def get_fingerprint(): """Get an image from the fingerprint sensor for search, process for a match.""" print("Waiting for finger...") @@ -58,12 +61,12 @@ def get_fingerprint(): print("Processing image...") if finger.image_2_tz(1) != adafruit_fingerprint.OK: + print("Error processing image.") return False print("Searching for matches...") return finger.finger_search() == adafruit_fingerprint.OK - def enroll_finger(location): """Enroll a fingerprint and store it in the specified location.""" for fingerimg in range(1, 3): @@ -78,7 +81,7 @@ def enroll_finger(location): print("Processing image...", end="") if finger.image_2_tz(fingerimg) != adafruit_fingerprint.OK: - print("Error processing image") + print("Error processing image.") return False if fingerimg == 1: @@ -89,20 +92,20 @@ def enroll_finger(location): print("Creating model...", end="") if finger.create_model() != adafruit_fingerprint.OK: - print("Error creating model") + print("Error creating model.") return False print(f"Storing model in location #{location}...", end="") if finger.store_model(location) != adafruit_fingerprint.OK: - print("Error storing model") + print("Error storing model.") return False - print("Model stored") + print("Model stored.") return True - def save_fingerprint_image(filename): """Capture a fingerprint and save the image to a file.""" + print("Waiting for finger...") while finger.get_image() != adafruit_fingerprint.OK: pass @@ -113,6 +116,8 @@ def save_fingerprint_image(filename): x, y = 0, 0 for i, value in enumerate(result): + if i % 100 == 0: + print("", end="") pixeldata[x, y] = (int(value) >> 4) * 17 x += 1 pixeldata[x, y] = (int(value) & mask) * 17 @@ -123,6 +128,7 @@ def save_fingerprint_image(filename): x += 1 img.save(filename) + print(f"\nImage saved to {filename}") return True @@ -140,7 +146,7 @@ def enroll_save_to_file(): print("Processing image...", end="") if finger.image_2_tz(fingerimg) != adafruit_fingerprint.OK: - print("Error processing image") + print("Error processing image.") return False if fingerimg == 1: @@ -150,7 +156,7 @@ def enroll_save_to_file(): print("Creating model...", end="") if finger.create_model() != adafruit_fingerprint.OK: - print("Error creating model") + print("Error creating model.") return False print("Storing template...") @@ -162,7 +168,6 @@ def enroll_save_to_file(): return True - def fingerprint_check_folder(): """Compare a fingerprint with all files in the fingerprint folder.""" print("Waiting for fingerprint...") @@ -171,6 +176,7 @@ def fingerprint_check_folder(): print("Processing image...") if finger.image_2_tz(1) != adafruit_fingerprint.OK: + print("Error processing image.") return False print("Searching for matches in the template folder...", end="") @@ -186,69 +192,101 @@ def fingerprint_check_folder(): if finger.compare_templates() == adafruit_fingerprint.OK: matched_filename = filename found_match = True - break # Stop searching after finding a match + break if found_match: print(f"Fingerprint matches the template in the file {matched_filename}!") else: - print("No match found") + print("No match found.") return found_match +def main(): + """Main function to run the fingerprint enrollment and verification program. -# Main program loop -while True: - print("----------------") - if finger.read_templates() != adafruit_fingerprint.OK: - raise RuntimeError("Could not read templates") - print("Stored fingerprint templates: ", finger.templates) - - if finger.count_templates() != adafruit_fingerprint.OK: - raise RuntimeError("Could not count templates") - print("Number of templates found: ", finger.template_count) - - if finger.read_sysparam() != adafruit_fingerprint.OK: - raise RuntimeError("Could not retrieve system parameters.") - print("Template library size: ", finger.library_size) - - print("e) Enroll fingerprint") - print("f) Search fingerprint") - print("d) Delete fingerprint") - print("s) Save fingerprint image") - print("cf) Compare template with file") - print("esf) Enroll and save to file") - print("r) Reset library") - print("q) Exit") - print("----------------") - - c = input("> ") - - if c == "e": - enroll_finger(get_num(finger.library_size)) - elif c == "f": - if get_fingerprint(): - print("Fingerprint detected with ID#",finger.finger_id,"& confidence",finger.confidence) - else: - print("Fingerprint not found") - elif c == "d": - if finger.delete_model(get_num(finger.library_size)) == adafruit_fingerprint.OK: - print("Deleted successfully!") - else: - print("Error deleting") - elif c == "s": - if save_fingerprint_image("fingerprint.png"): - print("Fingerprint image saved") - else: - print("Error saving image") - elif c == "cf": - fingerprint_check_folder() - elif c == "esf": - enroll_save_to_file() - elif c == "r": - if finger.empty_library() == adafruit_fingerprint.OK: - print("Library cleared") + This function provides a menu for the user to enroll fingerprints, search for + fingerprints, delete templates, save fingerprint images, and reset the fingerprint library. + It interacts with the user via the console and performs the necessary actions based on + user input. + """ + actions = { + "e": lambda: enroll_finger(get_num(finger.library_size)), + "f": lambda: print_fingerprint(), + "d": lambda: delete_fingerprint(), + "s": lambda: save_fingerprint_image(f"fingerprint_{int(time.time())}.png"), + "cf": lambda: fingerprint_check_folder(), + "esf": lambda: enroll_save_to_file(), + "r": lambda: reset_library(), + "q": lambda: exit_program() + } + + while True: + print("----------------") + if finger.read_templates() != adafruit_fingerprint.OK: + raise RuntimeError("Could not read templates.") + print("Stored fingerprint templates: ", finger.templates) + + if finger.count_templates() != adafruit_fingerprint.OK: + raise RuntimeError("Could not count templates.") + print("Number of templates found: ", finger.template_count) + + if finger.read_sysparam() != adafruit_fingerprint.OK: + raise RuntimeError("Could not retrieve system parameters.") + print("Template library size: ", finger.library_size) + + print("Options:") + for option in actions.keys(): + print(f"{option}) {option_description(option)}") + print("----------------") + + c = input("> ") + + if c in actions: + actions[c]() else: - print("Failed to clear library") - elif c == "q": - print("Exiting program") - break + print("Invalid option.") + +def print_fingerprint(): + """Prints the fingerprint detection result.""" + if get_fingerprint(): + output_finger_detected=f"Fingerprint detected with ID #{finger.finger_id}" + output_finger_confidence=f"Confidence: {finger.confidence}" + print(output_finger_detected) + print(output_finger_confidence) + else: + print("Fingerprint not found.") + +def delete_fingerprint(): + """Deletes a fingerprint model based on user input.""" + if finger.delete_model(get_num(finger.library_size)) == adafruit_fingerprint.OK: + print("Deleted successfully!") + else: + print("Failed to delete.") +def reset_library(): + """Resets the fingerprint library.""" + if finger.empty_library() == adafruit_fingerprint.OK: + print("Library reset.") + else: + print("Failed to reset library.") + +def exit_program(): + """Exits the program.""" + print("Exiting...") + sys.exit(0) + +def option_description(option): + """Returns a description for each menu option.""" + descriptions = { + "e": "Enroll fingerprint", + "f": "Search fingerprint", + "d": "Delete fingerprint", + "s": "Save fingerprint image", + "cf": "Compare template with file", + "esf": "Enroll and save to file", + "r": "Reset library", + "q": "Exit" + } + return descriptions.get(option, "No description available.") + +if __name__ == "__main__": + main() From a6bf0aff53df45671012ca856e5c774aaec59420 Mon Sep 17 00:00:00 2001 From: itsFDavid Date: Sat, 5 Oct 2024 21:44:34 -0600 Subject: [PATCH 06/13] Refactor code for improved performance and update menu options --- ...print_template_folder_compare_with_file.py | 59 +++++++++---------- 1 file changed, 28 insertions(+), 31 deletions(-) diff --git a/examples/fingerprint_template_folder_compare_with_file.py b/examples/fingerprint_template_folder_compare_with_file.py index affcf53..f7a4e32 100644 --- a/examples/fingerprint_template_folder_compare_with_file.py +++ b/examples/fingerprint_template_folder_compare_with_file.py @@ -209,17 +209,6 @@ def main(): It interacts with the user via the console and performs the necessary actions based on user input. """ - actions = { - "e": lambda: enroll_finger(get_num(finger.library_size)), - "f": lambda: print_fingerprint(), - "d": lambda: delete_fingerprint(), - "s": lambda: save_fingerprint_image(f"fingerprint_{int(time.time())}.png"), - "cf": lambda: fingerprint_check_folder(), - "esf": lambda: enroll_save_to_file(), - "r": lambda: reset_library(), - "q": lambda: exit_program() - } - while True: print("----------------") if finger.read_templates() != adafruit_fingerprint.OK: @@ -235,16 +224,38 @@ def main(): print("Template library size: ", finger.library_size) print("Options:") - for option in actions.keys(): - print(f"{option}) {option_description(option)}") + print("e) Enroll fingerprint") + print("f) Search fingerprint") + print("d) Delete fingerprint") + print("s) Save fingerprint image") + print("cf) Compare template with file") + print("esf) Enroll and save to file") + print("r) Reset library") + print("q) Exit") print("----------------") c = input("> ") - if c in actions: - actions[c]() - else: - print("Invalid option.") + match c: + case "e": + enroll_finger(get_num(finger.library_size)) + case "f": + print_fingerprint() + case "d": + delete_fingerprint() + case "s": + save_fingerprint_image(f"fingerprint_{int(time.time())}.png") + case "cf": + fingerprint_check_folder() + case "esf": + enroll_save_to_file() + case "r": + reset_library() + case "q": + exit_program() + case _: + print("Invalid option.") + def print_fingerprint(): """Prints the fingerprint detection result.""" @@ -268,25 +279,11 @@ def reset_library(): print("Library reset.") else: print("Failed to reset library.") - def exit_program(): """Exits the program.""" print("Exiting...") sys.exit(0) -def option_description(option): - """Returns a description for each menu option.""" - descriptions = { - "e": "Enroll fingerprint", - "f": "Search fingerprint", - "d": "Delete fingerprint", - "s": "Save fingerprint image", - "cf": "Compare template with file", - "esf": "Enroll and save to file", - "r": "Reset library", - "q": "Exit" - } - return descriptions.get(option, "No description available.") if __name__ == "__main__": main() From e741c79392775bc6a54a39b8f938a6dc0d4b7232 Mon Sep 17 00:00:00 2001 From: itsFDavid Date: Sat, 5 Oct 2024 21:56:52 -0600 Subject: [PATCH 07/13] Refactor code for improved performance for black format --- ...erprint_template_folder_compare_with_file.py | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/examples/fingerprint_template_folder_compare_with_file.py b/examples/fingerprint_template_folder_compare_with_file.py index f7a4e32..4dc185a 100644 --- a/examples/fingerprint_template_folder_compare_with_file.py +++ b/examples/fingerprint_template_folder_compare_with_file.py @@ -53,6 +53,7 @@ def get_num(max_num): except ValueError: print("Invalid input. Please enter a valid number.") + def get_fingerprint(): """Get an image from the fingerprint sensor for search, process for a match.""" print("Waiting for finger...") @@ -67,6 +68,7 @@ def get_fingerprint(): print("Searching for matches...") return finger.finger_search() == adafruit_fingerprint.OK + def enroll_finger(location): """Enroll a fingerprint and store it in the specified location.""" for fingerimg in range(1, 3): @@ -103,6 +105,7 @@ def enroll_finger(location): print("Model stored.") return True + def save_fingerprint_image(filename): """Capture a fingerprint and save the image to a file.""" print("Waiting for finger...") @@ -161,13 +164,17 @@ def enroll_save_to_file(): print("Storing template...") data = finger.get_fpdata("char", 1) - filename = os.path.join(FINGERPRINT_FOLDER, f"template_{int(time.time())}.dat") + filename = os.path.join( + FINGERPRINT_FOLDER, + f"template_{int(time.time())}.dat" + ) with open(filename, "wb") as file: file.write(bytearray(data)) print(f"Template saved to {filename}") return True + def fingerprint_check_folder(): """Compare a fingerprint with all files in the fingerprint folder.""" print("Waiting for fingerprint...") @@ -201,6 +208,7 @@ def fingerprint_check_folder(): return found_match + def main(): """Main function to run the fingerprint enrollment and verification program. @@ -233,9 +241,7 @@ def main(): print("r) Reset library") print("q) Exit") print("----------------") - c = input("> ") - match c: case "e": enroll_finger(get_num(finger.library_size)) @@ -267,18 +273,23 @@ def print_fingerprint(): else: print("Fingerprint not found.") + def delete_fingerprint(): """Deletes a fingerprint model based on user input.""" if finger.delete_model(get_num(finger.library_size)) == adafruit_fingerprint.OK: print("Deleted successfully!") else: print("Failed to delete.") + + def reset_library(): """Resets the fingerprint library.""" if finger.empty_library() == adafruit_fingerprint.OK: print("Library reset.") else: print("Failed to reset library.") + + def exit_program(): """Exits the program.""" print("Exiting...") From 21dc7f119d431851bb1c2e1e91f9dd4d2097d00a Mon Sep 17 00:00:00 2001 From: itsFDavid Date: Sat, 5 Oct 2024 22:02:36 -0600 Subject: [PATCH 08/13] format code with isort --- examples/fingerprint_template_folder_compare_with_file.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/fingerprint_template_folder_compare_with_file.py b/examples/fingerprint_template_folder_compare_with_file.py index 4dc185a..a7ada2f 100644 --- a/examples/fingerprint_template_folder_compare_with_file.py +++ b/examples/fingerprint_template_folder_compare_with_file.py @@ -25,10 +25,10 @@ import os import sys import time -from PIL import Image -import serial import adafruit_fingerprint +import serial +from PIL import Image # If using with a computer such as Linux/RaspberryPi, Mac, Windows with USB/serial converter: # uart = serial.Serial("COM6", baudrate=57600, timeout=1) From ef16bfdfd038aa1fe3ece2563a4577b9904d0bb6 Mon Sep 17 00:00:00 2001 From: itsFDavid Date: Sat, 5 Oct 2024 22:03:42 -0600 Subject: [PATCH 09/13] format code with black --- .../fingerprint_template_folder_compare_with_file.py | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/examples/fingerprint_template_folder_compare_with_file.py b/examples/fingerprint_template_folder_compare_with_file.py index a7ada2f..87eae21 100644 --- a/examples/fingerprint_template_folder_compare_with_file.py +++ b/examples/fingerprint_template_folder_compare_with_file.py @@ -41,6 +41,7 @@ # Folder where fingerprint templates are stored FINGERPRINT_FOLDER = "fingerprint/" + # Enroll and verification functions def get_num(max_num): """Prompts the user to enter a valid template number within the available range.""" @@ -164,10 +165,7 @@ def enroll_save_to_file(): print("Storing template...") data = finger.get_fpdata("char", 1) - filename = os.path.join( - FINGERPRINT_FOLDER, - f"template_{int(time.time())}.dat" - ) + filename = os.path.join(FINGERPRINT_FOLDER, f"template_{int(time.time())}.dat") with open(filename, "wb") as file: file.write(bytearray(data)) print(f"Template saved to {filename}") @@ -266,8 +264,8 @@ def main(): def print_fingerprint(): """Prints the fingerprint detection result.""" if get_fingerprint(): - output_finger_detected=f"Fingerprint detected with ID #{finger.finger_id}" - output_finger_confidence=f"Confidence: {finger.confidence}" + output_finger_detected = f"Fingerprint detected with ID #{finger.finger_id}" + output_finger_confidence = f"Confidence: {finger.confidence}" print(output_finger_detected) print(output_finger_confidence) else: From 386ce6b75ba4a593d5c4e4e3a0c53fbd007a7d21 Mon Sep 17 00:00:00 2001 From: itsFDavid Date: Sat, 5 Oct 2024 22:21:23 -0600 Subject: [PATCH 10/13] Refactor code for improved performance --- ...print_template_folder_compare_with_file.py | 26 +------------------ 1 file changed, 1 insertion(+), 25 deletions(-) diff --git a/examples/fingerprint_template_folder_compare_with_file.py b/examples/fingerprint_template_folder_compare_with_file.py index 87eae21..69bd3f9 100644 --- a/examples/fingerprint_template_folder_compare_with_file.py +++ b/examples/fingerprint_template_folder_compare_with_file.py @@ -60,12 +60,10 @@ def get_fingerprint(): print("Waiting for finger...") while finger.get_image() != adafruit_fingerprint.OK: pass - print("Processing image...") if finger.image_2_tz(1) != adafruit_fingerprint.OK: print("Error processing image.") return False - print("Searching for matches...") return finger.finger_search() == adafruit_fingerprint.OK @@ -75,34 +73,28 @@ def enroll_finger(location): for fingerimg in range(1, 3): action = "Place finger on sensor" if fingerimg == 1 else "Same finger again" print(action, end="") - while True: if finger.get_image() == adafruit_fingerprint.OK: print("Image captured") break print(".", end="") - print("Processing image...", end="") if finger.image_2_tz(fingerimg) != adafruit_fingerprint.OK: print("Error processing image.") return False - if fingerimg == 1: print("Remove finger") time.sleep(1) while finger.get_image() != adafruit_fingerprint.NOFINGER: pass - print("Creating model...", end="") if finger.create_model() != adafruit_fingerprint.OK: print("Error creating model.") return False - print(f"Storing model in location #{location}...", end="") if finger.store_model(location) != adafruit_fingerprint.OK: print("Error storing model.") return False - print("Model stored.") return True @@ -112,12 +104,10 @@ def save_fingerprint_image(filename): print("Waiting for finger...") while finger.get_image() != adafruit_fingerprint.OK: pass - img = Image.new("L", (256, 288), "white") pixeldata = img.load() mask = 0b00001111 result = finger.get_fpdata(sensorbuffer="image") - x, y = 0, 0 for i, value in enumerate(result): if i % 100 == 0: @@ -130,7 +120,6 @@ def save_fingerprint_image(filename): y += 1 else: x += 1 - img.save(filename) print(f"\nImage saved to {filename}") return True @@ -141,35 +130,29 @@ def enroll_save_to_file(): for fingerimg in range(1, 3): action = "Place finger on sensor" if fingerimg == 1 else "Same finger again" print(action, end="") - while True: if finger.get_image() == adafruit_fingerprint.OK: print("Image captured") break print(".", end="") - print("Processing image...", end="") if finger.image_2_tz(fingerimg) != adafruit_fingerprint.OK: print("Error processing image.") return False - if fingerimg == 1: print("Remove finger") while finger.get_image() != adafruit_fingerprint.NOFINGER: pass - print("Creating model...", end="") if finger.create_model() != adafruit_fingerprint.OK: print("Error creating model.") return False - print("Storing template...") data = finger.get_fpdata("char", 1) filename = os.path.join(FINGERPRINT_FOLDER, f"template_{int(time.time())}.dat") with open(filename, "wb") as file: file.write(bytearray(data)) print(f"Template saved to {filename}") - return True @@ -178,16 +161,13 @@ def fingerprint_check_folder(): print("Waiting for fingerprint...") while finger.get_image() != adafruit_fingerprint.OK: pass - print("Processing image...") if finger.image_2_tz(1) != adafruit_fingerprint.OK: print("Error processing image.") return False - print("Searching for matches in the template folder...", end="") found_match = False matched_filename = None - for filename in os.listdir(FINGERPRINT_FOLDER): if filename.endswith(".dat"): file_path = os.path.join(FINGERPRINT_FOLDER, filename) @@ -198,18 +178,15 @@ def fingerprint_check_folder(): matched_filename = filename found_match = True break - if found_match: print(f"Fingerprint matches the template in the file {matched_filename}!") else: print("No match found.") - return found_match def main(): """Main function to run the fingerprint enrollment and verification program. - This function provides a menu for the user to enroll fingerprints, search for fingerprints, delete templates, save fingerprint images, and reset the fingerprint library. It interacts with the user via the console and performs the necessary actions based on @@ -228,7 +205,6 @@ def main(): if finger.read_sysparam() != adafruit_fingerprint.OK: raise RuntimeError("Could not retrieve system parameters.") print("Template library size: ", finger.library_size) - print("Options:") print("e) Enroll fingerprint") print("f) Search fingerprint") @@ -291,7 +267,7 @@ def reset_library(): def exit_program(): """Exits the program.""" print("Exiting...") - sys.exit(0) + raise SystemExit if __name__ == "__main__": From 954dac2f4d3f242a499c3d8417fea55b01fbbf5d Mon Sep 17 00:00:00 2001 From: itsFDavid Date: Sat, 5 Oct 2024 22:29:18 -0600 Subject: [PATCH 11/13] Refactor code for improved performance --- examples/fingerprint_template_folder_compare_with_file.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/examples/fingerprint_template_folder_compare_with_file.py b/examples/fingerprint_template_folder_compare_with_file.py index 69bd3f9..3dd55e4 100644 --- a/examples/fingerprint_template_folder_compare_with_file.py +++ b/examples/fingerprint_template_folder_compare_with_file.py @@ -23,12 +23,11 @@ """ import os -import sys import time -import adafruit_fingerprint import serial from PIL import Image +import adafruit_fingerprint # If using with a computer such as Linux/RaspberryPi, Mac, Windows with USB/serial converter: # uart = serial.Serial("COM6", baudrate=57600, timeout=1) From 0f98a8cf944eaffb1472272d87a42dada47aba4e Mon Sep 17 00:00:00 2001 From: itsFDavid Date: Sat, 5 Oct 2024 22:29:38 -0600 Subject: [PATCH 12/13] Refactor code for pass pylint --- ...print_template_folder_compare_with_file.py | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/examples/fingerprint_template_folder_compare_with_file.py b/examples/fingerprint_template_folder_compare_with_file.py index 3dd55e4..f5ce68b 100644 --- a/examples/fingerprint_template_folder_compare_with_file.py +++ b/examples/fingerprint_template_folder_compare_with_file.py @@ -107,18 +107,18 @@ def save_fingerprint_image(filename): pixeldata = img.load() mask = 0b00001111 result = finger.get_fpdata(sensorbuffer="image") - x, y = 0, 0 + coor_x, coor_y = 0, 0 for i, value in enumerate(result): if i % 100 == 0: print("", end="") - pixeldata[x, y] = (int(value) >> 4) * 17 - x += 1 - pixeldata[x, y] = (int(value) & mask) * 17 - if x == 255: - x = 0 - y += 1 + pixeldata[coor_x, coor_y] = (int(value) >> 4) * 17 + coor_x += 1 + pixeldata[coor_x, coor_y] = (int(value) & mask) * 17 + if coor_x == 255: + coor_x = 0 + coor_y += 1 else: - x += 1 + coor_x += 1 img.save(filename) print(f"\nImage saved to {filename}") return True @@ -214,8 +214,8 @@ def main(): print("r) Reset library") print("q) Exit") print("----------------") - c = input("> ") - match c: + user_choice = input("> ") + match user_choice.lower(): case "e": enroll_finger(get_num(finger.library_size)) case "f": From 35408d6eb6a9174861ae5c3405d0e3d788588d74 Mon Sep 17 00:00:00 2001 From: itsFDavid Date: Mon, 7 Oct 2024 22:07:05 -0600 Subject: [PATCH 13/13] Refactor code for renaming fingerprint template file for Raspberry Pi --- ....py => fingerprint_template_folder_compare_with_file_rpi.py} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename examples/{fingerprint_template_folder_compare_with_file.py => fingerprint_template_folder_compare_with_file_rpi.py} (99%) diff --git a/examples/fingerprint_template_folder_compare_with_file.py b/examples/fingerprint_template_folder_compare_with_file_rpi.py similarity index 99% rename from examples/fingerprint_template_folder_compare_with_file.py rename to examples/fingerprint_template_folder_compare_with_file_rpi.py index f5ce68b..b68ef5b 100644 --- a/examples/fingerprint_template_folder_compare_with_file.py +++ b/examples/fingerprint_template_folder_compare_with_file_rpi.py @@ -1,4 +1,4 @@ -# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-FileCopyrightText: 2024 itsFDavid # SPDX-License-Identifier: MIT """ `fingerprint_template_folder_compare_with_file.py`