aramnesia77 commited on
Commit
7aa485d
Β·
verified Β·
1 Parent(s): c959fa1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +79 -118
app.py CHANGED
@@ -7,8 +7,8 @@ Two workflows in one page:
7
  Tab 2 "One photo" -> upload a single photo that already has both sides
8
  side-by-side; auto-detect, split, crop, recompose.
9
 
10
- Both sides are scaled so their longest diameters match, so irregular
11
- (ancient) coins look proportional. Output: 1200x600 white .jpg,
12
  named after the uploaded file.
13
  """
14
 
@@ -16,7 +16,8 @@ import os
16
  import tempfile
17
 
18
  import numpy as np
19
- from PIL import Image, ImageOps, ImageFile
 
20
 
21
  ImageFile.LOAD_TRUNCATED_IMAGES = True
22
 
@@ -33,18 +34,6 @@ def get_rembg():
33
 
34
 
35
  # ── shared helpers ────────────────────────────────────────────────
36
- def crop_image_with_padding(img, padding=10):
37
- """Tight crop on non-white pixels, then add uniform padding."""
38
- bbox = ImageOps.invert(img.convert("L")).getbbox()
39
- if not bbox:
40
- return img
41
- l, u, r, d = bbox
42
- return img.crop((
43
- max(l - padding, 0), max(u - padding, 0),
44
- min(r + padding, img.width), min(d + padding, img.height),
45
- ))
46
-
47
-
48
  def bg_diff_mask(img, bg_sample=10, thresh=25):
49
  """Boolean mask of pixels that differ from corner-sampled background."""
50
  arr = np.array(img.convert("RGB"))
@@ -58,101 +47,69 @@ def bg_diff_mask(img, bg_sample=10, thresh=25):
58
  return np.abs(arr - bg).sum(axis=2) > thresh
59
 
60
 
61
- def _convex_hull(points):
62
- """Monotone-chain convex hull of (x, y) tuples."""
63
- pts = sorted(set(points))
64
- if len(pts) <= 2:
65
- return pts
66
-
67
- def cross(o, a, b):
68
- return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
69
-
70
- lower = []
71
- for p in pts:
72
- while len(lower) >= 2 and cross(lower[-2], lower[-1], p) <= 0:
73
- lower.pop()
74
- lower.append(p)
75
- upper = []
76
- for p in reversed(pts):
77
- while len(upper) >= 2 and cross(upper[-2], upper[-1], p) <= 0:
78
- upper.pop()
79
- upper.append(p)
80
- return lower[:-1] + upper[:-1]
81
-
82
-
83
- def longest_diameter(mask):
84
- """Longest point-to-point distance across the mask, any angle."""
85
- try:
86
- ys, xs = np.where(mask)
87
- if xs.size < 2:
88
- return None
89
- order = np.lexsort((xs, ys))
90
- ys_s, xs_s = ys[order], xs[order]
91
- uy, idx = np.unique(ys_s, return_index=True)
92
- xmin = xs_s[idx]
93
- xmax = xs_s[np.append(idx[1:], len(xs_s)) - 1]
94
- points = (list(zip(xmin.tolist(), uy.tolist()))
95
- + list(zip(xmax.tolist(), uy.tolist())))
96
- hull = _convex_hull(points)
97
- hp = np.array(hull, dtype=float)
98
- d2 = ((hp[:, None, :] - hp[None, :, :]) ** 2).sum(-1)
99
- return float(np.sqrt(d2.max()))
100
- except Exception as e:
101
- print(f"longest_diameter failed ({e})")
102
- return None
 
 
 
 
 
 
 
 
 
 
 
 
 
103
 
104
 
105
- def smart_crop(img, pad=10, bg_sample=10, thresh=25):
106
- """Background removal using only Pillow + NumPy (corner-sampled bg)."""
107
- try:
108
- mask = bg_diff_mask(img, bg_sample, thresh)
109
- h, w = mask.shape
110
- ys, xs = np.where(mask)
111
- if xs.size == 0 or ys.size == 0:
112
- return img
113
- l, r = xs.min(), xs.max()
114
- u, d = ys.min(), ys.max()
115
- l = max(l - pad, 0); u = max(u - pad, 0)
116
- r = min(r + pad + 1, w); d = min(d + pad + 1, h)
117
- return img.crop((l, u, r, d))
118
- except Exception as e:
119
- print(f"smart_crop failed ({e}); using original")
120
- return img
121
-
122
-
123
- def find_coin_regions(img, bg_sample=10, thresh=25):
124
- """Detect two coin regions in a single side-by-side photo."""
125
- try:
126
- mask = bg_diff_mask(img, bg_sample, thresh)
127
- h, w = mask.shape
128
- x_projection = np.sum(mask, axis=0)
129
- nonzero_cols = np.where(x_projection > 0)[0]
130
- if len(nonzero_cols) == 0:
131
- return (0, 0, w // 2, h), (w // 2, 0, w, h)
132
- col_start, col_end = nonzero_cols[0], nonzero_cols[-1]
133
- middle_start = col_start + (col_end - col_start) // 4
134
- middle_end = col_start + 3 * (col_end - col_start) // 4
135
- if middle_start < middle_end:
136
- split_point = middle_start + int(np.argmin(x_projection[middle_start:middle_end]))
137
- else:
138
- split_point = (col_start + col_end) // 2
139
-
140
- def bbox_for(cols):
141
- x1, x2 = cols[0], cols[-1]
142
- sub = mask[:, x1:x2 + 1]
143
- yproj = np.where(np.sum(sub, axis=1) > 0)[0]
144
- y1, y2 = (yproj[0], yproj[-1]) if len(yproj) else (0, h)
145
- return (int(x1), int(y1), int(x2) + 1, int(y2) + 1)
146
-
147
- left_cols = nonzero_cols[nonzero_cols <= split_point]
148
- right_cols = nonzero_cols[nonzero_cols > split_point]
149
- left_bbox = bbox_for(left_cols) if len(left_cols) else (0, 0, split_point, h)
150
- right_bbox = bbox_for(right_cols) if len(right_cols) else (split_point, 0, w, h)
151
- return left_bbox, right_bbox
152
- except Exception as e:
153
- print(f"coin detection failed ({e}); simple split")
154
- w, h = img.size
155
- return (0, 0, w // 2, h), (w // 2, 0, w, h)
156
 
157
 
158
  def resize_and_pad(img, target_w=575, target_h=575):
@@ -168,8 +125,8 @@ def resize_and_pad(img, target_w=575, target_h=575):
168
 
169
  def matched_squares(sides, target_diam=535, target_w=575, target_h=575):
170
  """
171
- sides: list of (cropped_img, diameter_px).
172
- Scale both so their longest diameters render at the same pixel size.
173
  """
174
  if any(d is None or d <= 0 for _, d in sides):
175
  return [resize_and_pad(img, target_w, target_h) for img, _ in sides]
@@ -220,10 +177,12 @@ def process_two(front_path, back_path):
220
  im = Image.open(p).convert("RGB")
221
  cut = remove(im) # RGBA with transparency
222
  alpha = np.array(cut)[:, :, 3]
223
- diameter = longest_diameter(alpha > 60)
 
 
224
  white = Image.new("RGBA", cut.size, "WHITE")
225
  white.paste(cut, (0, 0), cut)
226
- cropped = crop_image_with_padding(white.convert("RGB"), padding=10)
227
  sides.append((cropped, diameter))
228
  squares = matched_squares(sides)
229
  return save_jpg(compose(squares[0], squares[1]), front_path)
@@ -234,12 +193,14 @@ def process_one(photo_path):
234
  if photo_path is None:
235
  raise gr.Error("Please upload a photo.")
236
  photo = Image.open(photo_path).convert("RGB")
237
- left_bbox, right_bbox = find_coin_regions(photo)
 
 
 
238
  sides = []
239
- for bbox in (left_bbox, right_bbox):
240
- half = photo.crop(bbox)
241
- diameter = longest_diameter(bg_diff_mask(half))
242
- cropped = smart_crop(half, pad=10)
243
  sides.append((cropped.convert("RGB"), diameter))
244
  squares = matched_squares(sides)
245
  return save_jpg(compose(squares[0], squares[1]), photo_path)
@@ -274,4 +235,4 @@ with gr.Blocks(title="CoinCrop") as demo:
274
  btn1.click(process_one, inputs=photo, outputs=out1)
275
 
276
  if __name__ == "__main__":
277
- demo.launch()
 
7
  Tab 2 "One photo" -> upload a single photo that already has both sides
8
  side-by-side; auto-detect, split, crop, recompose.
9
 
10
+ Both sides are scaled so their cleaned silhouette areas match, so irregular
11
+ (ancient) coins look proportional at any orientation. Output: 1200x600 white .jpg,
12
  named after the uploaded file.
13
  """
14
 
 
16
  import tempfile
17
 
18
  import numpy as np
19
+ from PIL import Image, ImageFile
20
+ from scipy import ndimage
21
 
22
  ImageFile.LOAD_TRUNCATED_IMAGES = True
23
 
 
34
 
35
 
36
  # ── shared helpers ────────────────────────────────────────────────
 
 
 
 
 
 
 
 
 
 
 
 
37
  def bg_diff_mask(img, bg_sample=10, thresh=25):
38
  """Boolean mask of pixels that differ from corner-sampled background."""
39
  arr = np.array(img.convert("RGB"))
 
47
  return np.abs(arr - bg).sum(axis=2) > thresh
48
 
49
 
50
+ def largest_components(mask, count=1):
51
+ """Return the largest cleaned foreground components as boolean masks."""
52
+ mask = np.asarray(mask, dtype=bool)
53
+ if not mask.any():
54
+ return []
55
+
56
+ # Remove isolated JPEG/rembg pixels and close one-pixel breaks in the rim.
57
+ cleaned = ndimage.median_filter(mask.astype(np.uint8), size=3) > 0
58
+ cleaned = ndimage.binary_closing(cleaned, structure=np.ones((3, 3)))
59
+ labels, total = ndimage.label(cleaned, structure=np.ones((3, 3)))
60
+ if total == 0:
61
+ return []
62
+
63
+ areas = np.bincount(labels.ravel())
64
+ areas[0] = 0
65
+ component_ids = np.argsort(areas)[::-1]
66
+ components = []
67
+ min_area = max(9, int(mask.size * 0.0005))
68
+ for component_id in component_ids:
69
+ if component_id == 0 or areas[component_id] < min_area:
70
+ continue
71
+ component = labels == component_id
72
+ # Size the exterior flan, not holes, glare, or missing interior pixels.
73
+ components.append(ndimage.binary_fill_holes(component))
74
+ if len(components) == count:
75
+ break
76
+ return components
77
+
78
+
79
+ def coin_components(mask, count=2):
80
+ """Find the main coin shape(s), falling back to one per image half."""
81
+ components = largest_components(mask, count=count)
82
+ if count != 2 or len(components) == 2:
83
+ return components
84
+
85
+ h, w = mask.shape
86
+ components = []
87
+ for x1, x2 in ((0, w // 2), (w // 2, w)):
88
+ found = largest_components(mask[:, x1:x2], count=1)
89
+ if not found:
90
+ continue
91
+ component = np.zeros((h, w), dtype=bool)
92
+ component[:, x1:x2] = found[0]
93
+ components.append(component)
94
+ return components
95
+
96
+
97
+ def crop_to_mask(img, mask):
98
+ """Tightly crop an image and its already-cleaned mask together."""
99
+ ys, xs = np.where(mask)
100
+ if xs.size == 0:
101
+ return img, mask
102
+ bbox = (int(xs.min()), int(ys.min()), int(xs.max()) + 1, int(ys.max()) + 1)
103
+ l, u, r, d = bbox
104
+ return img.crop(bbox), mask[u:d, l:r]
105
 
106
 
107
+ def equivalent_diameter(mask):
108
+ """Rotation-independent diameter of a circle with the same mask area."""
109
+ area = int(np.count_nonzero(mask))
110
+ if area <= 0:
111
+ return None
112
+ return float(np.sqrt(4.0 * area / np.pi))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
 
114
 
115
  def resize_and_pad(img, target_w=575, target_h=575):
 
125
 
126
  def matched_squares(sides, target_diam=535, target_w=575, target_h=575):
127
  """
128
+ sides: list of (cropped_img, equivalent_diameter_px).
129
+ Scale both to the same rotation-independent silhouette size.
130
  """
131
  if any(d is None or d <= 0 for _, d in sides):
132
  return [resize_and_pad(img, target_w, target_h) for img, _ in sides]
 
177
  im = Image.open(p).convert("RGB")
178
  cut = remove(im) # RGBA with transparency
179
  alpha = np.array(cut)[:, :, 3]
180
+ components = largest_components(alpha > 96, count=1)
181
+ mask = components[0] if components else alpha > 96
182
+ diameter = equivalent_diameter(mask)
183
  white = Image.new("RGBA", cut.size, "WHITE")
184
  white.paste(cut, (0, 0), cut)
185
+ cropped, _ = crop_to_mask(white.convert("RGB"), mask)
186
  sides.append((cropped, diameter))
187
  squares = matched_squares(sides)
188
  return save_jpg(compose(squares[0], squares[1]), front_path)
 
193
  if photo_path is None:
194
  raise gr.Error("Please upload a photo.")
195
  photo = Image.open(photo_path).convert("RGB")
196
+ components = coin_components(bg_diff_mask(photo), count=2)
197
+ if len(components) != 2:
198
+ raise gr.Error("I couldn't reliably find two coin sides in this photo.")
199
+ components.sort(key=lambda mask: float(np.where(mask)[1].mean()))
200
  sides = []
201
+ for mask in components:
202
+ cropped, cropped_mask = crop_to_mask(photo, mask)
203
+ diameter = equivalent_diameter(cropped_mask)
 
204
  sides.append((cropped.convert("RGB"), diameter))
205
  squares = matched_squares(sides)
206
  return save_jpg(compose(squares[0], squares[1]), photo_path)
 
235
  btn1.click(process_one, inputs=photo, outputs=out1)
236
 
237
  if __name__ == "__main__":
238
+ demo.launch()