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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import os
|
| 3 |
+
import json
|
| 4 |
+
import cv2
|
| 5 |
+
import numpy as np
|
| 6 |
+
from sklearn.cluster import KMeans
|
| 7 |
+
|
| 8 |
+
# ----------------- Config -----------------
|
| 9 |
+
RESIZE_MAX = 1600
|
| 10 |
+
MIN_AREA = 300
|
| 11 |
+
MAX_AREA = 120000
|
| 12 |
+
APPROX_EPS = 0.06
|
| 13 |
+
IOU_NMS = 0.25
|
| 14 |
+
COLOR_CLUSTER_N = 6
|
| 15 |
+
SAT_MIN = 20
|
| 16 |
+
VAL_MIN = 20
|
| 17 |
+
ROW_TOL = 0.75
|
| 18 |
+
AREA_FILTER_THRESH = 0.35
|
| 19 |
+
|
| 20 |
+
# ----------------- Utility Functions -----------------
|
| 21 |
+
def load_and_resize(img_or_path, max_dim=RESIZE_MAX):
|
| 22 |
+
if isinstance(img_or_path, str): # file path
|
| 23 |
+
img = cv2.imread(img_or_path)
|
| 24 |
+
if img is None:
|
| 25 |
+
raise FileNotFoundError(f"Image not found: {img_or_path}")
|
| 26 |
+
elif isinstance(img_or_path, np.ndarray): # already loaded
|
| 27 |
+
img = img_or_path.copy()
|
| 28 |
+
else:
|
| 29 |
+
raise ValueError("Input must be a file path or a numpy array")
|
| 30 |
+
|
| 31 |
+
h, w = img.shape[:2]
|
| 32 |
+
if max(h, w) > max_dim:
|
| 33 |
+
scale = max_dim / float(max(h, w))
|
| 34 |
+
img = cv2.resize(img, (int(w * scale), int(h * scale)), interpolation=cv2.INTER_AREA)
|
| 35 |
+
return img
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def non_max_suppression(boxes, iou_thresh=IOU_NMS):
|
| 39 |
+
if not boxes:
|
| 40 |
+
return []
|
| 41 |
+
arr = np.array(boxes, dtype=float)
|
| 42 |
+
x1 = arr[:, 0]; y1 = arr[:, 1]; x2 = arr[:, 0] + arr[:, 2]; y2 = arr[:, 1] + arr[:, 3]
|
| 43 |
+
areas = (x2 - x1) * (y2 - y1)
|
| 44 |
+
order = areas.argsort()[::-1]
|
| 45 |
+
keep = []
|
| 46 |
+
while order.size > 0:
|
| 47 |
+
i = order[0]
|
| 48 |
+
keep.append(tuple(arr[i].astype(int)))
|
| 49 |
+
xx1 = np.maximum(x1[i], x1[order[1:]])
|
| 50 |
+
yy1 = np.maximum(y1[i], y1[order[1:]])
|
| 51 |
+
xx2 = np.minimum(x2[i], x2[order[1:]])
|
| 52 |
+
yy2 = np.minimum(y2[i], y2[order[1:]])
|
| 53 |
+
w = np.maximum(0.0, xx2 - xx1)
|
| 54 |
+
h = np.maximum(0.0, yy2 - yy1)
|
| 55 |
+
inter = w * h
|
| 56 |
+
union = areas[i] + areas[order[1:]] - inter
|
| 57 |
+
iou = inter / (union + 1e-8)
|
| 58 |
+
inds = np.where(iou <= iou_thresh)[0]
|
| 59 |
+
order = order[inds + 1]
|
| 60 |
+
return keep
|
| 61 |
+
|
| 62 |
+
def color_cluster_masks(img, n_clusters=COLOR_CLUSTER_N):
|
| 63 |
+
lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
|
| 64 |
+
h, w = lab.shape[:2]
|
| 65 |
+
pixels = lab.reshape(-1, 3).astype(np.float32)
|
| 66 |
+
max_samples = 30000
|
| 67 |
+
if pixels.shape[0] > max_samples:
|
| 68 |
+
rng = np.random.default_rng(0)
|
| 69 |
+
sample_idx = rng.choice(pixels.shape[0], max_samples, replace=False)
|
| 70 |
+
sample = pixels[sample_idx]
|
| 71 |
+
else:
|
| 72 |
+
sample = pixels
|
| 73 |
+
n_clusters = min(n_clusters, max(1, sample.shape[0]))
|
| 74 |
+
kmeans = KMeans(n_clusters=n_clusters, random_state=0, n_init=8).fit(sample)
|
| 75 |
+
centers = kmeans.cluster_centers_
|
| 76 |
+
centers_f = centers.astype(np.float32).reshape(1, 1, n_clusters, 3)
|
| 77 |
+
lab_f = lab.astype(np.float32).reshape(h, w, 1, 3)
|
| 78 |
+
diff = lab_f - centers_f
|
| 79 |
+
dist = np.linalg.norm(diff, axis=3)
|
| 80 |
+
labels = np.argmin(dist, axis=2).astype(np.int32)
|
| 81 |
+
masks = [(labels == k).astype(np.uint8) * 255 for k in range(n_clusters)]
|
| 82 |
+
return masks
|
| 83 |
+
|
| 84 |
+
def refine_mask_by_hsv(mask, img, sat_min=SAT_MIN, val_min=VAL_MIN):
|
| 85 |
+
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
|
| 86 |
+
s = hsv[:, :, 1]; v = hsv[:, :, 2]
|
| 87 |
+
sv_mask = (s >= sat_min) & (v >= val_min)
|
| 88 |
+
refined = mask.copy()
|
| 89 |
+
refined[~sv_mask] = 0
|
| 90 |
+
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
|
| 91 |
+
refined = cv2.morphologyEx(refined, cv2.MORPH_CLOSE, kernel, iterations=2)
|
| 92 |
+
refined = cv2.morphologyEx(refined, cv2.MORPH_OPEN, kernel, iterations=1)
|
| 93 |
+
return refined
|
| 94 |
+
|
| 95 |
+
def contours_from_mask(mask):
|
| 96 |
+
cnts, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
| 97 |
+
rects = []
|
| 98 |
+
for c in cnts:
|
| 99 |
+
area = cv2.contourArea(c)
|
| 100 |
+
if area < MIN_AREA or area > MAX_AREA:
|
| 101 |
+
continue
|
| 102 |
+
peri = cv2.arcLength(c, True)
|
| 103 |
+
approx = cv2.approxPolyDP(c, APPROX_EPS * peri, True)
|
| 104 |
+
x, y, w, h = cv2.boundingRect(approx)
|
| 105 |
+
if h == 0 or w == 0:
|
| 106 |
+
continue
|
| 107 |
+
ar = w / float(h)
|
| 108 |
+
if 0.12 < ar < 8:
|
| 109 |
+
rects.append((x, y, w, h))
|
| 110 |
+
return rects
|
| 111 |
+
|
| 112 |
+
def mser_candidates(img):
|
| 113 |
+
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
| 114 |
+
mser = cv2.MSER_create()
|
| 115 |
+
mser.setMinArea(60)
|
| 116 |
+
mser.setMaxArea(MAX_AREA)
|
| 117 |
+
regions, _ = mser.detectRegions(gray)
|
| 118 |
+
rects = []
|
| 119 |
+
for r in regions:
|
| 120 |
+
x, y, w, h = cv2.boundingRect(r.reshape(-1, 1, 2))
|
| 121 |
+
area = w * h
|
| 122 |
+
if area < MIN_AREA or area > MAX_AREA:
|
| 123 |
+
continue
|
| 124 |
+
ar = w / float(h) if h > 0 else 0
|
| 125 |
+
if 0.25 < ar < 4.0:
|
| 126 |
+
rects.append((x, y, w, h))
|
| 127 |
+
return rects
|
| 128 |
+
|
| 129 |
+
def collect_candidates(img):
|
| 130 |
+
masks = color_cluster_masks(img, n_clusters=COLOR_CLUSTER_N)
|
| 131 |
+
cluster_rects = []
|
| 132 |
+
for m in masks:
|
| 133 |
+
refined = refine_mask_by_hsv(m, img)
|
| 134 |
+
rects = contours_from_mask(refined)
|
| 135 |
+
cluster_rects.extend(rects)
|
| 136 |
+
mser_rects = mser_candidates(img)
|
| 137 |
+
all_rects = cluster_rects + mser_rects
|
| 138 |
+
nms = non_max_suppression(all_rects, IOU_NMS)
|
| 139 |
+
return nms
|
| 140 |
+
|
| 141 |
+
def filter_by_area(rects):
|
| 142 |
+
if not rects:
|
| 143 |
+
return rects
|
| 144 |
+
areas = np.array([w * h for (_, _, w, h) in rects], dtype=float)
|
| 145 |
+
avg_area = np.mean(areas)
|
| 146 |
+
lower = avg_area * (1.0 - AREA_FILTER_THRESH)
|
| 147 |
+
upper = avg_area * (1.0 + AREA_FILTER_THRESH)
|
| 148 |
+
return [r for r, a in zip(rects, areas) if lower <= a <= upper]
|
| 149 |
+
|
| 150 |
+
def group_rows(rects, tol=ROW_TOL):
|
| 151 |
+
if not rects:
|
| 152 |
+
return []
|
| 153 |
+
rects = sorted(rects, key=lambda b: b[1])
|
| 154 |
+
rows = [[rects[0]]]
|
| 155 |
+
for r in rects[1:]:
|
| 156 |
+
prev = rows[-1][-1]
|
| 157 |
+
y1 = prev[1] + prev[3] / 2.0
|
| 158 |
+
y2 = r[1] + r[3] / 2.0
|
| 159 |
+
avg_h = (prev[3] + r[3]) / 2.0
|
| 160 |
+
if abs(y1 - y2) <= tol * avg_h:
|
| 161 |
+
rows[-1].append(r)
|
| 162 |
+
else:
|
| 163 |
+
rows.append([r])
|
| 164 |
+
return rows
|
| 165 |
+
|
| 166 |
+
def group_columns(rects, tol=ROW_TOL):
|
| 167 |
+
if not rects:
|
| 168 |
+
return []
|
| 169 |
+
rects = sorted(rects, key=lambda b: b[0])
|
| 170 |
+
cols = [[rects[0]]]
|
| 171 |
+
for r in rects[1:]:
|
| 172 |
+
prev = cols[-1][-1]
|
| 173 |
+
x1 = prev[0] + prev[2] / 2.0
|
| 174 |
+
x2 = r[0] + r[2] / 2.0
|
| 175 |
+
avg_w = (prev[2] + r[2]) / 2.0
|
| 176 |
+
if abs(x1 - x2) <= tol * avg_w:
|
| 177 |
+
cols[-1].append(r)
|
| 178 |
+
else:
|
| 179 |
+
cols.append([r])
|
| 180 |
+
return cols
|
| 181 |
+
|
| 182 |
+
def fill_missing_boxes(img, reference_rects, row_tol=ROW_TOL, col_tol=ROW_TOL):
|
| 183 |
+
if not reference_rects:
|
| 184 |
+
return []
|
| 185 |
+
areas = [w * h for (_, _, w, h) in reference_rects]
|
| 186 |
+
rounded_areas = [int(a // 100) * 100 for a in areas]
|
| 187 |
+
unique, counts = np.unique(rounded_areas, return_counts=True)
|
| 188 |
+
most_common_area = unique[np.argmax(counts)]
|
| 189 |
+
closest_box = min(reference_rects, key=lambda r: abs((r[2]*r[3]) - most_common_area))
|
| 190 |
+
avg_w, avg_h = int(closest_box[2]), int(closest_box[3])
|
| 191 |
+
rows = group_rows(reference_rects, tol=row_tol)
|
| 192 |
+
cols = group_columns(reference_rects, tol=col_tol)
|
| 193 |
+
if not rows or not cols:
|
| 194 |
+
return []
|
| 195 |
+
row_ys = [int(np.mean([y+h/2.0 for (x,y,w,h) in r])) for r in rows]
|
| 196 |
+
col_xs = [int(np.mean([x+w/2.0 for (x,y,w,h) in c])) for c in cols]
|
| 197 |
+
centers_existing = [(int(x+w/2), int(y+h/2)) for (x,y,w,h) in reference_rects]
|
| 198 |
+
synth_boxes = []
|
| 199 |
+
tol_x = avg_w * 0.45
|
| 200 |
+
tol_y = avg_h * 0.45
|
| 201 |
+
for ry in row_ys:
|
| 202 |
+
for cx in col_xs:
|
| 203 |
+
exists = any(abs(ex[0]-cx)<tol_x and abs(ex[1]-ry)<tol_y for ex in centers_existing)
|
| 204 |
+
if not exists:
|
| 205 |
+
x = int(cx - avg_w/2)
|
| 206 |
+
y = int(ry - avg_h/2)
|
| 207 |
+
synth_boxes.append({'x': x, 'y': y, 'w': avg_w, 'h': avg_h, 'synthetic': True})
|
| 208 |
+
return synth_boxes
|
| 209 |
+
|
| 210 |
+
def split_left_right(rects, img, left_frac):
|
| 211 |
+
if not rects:
|
| 212 |
+
return [], []
|
| 213 |
+
h, w = img.shape[:2]
|
| 214 |
+
left = [r for r in rects if (r[0] + r[2]/2.0) < left_frac * w]
|
| 215 |
+
right = [r for r in rects if r not in left]
|
| 216 |
+
return sorted(left, key=lambda b: b[1]), sorted(right, key=lambda b: (b[1], b[0]))
|
| 217 |
+
|
| 218 |
+
def match_left_to_right(left_boxes, right_boxes):
|
| 219 |
+
mapping = {}
|
| 220 |
+
for i, tb in enumerate(left_boxes):
|
| 221 |
+
key = f"test_box_{i+1}"
|
| 222 |
+
tx, ty, tw, th = tb
|
| 223 |
+
tcy = ty + th/2.0
|
| 224 |
+
mapping[key] = {"test_box": [int(tx), int(ty), int(tw), int(th)], "matched_refs": []}
|
| 225 |
+
for rb in right_boxes:
|
| 226 |
+
x, y, w, h = rb['x'], rb['y'], rb['w'], rb['h']
|
| 227 |
+
cy = y + h/2.0
|
| 228 |
+
avg_h = (th + h)/2.0
|
| 229 |
+
if abs(tcy - cy) <= ROW_TOL * avg_h:
|
| 230 |
+
mapping[key]["matched_refs"].append({k:int(v) for k,v in rb.items() if k!="synthetic"})
|
| 231 |
+
return mapping
|
| 232 |
+
|
| 233 |
+
def visualize(img, left, right, mapping):
|
| 234 |
+
vis = img.copy()
|
| 235 |
+
for i, tb in enumerate(left):
|
| 236 |
+
x,y,w,h = tb
|
| 237 |
+
cv2.rectangle(vis, (x,y), (x+w,y+h), (255,0,0), 2)
|
| 238 |
+
cv2.putText(vis, f"T{i+1}", (x,y-5), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (255,0,0), 1)
|
| 239 |
+
for j, rb in enumerate(right):
|
| 240 |
+
color = (0,180,0) if rb.get('synthetic', False) else (0,255,0)
|
| 241 |
+
cv2.rectangle(vis, (rb['x'], rb['y']), (rb['x']+rb['w'], rb['y']+rb['h']), color, 1)
|
| 242 |
+
cv2.putText(vis, f"R{j+1}", (rb['x'], rb['y']-6), cv2.FONT_HERSHEY_SIMPLEX, 0.4, color, 1)
|
| 243 |
+
for i, tb in enumerate(left):
|
| 244 |
+
key = f"test_box_{i+1}"
|
| 245 |
+
tx, ty, tw, th = tb
|
| 246 |
+
tcx, tcy = int(tx + tw/2), int(ty + th/2)
|
| 247 |
+
for rb in mapping[key]["matched_refs"]:
|
| 248 |
+
rcx = int(rb["x"] + rb["w"]/2)
|
| 249 |
+
rcy = int(rb["y"] + rb["h"]/2)
|
| 250 |
+
cv2.line(vis, (tcx,tcy), (rcx,rcy), (0,0,255), 1)
|
| 251 |
+
vis_rgb = cv2.cvtColor(vis, cv2.COLOR_BGR2RGB)
|
| 252 |
+
return vis_rgb
|
| 253 |
+
def keep_one_box_per_row(rects, reference_rects=None, row_tol=ROW_TOL):
|
| 254 |
+
"""
|
| 255 |
+
Keep only one representative box per row.
|
| 256 |
+
Selection score for each box in a row is based on:
|
| 257 |
+
- closeness of box area to expected (dominant) area
|
| 258 |
+
- closeness of aspect ratio (w/h) to expected aspect ratio
|
| 259 |
+
- small penalty for very skinny or very flat boxes
|
| 260 |
+
reference_rects: list of all detected rects (used to compute expected area/aspect ratio).
|
| 261 |
+
"""
|
| 262 |
+
if not rects:
|
| 263 |
+
return rects
|
| 264 |
+
|
| 265 |
+
# Compute expected statistics from reference_rects (fallback to rects if None)
|
| 266 |
+
ref = reference_rects if (reference_rects and len(reference_rects) > 0) else rects
|
| 267 |
+
areas_ref = np.array([w * h for (_, _, w, h) in ref], dtype=float)
|
| 268 |
+
ars_ref = np.array([w / float(h) for (_, _, w, h) in ref], dtype=float)
|
| 269 |
+
|
| 270 |
+
# Robust central estimates (median)
|
| 271 |
+
expected_area = float(np.median(areas_ref))
|
| 272 |
+
expected_ar = float(np.median(ars_ref))
|
| 273 |
+
|
| 274 |
+
# Safety floor
|
| 275 |
+
if expected_area <= 0:
|
| 276 |
+
expected_area = np.mean(areas_ref) if len(areas_ref) else 1.0
|
| 277 |
+
if expected_ar <= 0:
|
| 278 |
+
expected_ar = 1.0
|
| 279 |
+
|
| 280 |
+
# Group rectangles into rows by vertical center proximity
|
| 281 |
+
rects_sorted = sorted(rects, key=lambda b: b[1])
|
| 282 |
+
rows = [[rects_sorted[0]]]
|
| 283 |
+
for r in rects_sorted[1:]:
|
| 284 |
+
y_center = r[1] + r[3] / 2.0
|
| 285 |
+
last = rows[-1][-1]
|
| 286 |
+
last_center = last[1] + last[3] / 2.0
|
| 287 |
+
avg_h = (r[3] + last[3]) / 2.0
|
| 288 |
+
if abs(y_center - last_center) <= row_tol * avg_h:
|
| 289 |
+
rows[-1].append(r)
|
| 290 |
+
else:
|
| 291 |
+
rows.append([r])
|
| 292 |
+
|
| 293 |
+
kept = []
|
| 294 |
+
for group in rows:
|
| 295 |
+
if len(group) == 1:
|
| 296 |
+
kept.append(group[0])
|
| 297 |
+
continue
|
| 298 |
+
|
| 299 |
+
# Compute a score for each candidate; lower is better
|
| 300 |
+
scores = []
|
| 301 |
+
for (x, y, w, h) in group:
|
| 302 |
+
area = w * h
|
| 303 |
+
ar = w / float(h) if h > 0 else 0.0
|
| 304 |
+
|
| 305 |
+
# area closeness: use log-ratio so relative differences are symmetric
|
| 306 |
+
area_score = abs(np.log((area + 1e-6) / (expected_area + 1e-6)))
|
| 307 |
+
|
| 308 |
+
# aspect ratio closeness (normalized)
|
| 309 |
+
ar_score = abs(ar - expected_ar) / (expected_ar + 1e-6)
|
| 310 |
+
|
| 311 |
+
# penalty for extremely skinny or extremely tall flat boxes
|
| 312 |
+
penalty = 0.0
|
| 313 |
+
if ar < 0.25: # very skinny tall
|
| 314 |
+
penalty += 1.0
|
| 315 |
+
if ar > 4.0: # very wide flat (unlikely in left column but defensive)
|
| 316 |
+
penalty += 0.6
|
| 317 |
+
|
| 318 |
+
# small preference toward boxes centered horizontally in the row (optional)
|
| 319 |
+
# compute row median x center
|
| 320 |
+
group_centers_x = [g[0] + g[2]/2.0 for g in group]
|
| 321 |
+
median_cx = float(np.median(group_centers_x))
|
| 322 |
+
cx = x + w/2.0
|
| 323 |
+
center_score = abs(cx - median_cx) / (expected_ar * np.sqrt(expected_area) + 1.0)
|
| 324 |
+
|
| 325 |
+
# combine scores with weights (tune if needed)
|
| 326 |
+
score = (2.0 * area_score) + (1.2 * ar_score) + (0.5 * center_score) + penalty
|
| 327 |
+
scores.append(score)
|
| 328 |
+
|
| 329 |
+
best_idx = int(np.argmin(scores))
|
| 330 |
+
best_box = group[best_idx]
|
| 331 |
+
kept.append(best_box)
|
| 332 |
+
|
| 333 |
+
# optional: sort kept boxes by y
|
| 334 |
+
kept = sorted(kept, key=lambda b: b[1])
|
| 335 |
+
print(f"Kept {len(kept)} boxes (one per row) out of {len(rects)} candidates.")
|
| 336 |
+
return kept
|
| 337 |
+
|
| 338 |
+
# ----------------- Pipeline -----------------
|
| 339 |
+
def process_image(image, left_frac):
|
| 340 |
+
img_bgr = load_and_resize(image)
|
| 341 |
+
rects = collect_candidates(img_bgr)
|
| 342 |
+
rects = filter_by_area(rects)
|
| 343 |
+
synth = fill_missing_boxes(img_bgr, rects)
|
| 344 |
+
all_boxes = rects + [(b['x'], b['y'], b['w'], b['h']) for b in synth]
|
| 345 |
+
left, right = split_left_right(all_boxes, img_bgr, left_frac)
|
| 346 |
+
left = keep_one_box_per_row(left)
|
| 347 |
+
right_with_synth = [{'x':x,'y':y,'w':w,'h':h,'synthetic':False} for (x,y,w,h) in right] + synth
|
| 348 |
+
mapping = match_left_to_right(left, right_with_synth)
|
| 349 |
+
result = visualize(img_bgr, left, right_with_synth, mapping)
|
| 350 |
+
return result
|
| 351 |
+
|
| 352 |
+
# ----------------- Gradio App -----------------
|
| 353 |
+
title = "Grid Detection & Matching Viewer"
|
| 354 |
+
description = "Upload an image, adjust the Left/Right threshold, and view final matching visualization."
|
| 355 |
+
|
| 356 |
+
iface = gr.Interface(
|
| 357 |
+
fn=process_image,
|
| 358 |
+
inputs=[
|
| 359 |
+
gr.Image(type="numpy", label="Upload Image"),
|
| 360 |
+
gr.Slider(0.1, 0.9, value=0.35, step=0.01, label="Left Fraction Threshold (LEFT_FRAC_FALLBACK)")
|
| 361 |
+
],
|
| 362 |
+
outputs=gr.Image(label="Matched Output", type="numpy"),
|
| 363 |
+
title=title,
|
| 364 |
+
description=description,
|
| 365 |
+
examples=None
|
| 366 |
+
)
|
| 367 |
+
|
| 368 |
+
if __name__ == "__main__":
|
| 369 |
+
iface.launch()
|
requirements.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio
|
| 2 |
+
opencv-python-headless
|
| 3 |
+
numpy
|
| 4 |
+
scikit-learn
|