from fastapi import FastAPI, File, UploadFile, HTTPException from PIL import Image import numpy as np from io import BytesIO import math import pickle import os app = FastAPI(title="Fingerprint detection API") som_model = None classification_matrix = None def sobel(I): m, n = I.shape Gx = np.zeros([m-2, n-2], np.float32) Gy = np.zeros([m-2, n-2], np.float32) gx = [[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]] gy = [[1, 2, 1], [0, 0, 0], [-1, -2, -1]] for j in range(1, m-2): for i in range(1, n-2): Gx[j-1, i-1] = sum(sum(I[j-1:j+2, i-1:i+2] * gx)) Gy[j-1, i-1] = sum(sum(I[j-1:j+2, i-1:i+2] * gy)) return Gx, Gy def medfilt2(G, d=3): m, n = G.shape temp = np.zeros([m+2*(d//2), n+2*(d//2)], np.float32) salida = np.zeros([m, n], np.float32) temp[1:m+1, 1:n+1] = G for i in range(1, m): for j in range(1, n): A = np.asarray(temp[i-1:i+2, j-1:j+2]).reshape(-1) salida[i-1, j-1] = np.sort(A)[d+1] return salida def orientacion(patron, w): Gx, Gy = sobel(patron) Gx = medfilt2(Gx) Gy = medfilt2(Gy) m, n = Gx.shape mOrientaciones = np.zeros([m//w, n//w], np.float32) for i in range(m//w): for j in range(n//w): YY = sum(sum(2*Gx[i*w:(i+1)*w, j*w:(j+1)*w]*Gy[i*w:(i+1)*w, j*w:(j+1)*w])) XX = sum(sum(Gx[i*w:(i+1)*w, j*w:(j+1)*w]**2-Gy[i*w:(i+1)*w, j*w:(j+1)*w]**2)) mOrientaciones[i, j] = (0.5*math.atan2(YY, XX) + math.pi/2.0)*(180.0/math.pi) return mOrientaciones def representativo(image_array): if isinstance(image_array, np.ndarray): if len(image_array.shape) == 3: image_array = np.mean(image_array, axis=2) im = Image.fromarray(image_array.astype(np.uint8)) else: im = image_array im = im.resize((256, 256)) m, n = im.size imarray = np.array(im, np.float32) patron = imarray[1:m-1, 1:n-1] EE = orientacion(patron, 14) return np.asarray(EE).reshape(-1) def is_valid_fingerprint_features(features): if features is None or len(features) != 324: return False if np.any(np.isnan(features)) or np.any(np.isinf(features)): return False if np.min(features) < 0 or np.max(features) > 180: return False orientation_variance = np.var(features) if orientation_variance < 100: return False bins = np.histogram(features, bins=18, range=(0, 180))[0] non_empty_bins = np.sum(bins > 0) if non_empty_bins < 6: return False return True def load_trained_model(): global som_model, classification_matrix try: if os.path.exists('somhuella.pkl'): with open('somhuella.pkl', 'rb') as f: som_model = pickle.load(f) print("OK model") else: print("cargar somhuella.pkl") return False if os.path.exists('matrizMM.txt'): classification_matrix = np.loadtxt('matrizMM.txt') print("OK matrix") else: print("load matrix") return False return True except Exception as e: print(f"error {e}") return False def detect_and_classify_fingerprint(features): global som_model, classification_matrix if not is_valid_fingerprint_features(features): return False, "no fingerprint patterns" if som_model is None or classification_matrix is None: return True, "Fingerprint pattern detected" try: winner = som_model.winner(features) classification_value = classification_matrix[winner] if classification_value == -1: return False, "no pattern" class_names = { 0: "LEFT_LOOP", 1: "RIGHT_LOOP", 2: "WHORL", 3: "ARCO" } class_name = class_names.get(int(classification_value), "UNKNOWN") return True, f"{class_name} fingerprint detected (class {int(classification_value)})" except Exception as e: print(f"Error in SOM class: {e}") return True, "Fingerprint pattern detected (classification error)" load_trained_model() @app.post("/detect_fingerprint/") async def detect_fingerprint(file: UploadFile = File(...)): try: contents = await file.read() image = Image.open(BytesIO(contents)) image_array = np.array(image) features = representativo(image_array) is_fingerprint, details = detect_and_classify_fingerprint(features) return { "fingerprint_detected": is_fingerprint, "details": details } except Exception as e: raise HTTPException(status_code=500, detail=f"error processing image: {str(e)}")