Skip to content

Commit 39c71bf

Browse files
authored
Merge pull request #55 from itsFDavid/compare_with_file
add program to compare template with fingerprint folfer
2 parents 2c7d330 + 35408d6 commit 39c71bf

File tree

1 file changed

+273
-0
lines changed

1 file changed

+273
-0
lines changed
Lines changed: 273 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,273 @@
1+
# SPDX-FileCopyrightText: 2024 itsFDavid
2+
# SPDX-License-Identifier: MIT
3+
"""
4+
`fingerprint_template_folder_compare_with_file.py`
5+
====================================================
6+
7+
This is an example program to demo storing fingerprint templates in a folder. It also allows
8+
comparing a newly obtained print with one stored in the folder in the previous step. This is helpful
9+
when fingerprint templates are stored centrally (not on sensor's flash memory) and shared
10+
between multiple sensors.
11+
12+
* Author(s): itsFDavid
13+
14+
Implementation Notes
15+
--------------------
16+
This program was used on other fingerprint sensors,
17+
and everything worked as expected, including testing with Raspberry Pi Zero 2W.
18+
19+
To run the program:
20+
1. Connect the fingerprint sensor to your Raspberry Pi.
21+
2. Install required libraries.
22+
3. Execute the script using Python.
23+
"""
24+
25+
import os
26+
import time
27+
28+
import serial
29+
from PIL import Image
30+
import adafruit_fingerprint
31+
32+
# If using with a computer such as Linux/RaspberryPi, Mac, Windows with USB/serial converter:
33+
# uart = serial.Serial("COM6", baudrate=57600, timeout=1)
34+
35+
# If using with Linux/Raspberry Pi and hardware UART:
36+
uart = serial.Serial("/dev/ttyUSB0", baudrate=57600, timeout=1)
37+
38+
finger = adafruit_fingerprint.Adafruit_Fingerprint(uart)
39+
40+
# Folder where fingerprint templates are stored
41+
FINGERPRINT_FOLDER = "fingerprint/"
42+
43+
44+
# Enroll and verification functions
45+
def get_num(max_num):
46+
"""Prompts the user to enter a valid template number within the available range."""
47+
while True:
48+
try:
49+
num = int(input(f"Enter a template number (0-{max_num}): "))
50+
if 0 <= num <= max_num:
51+
return num
52+
print(f"Please enter a number between 0 and {max_num}.")
53+
except ValueError:
54+
print("Invalid input. Please enter a valid number.")
55+
56+
57+
def get_fingerprint():
58+
"""Get an image from the fingerprint sensor for search, process for a match."""
59+
print("Waiting for finger...")
60+
while finger.get_image() != adafruit_fingerprint.OK:
61+
pass
62+
print("Processing image...")
63+
if finger.image_2_tz(1) != adafruit_fingerprint.OK:
64+
print("Error processing image.")
65+
return False
66+
print("Searching for matches...")
67+
return finger.finger_search() == adafruit_fingerprint.OK
68+
69+
70+
def enroll_finger(location):
71+
"""Enroll a fingerprint and store it in the specified location."""
72+
for fingerimg in range(1, 3):
73+
action = "Place finger on sensor" if fingerimg == 1 else "Same finger again"
74+
print(action, end="")
75+
while True:
76+
if finger.get_image() == adafruit_fingerprint.OK:
77+
print("Image captured")
78+
break
79+
print(".", end="")
80+
print("Processing image...", end="")
81+
if finger.image_2_tz(fingerimg) != adafruit_fingerprint.OK:
82+
print("Error processing image.")
83+
return False
84+
if fingerimg == 1:
85+
print("Remove finger")
86+
time.sleep(1)
87+
while finger.get_image() != adafruit_fingerprint.NOFINGER:
88+
pass
89+
print("Creating model...", end="")
90+
if finger.create_model() != adafruit_fingerprint.OK:
91+
print("Error creating model.")
92+
return False
93+
print(f"Storing model in location #{location}...", end="")
94+
if finger.store_model(location) != adafruit_fingerprint.OK:
95+
print("Error storing model.")
96+
return False
97+
print("Model stored.")
98+
return True
99+
100+
101+
def save_fingerprint_image(filename):
102+
"""Capture a fingerprint and save the image to a file."""
103+
print("Waiting for finger...")
104+
while finger.get_image() != adafruit_fingerprint.OK:
105+
pass
106+
img = Image.new("L", (256, 288), "white")
107+
pixeldata = img.load()
108+
mask = 0b00001111
109+
result = finger.get_fpdata(sensorbuffer="image")
110+
coor_x, coor_y = 0, 0
111+
for i, value in enumerate(result):
112+
if i % 100 == 0:
113+
print("", end="")
114+
pixeldata[coor_x, coor_y] = (int(value) >> 4) * 17
115+
coor_x += 1
116+
pixeldata[coor_x, coor_y] = (int(value) & mask) * 17
117+
if coor_x == 255:
118+
coor_x = 0
119+
coor_y += 1
120+
else:
121+
coor_x += 1
122+
img.save(filename)
123+
print(f"\nImage saved to {filename}")
124+
return True
125+
126+
127+
def enroll_save_to_file():
128+
"""Capture a fingerprint, create a model, and save it to a file."""
129+
for fingerimg in range(1, 3):
130+
action = "Place finger on sensor" if fingerimg == 1 else "Same finger again"
131+
print(action, end="")
132+
while True:
133+
if finger.get_image() == adafruit_fingerprint.OK:
134+
print("Image captured")
135+
break
136+
print(".", end="")
137+
print("Processing image...", end="")
138+
if finger.image_2_tz(fingerimg) != adafruit_fingerprint.OK:
139+
print("Error processing image.")
140+
return False
141+
if fingerimg == 1:
142+
print("Remove finger")
143+
while finger.get_image() != adafruit_fingerprint.NOFINGER:
144+
pass
145+
print("Creating model...", end="")
146+
if finger.create_model() != adafruit_fingerprint.OK:
147+
print("Error creating model.")
148+
return False
149+
print("Storing template...")
150+
data = finger.get_fpdata("char", 1)
151+
filename = os.path.join(FINGERPRINT_FOLDER, f"template_{int(time.time())}.dat")
152+
with open(filename, "wb") as file:
153+
file.write(bytearray(data))
154+
print(f"Template saved to {filename}")
155+
return True
156+
157+
158+
def fingerprint_check_folder():
159+
"""Compare a fingerprint with all files in the fingerprint folder."""
160+
print("Waiting for fingerprint...")
161+
while finger.get_image() != adafruit_fingerprint.OK:
162+
pass
163+
print("Processing image...")
164+
if finger.image_2_tz(1) != adafruit_fingerprint.OK:
165+
print("Error processing image.")
166+
return False
167+
print("Searching for matches in the template folder...", end="")
168+
found_match = False
169+
matched_filename = None
170+
for filename in os.listdir(FINGERPRINT_FOLDER):
171+
if filename.endswith(".dat"):
172+
file_path = os.path.join(FINGERPRINT_FOLDER, filename)
173+
with open(file_path, "rb") as file:
174+
data = file.read()
175+
finger.send_fpdata(list(data), "char", 2)
176+
if finger.compare_templates() == adafruit_fingerprint.OK:
177+
matched_filename = filename
178+
found_match = True
179+
break
180+
if found_match:
181+
print(f"Fingerprint matches the template in the file {matched_filename}!")
182+
else:
183+
print("No match found.")
184+
return found_match
185+
186+
187+
def main():
188+
"""Main function to run the fingerprint enrollment and verification program.
189+
This function provides a menu for the user to enroll fingerprints, search for
190+
fingerprints, delete templates, save fingerprint images, and reset the fingerprint library.
191+
It interacts with the user via the console and performs the necessary actions based on
192+
user input.
193+
"""
194+
while True:
195+
print("----------------")
196+
if finger.read_templates() != adafruit_fingerprint.OK:
197+
raise RuntimeError("Could not read templates.")
198+
print("Stored fingerprint templates: ", finger.templates)
199+
200+
if finger.count_templates() != adafruit_fingerprint.OK:
201+
raise RuntimeError("Could not count templates.")
202+
print("Number of templates found: ", finger.template_count)
203+
204+
if finger.read_sysparam() != adafruit_fingerprint.OK:
205+
raise RuntimeError("Could not retrieve system parameters.")
206+
print("Template library size: ", finger.library_size)
207+
print("Options:")
208+
print("e) Enroll fingerprint")
209+
print("f) Search fingerprint")
210+
print("d) Delete fingerprint")
211+
print("s) Save fingerprint image")
212+
print("cf) Compare template with file")
213+
print("esf) Enroll and save to file")
214+
print("r) Reset library")
215+
print("q) Exit")
216+
print("----------------")
217+
user_choice = input("> ")
218+
match user_choice.lower():
219+
case "e":
220+
enroll_finger(get_num(finger.library_size))
221+
case "f":
222+
print_fingerprint()
223+
case "d":
224+
delete_fingerprint()
225+
case "s":
226+
save_fingerprint_image(f"fingerprint_{int(time.time())}.png")
227+
case "cf":
228+
fingerprint_check_folder()
229+
case "esf":
230+
enroll_save_to_file()
231+
case "r":
232+
reset_library()
233+
case "q":
234+
exit_program()
235+
case _:
236+
print("Invalid option.")
237+
238+
239+
def print_fingerprint():
240+
"""Prints the fingerprint detection result."""
241+
if get_fingerprint():
242+
output_finger_detected = f"Fingerprint detected with ID #{finger.finger_id}"
243+
output_finger_confidence = f"Confidence: {finger.confidence}"
244+
print(output_finger_detected)
245+
print(output_finger_confidence)
246+
else:
247+
print("Fingerprint not found.")
248+
249+
250+
def delete_fingerprint():
251+
"""Deletes a fingerprint model based on user input."""
252+
if finger.delete_model(get_num(finger.library_size)) == adafruit_fingerprint.OK:
253+
print("Deleted successfully!")
254+
else:
255+
print("Failed to delete.")
256+
257+
258+
def reset_library():
259+
"""Resets the fingerprint library."""
260+
if finger.empty_library() == adafruit_fingerprint.OK:
261+
print("Library reset.")
262+
else:
263+
print("Failed to reset library.")
264+
265+
266+
def exit_program():
267+
"""Exits the program."""
268+
print("Exiting...")
269+
raise SystemExit
270+
271+
272+
if __name__ == "__main__":
273+
main()

0 commit comments

Comments
 (0)