Overglitch commited on
Commit
a9429a6
verified
1 Parent(s): a6787f8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -69
app.py CHANGED
@@ -1,22 +1,51 @@
1
  from fastapi import FastAPI, File, UploadFile, HTTPException
2
- from minisom import MiniSom
3
- import numpy as np
4
  from PIL import Image
 
5
  import pickle
6
 
7
  app = FastAPI()
8
 
9
- # Cargar el modelo SOM entrenado
10
- with open('som.pkl', 'rb') as infile:
11
- som_model = pickle.load(infile)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
- # Etiquetas para los tipos de huellas dactilares
14
- LABELS = {0: 'LL', 1: 'RL', 2: 'WH', 3: 'AR'}
 
 
 
 
 
 
 
15
 
16
- # Funci贸n para procesar y clasificar una imagen de huella dactilar
17
- def classify_fingerprint(image_path):
18
- # Funci贸n para calcular las orientaciones de la imagen
19
- def sobel(I):
20
  m,n = I.shape# I de 254x254
21
  Gx = np.zeros([m-2,n-2],np.float32)# Gx de 252x252
22
  Gy = np.zeros([m-2,n-2],np.float32)# Gy de 252x252
@@ -28,63 +57,36 @@ def classify_fingerprint(image_path):
28
  Gy[j-1,i-1] = sum(sum(I[j-1:j+2,i-1:i+2]*gy))
29
  return Gx,Gy
30
 
31
- def medfilt2(G,d=3):
32
- m,n = G.shape
33
- temp = np.zeros([m+2*(d//2),n+2*(d//2)],np.float32)
34
- salida = np.zeros([m,n],np.float32)
35
- temp[1:m+1,1:n+1] = G
36
- for i in range(1,m):
37
- for j in range(1,n):
38
- A = np.asarray(temp[i-1:i+2,j-1:j+2]).reshape(-1)
39
- salida[i-1,j-1] = np.sort(A)[d+1]
40
- return salida
41
-
42
- def orientacion(patron,w):
43
- Gx,Gy = sobel(patron)# patron de 254x254
44
- Gx = medfilt2(Gx)# Gx de 252x252
45
- Gy = medfilt2(Gy)# Gy de 252x252
46
- m,n = Gx.shape
47
- mOrientaciones = np.zeros([m//w,n//w],np.float32)# de una matriz de 18x18
48
- for i in range(m//w):
49
- for j in range(n//w):
50
- YY = sum(sum(2*Gx[i*w:(i+1)*w,j:j+1]*Gy[i*w:(i+1)*w,j:j+1]))
51
- XX = sum(sum(Gx[i*w:(i+1)*w,j:j+1]**2-Gy[i*w:(i+1)*w,j:j+1]**2))
52
- #YY = sum(sum(2*Gx[i*w:(i+1)*w,0:1]*Gy[i*w:(i+1)*w,0:1]))
53
- #XX = sum(sum(Gx[i*w:(i+1)*w,0:1]**2-Gy[i*w:(i+1)*w,0:1]**2))
54
- mOrientaciones[i,j] = (0.5*math.atan2(YY,XX) + math.pi/2.0)*(180.0/math.pi)
55
- return mOrientaciones
56
-
57
- def representativo(archivo):
58
- im = Image.open(archivo)
59
- m,n = im.size
60
- imarray = np.array(im,np.float32)
61
- patron = imarray[1:m-1,1:n-1]# de 256x256 a 254x254
62
- EE = orientacion(patron,14)# retorna EE de 18x18
63
- return np.asarray(EE).reshape(-1)
64
 
65
- # Obtener el vector representativo de la imagen de huella dactilar
66
- fingerprint_vector = representativo(image_path)
67
-
68
- # Calcular la ubicaci贸n ganadora en el SOM para el vector de huella dactilar
69
- winner_position = som_model.winner(fingerprint_vector)
70
-
71
- # Obtener la etiqueta correspondiente a la ubicaci贸n ganadora
72
- label = LABELS[som_model[winner_position[0], winner_position[1]]]
73
-
74
- return label
 
 
 
 
75
 
76
- # Ruta de predicci贸n
77
- @app.post("/predict/")
78
- async def predict(file: UploadFile = File(...)):
79
- try:
80
- # Guardar la imagen subida
81
- with open("temp_image.tif", "wb") as buffer:
82
- buffer.write(await file.read())
83
-
84
- # Clasificar la imagen de huella dactilar
85
- prediction = classify_fingerprint("temp_image.tif")
86
-
87
- return {"prediction": prediction}
88
-
89
- except Exception as e:
90
- raise HTTPException(status_code=500, detail=str(e))
 
1
  from fastapi import FastAPI, File, UploadFile, HTTPException
 
 
2
  from PIL import Image
3
+ import numpy as np
4
  import pickle
5
 
6
  app = FastAPI()
7
 
8
+ # Cargar el modelo SOM previamente entrenado
9
+ with open("som.pkl", "rb") as tf:
10
+ som = pickle.load(tf)
11
+
12
+ # Funci贸n para realizar la predicci贸n de huellas dactilares
13
+ def predict_fingerprint(image):
14
+ try:
15
+ # Preprocesar la imagen para que coincida con las dimensiones esperadas por el SOM
16
+ processed_image = preprocess_image(image)
17
+ # Obtener la ubicaci贸n del nodo ganador en el SOM
18
+ winner = som.winner(processed_image)
19
+ # Asignar la etiqueta correspondiente a la ubicaci贸n ganadora en el SOM
20
+ fingerprint_type = get_fingerprint_type(winner)
21
+ return fingerprint_type
22
+ except Exception as e:
23
+ raise HTTPException(status_code=500, detail=str(e))
24
+
25
+ def preprocess_image(image):
26
+ # Guardar la imagen en formato TIFF
27
+ image.save("temp_image.tif")
28
+ # Aplicar el mismo preprocesamiento que a arco1.tif
29
+ processed_image = representativo("temp_image.tif")
30
+ return processed_image
31
+
32
+ def get_fingerprint_type(winner):
33
+ # Usar la matriz M del c贸digo SOM para asignar la etiqueta correspondiente
34
+ labels = {0: "LL", 1: "RL", 2: "WH", 3: "AR"} # Mapa de etiquetas
35
+ fingerprint_type = labels[int(M[winner[0], winner[1]])]
36
+ return fingerprint_type
37
 
38
+ @app.post("/predict/")
39
+ async def predict_fingerprint_api(file: UploadFile = File(...)):
40
+ try:
41
+ contents = await file.read()
42
+ image = Image.open(BytesIO(contents))
43
+ fingerprint_type = predict_fingerprint(image)
44
+ return {"prediction": fingerprint_type}
45
+ except Exception as e:
46
+ raise HTTPException(status_code=500, detail=str(e))
47
 
48
+ def sobel(I):
 
 
 
49
  m,n = I.shape# I de 254x254
50
  Gx = np.zeros([m-2,n-2],np.float32)# Gx de 252x252
51
  Gy = np.zeros([m-2,n-2],np.float32)# Gy de 252x252
 
57
  Gy[j-1,i-1] = sum(sum(I[j-1:j+2,i-1:i+2]*gy))
58
  return Gx,Gy
59
 
60
+ def medfilt2(G,d=3):
61
+ m,n = G.shape
62
+ temp = np.zeros([m+2*(d//2),n+2*(d//2)],np.float32)
63
+ salida = np.zeros([m,n],np.float32)
64
+ temp[1:m+1,1:n+1] = G
65
+ for i in range(1,m):
66
+ for j in range(1,n):
67
+ A = np.asarray(temp[i-1:i+2,j-1:j+2]).reshape(-1)
68
+ salida[i-1,j-1] = np.sort(A)[d+1]
69
+ return salida
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
 
71
+ def orientacion(patron,w):
72
+ Gx,Gy = sobel(patron)# patron de 254x254
73
+ Gx = medfilt2(Gx)# Gx de 252x252
74
+ Gy = medfilt2(Gy)# Gy de 252x252
75
+ m,n = Gx.shape
76
+ mOrientaciones = np.zeros([m//w,n//w],np.float32)# de una matriz de 18x18
77
+ for i in range(m//w):
78
+ for j in range(n//w):
79
+ YY = sum(sum(2*Gx[i*w:(i+1)*w,j:j+1]*Gy[i*w:(i+1)*w,j:j+1]))
80
+ XX = sum(sum(Gx[i*w:(i+1)*w,j:j+1]**2-Gy[i*w:(i+1)*w,j:j+1]**2))
81
+ #YY = sum(sum(2*Gx[i*w:(i+1)*w,0:1]*Gy[i*w:(i+1)*w,0:1]))
82
+ #XX = sum(sum(Gx[i*w:(i+1)*w,0:1]**2-Gy[i*w:(i+1)*w,0:1]**2))
83
+ mOrientaciones[i,j] = (0.5*math.atan2(YY,XX) + math.pi/2.0)*(180.0/math.pi)
84
+ return mOrientaciones
85
 
86
+ def representativo(archivo):
87
+ im = Image.open(archivo)
88
+ m,n = im.size
89
+ imarray = np.array(im,np.float32)
90
+ patron = imarray[1:m-1,1:n-1]# de 256x256 a 254x254
91
+ EE = orientacion(patron,14)# retorna EE de 18x18
92
+ return np.asarray(EE).reshape(-1)