afdx2 commited on
Commit
7982cea
·
verified ·
1 Parent(s): ca6ae1b

Update server1.py

Browse files
Files changed (1) hide show
  1. server1.py +26 -63
server1.py CHANGED
@@ -2,91 +2,54 @@
2
 
3
  import io
4
  import numpy as np
 
5
  from fastapi import FastAPI, UploadFile, File
6
  from fastapi.responses import JSONResponse
7
  from PIL import Image
8
- import torch
9
-
10
- from transformers import SamModel, SamProcessor
11
 
12
  app = FastAPI(title="Accudoctor Strip Analyzer")
13
 
14
- DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
15
-
16
- # modelo abierto que SI funciona
17
- model = SamModel.from_pretrained("facebook/sam-vit-base").to(DEVICE)
18
- processor = SamProcessor.from_pretrained("facebook/sam-vit-base")
19
-
20
- def dominant_color(pil_img):
21
- img = pil_img.resize((60, 60))
22
- arr = np.array(img).reshape((-1, 3))
23
-
24
- pixels, counts = np.unique(arr, axis=0, return_counts=True)
25
- dom = pixels[counts.argmax()]
26
-
27
- return "#{:02x}{:02x}{:02x}".format(dom[0], dom[1], dom[2])
28
-
29
- def analyze_strip(image_bytes):
30
-
31
- img = Image.open(io.BytesIO(image_bytes))
32
- if img.mode != "RGB":
33
- img = img.convert("RGB")
34
 
35
- inputs = processor(img, return_tensors="pt").to(DEVICE)
36
-
37
- with torch.no_grad():
38
- outputs = model(**inputs)
39
-
40
- masks = processor.post_process_masks(
41
- outputs.pred_masks.cpu(),
42
- inputs["original_sizes"].cpu(),
43
- inputs["reshaped_input_sizes"].cpu()
44
- )[0].numpy()
45
-
46
- blocks = []
47
  np_img = np.array(img)
48
- H, W = np_img.shape[:2]
49
 
50
- for mask in masks:
51
- ys, xs = np.where(mask > 0.5)
52
- if len(xs) == 0:
53
- continue
54
 
55
- x1, x2 = xs.min(), xs.max()
56
- y1, y2 = ys.min(), ys.max()
57
 
58
- w = x2 - x1
59
- h = y2 - y1
60
 
61
- if h / (w + 1e-6) < 3:
62
- continue
63
 
64
- if h < H * 0.04:
65
- continue
66
 
67
- crop = img.crop((x1, y1, x2, y2))
68
- color = dominant_color(crop)
 
69
 
70
- blocks.append({
71
- "bbox": [int(x1), int(y1), int(x2), int(y2)],
72
- "color_hex": color,
73
- "y_center": (y1 + y2) / 2
74
- })
75
-
76
- blocks = sorted(blocks, key=lambda b: b["y_center"])
77
 
78
- for i, b in enumerate(blocks):
79
- b["index"] = i + 1
80
- del b["y_center"]
81
 
82
- return blocks[:11]
83
 
84
  @app.post("/strip/")
85
  async def strip(front: UploadFile = File(...)):
86
  try:
87
  bytes_img = await front.read()
88
- result = analyze_strip(bytes_img)
89
 
90
- return JSONResponse(content={"code": 200, "blocks": result})
 
 
 
 
91
  except Exception as e:
92
  return JSONResponse(content={"code": 500, "error": str(e)})
 
2
 
3
  import io
4
  import numpy as np
5
+ import cv2
6
  from fastapi import FastAPI, UploadFile, File
7
  from fastapi.responses import JSONResponse
8
  from PIL import Image
 
 
 
9
 
10
  app = FastAPI(title="Accudoctor Strip Analyzer")
11
 
12
+ def contar_cuadrados(image_bytes):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
+ img = Image.open(io.BytesIO(image_bytes)).convert("RGB")
 
 
 
 
 
 
 
 
 
 
 
15
  np_img = np.array(img)
 
16
 
17
+ gray = cv2.cvtColor(np_img, cv2.COLOR_RGB2GRAY)
18
+ blur = cv2.GaussianBlur(gray, (5,5), 0)
 
 
19
 
20
+ # bordes
21
+ edges = cv2.Canny(blur, 50, 150)
22
 
23
+ # contornos
24
+ contours, _ = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
25
 
26
+ cuadrados = []
 
27
 
28
+ for cnt in contours:
29
+ approx = cv2.approxPolyDP(cnt, 0.04 * cv2.arcLength(cnt, True), True)
30
 
31
+ # queremos formas cuadradas / rectangulares
32
+ if len(approx) == 4 and cv2.contourArea(cnt) > 200:
33
+ x, y, w, h = cv2.boundingRect(cnt)
34
 
35
+ if w > 10 and h > 10:
36
+ cuadrados.append({
37
+ "bbox": [int(x), int(y), int(x+w), int(y+h)]
38
+ })
 
 
 
39
 
40
+ return cuadrados
 
 
41
 
 
42
 
43
  @app.post("/strip/")
44
  async def strip(front: UploadFile = File(...)):
45
  try:
46
  bytes_img = await front.read()
47
+ cuadrados = contar_cuadrados(bytes_img)
48
 
49
+ return JSONResponse(content={
50
+ "code": 200,
51
+ "count": len(cuadrados),
52
+ "cuadrados": cuadrados
53
+ })
54
  except Exception as e:
55
  return JSONResponse(content={"code": 500, "error": str(e)})