Bing Yan commited on
Commit
ba72d0f
·
1 Parent(s): 8e295bb

Per-image axis bounds and current unit detection

Browse files

- Fix OCR: handle tilde (~) as minus sign in tick label parsing
- Add y-axis unit detection: rotate left margin 90° and OCR to read
the rotated axis label (e.g. "I (µA)" vs "I (mA)")
- Handle OCR misreading µ as M (uppercase MA → µA)
- auto_detect_axis_bounds now returns per-image bounds with y_unit
- Add current unit dropdown (auto/µA/mA/A/nA) to image analysis UI
- Use median E0 across all images (matching CSV path behavior)
- Two-pass processing: digitize all images first, then nondimensionalize
with shared E0

Each uploaded image now gets independent axis range detection and
unit identification, so images with different current scales (e.g.
µA at slow scan rates, mA at fast) are handled correctly.

Made-with: Cursor

Files changed (2) hide show
  1. app.py +59 -28
  2. digitizer.py +67 -6
app.py CHANGED
@@ -145,8 +145,30 @@ def analyze_cv(files, scan_rates_text, E0_V, T_K, A_cm2,
145
  return _run_ec_analysis(potentials, fluxes, sigmas_list, n_samples, preproc_text=preproc_info)
146
 
147
 
148
- def analyze_cv_image(files, scan_rate_text, E0_V, threshold, n_samples,
149
- x_min, x_max, y_min, y_max):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
150
  """Analyze CV from uploaded plot images (one per scan rate).
151
 
152
  Extracts CV curves via image digitization, then nondimensionalizes
@@ -179,21 +201,15 @@ def analyze_cv_image(files, scan_rate_text, E0_V, threshold, n_samples,
179
  v is not None and v != 0 for v in [x_min, x_max, y_min, y_max]
180
  )
181
 
182
- potentials, fluxes, sigmas_list = [], [], []
183
- preproc_parts = []
184
-
185
  D = 1e-5
186
  T = 298.15
187
  A = 0.0707
188
  C_molcm3 = 1e-6
189
  n = 1
190
- e0 = None
191
- e0_source = None
192
-
193
- if E0_V is not None and E0_V != 0:
194
- e0 = float(E0_V)
195
- e0_source = "user"
196
 
 
 
 
197
  for idx, f in enumerate(files):
198
  img_arr = np.array(PILImage.open(f.name).convert("RGB"))
199
  v_Vs = scan_rates[idx]
@@ -203,7 +219,6 @@ def analyze_cv_image(files, scan_rate_text, E0_V, threshold, n_samples,
203
  "x_min": float(x_min), "x_max": float(x_max),
204
  "y_min": float(y_min), "y_max": float(y_max),
205
  }
206
- bounds_source = "user"
207
  else:
208
  bounds = auto_detect_axis_bounds(img_arr)
209
  if bounds is None:
@@ -211,7 +226,6 @@ def analyze_cv_image(files, scan_rate_text, E0_V, threshold, n_samples,
211
  f"Could not auto-detect axis bounds for image {idx + 1}. "
212
  "Please enter E min, E max, I min, I max under "
213
  "'Axis overrides'.")
214
- bounds_source = "auto"
215
 
216
  try:
217
  E_V, I_raw = digitize_plot(
@@ -222,21 +236,31 @@ def analyze_cv_image(files, scan_rate_text, E0_V, threshold, n_samples,
222
  except Exception as exc:
223
  return _ec_error(f"Digitization failed for image {idx + 1}: {exc}")
224
 
225
- i_max = np.max(np.abs(I_raw))
226
- if i_max > 100:
227
- i_A = I_raw * 1e-6
228
- i_unit = "µA"
229
- elif i_max > 0.1:
230
- i_A = I_raw * 1e-3
231
- i_unit = "mA"
232
  else:
233
- i_A = I_raw
234
- i_unit = "A"
 
 
 
 
 
235
 
236
- if e0 is None:
237
- e0 = float(estimate_E0(E_V, i_A))
238
- e0_source = "auto"
 
 
 
 
239
 
 
 
 
 
240
  theta, flux, sigma = nondimensionalize_cv(
241
  E_V, i_A, v_Vs, e0, T, A, C_molcm3, D, n
242
  )
@@ -246,14 +270,14 @@ def analyze_cv_image(files, scan_rate_text, E0_V, threshold, n_samples,
246
 
247
  preproc_parts.append(
248
  f"{v_Vs*1000:.1f} mV/s (σ={sigma:.2f}, "
249
- f"bounds {bounds_source}: E=[{bounds['x_min']:.3f}, {bounds['x_max']:.3f}] V, "
250
  f"I=[{bounds['y_min']:.2f}, {bounds['y_max']:.2f}] {i_unit})"
251
  )
252
 
253
  preproc_info = f"**Preprocessing ({len(files)} image{'s' if len(files) > 1 else ''}):** "
254
  preproc_info += "; ".join(preproc_parts) + ". "
255
  if e0_source == "auto":
256
- preproc_info += f"E₀ auto-estimated as {e0:.4f} V."
257
  else:
258
  preproc_info += f"E₀ = {e0:.4f} V (user-provided)."
259
 
@@ -755,6 +779,12 @@ def build_app():
755
  0, 255, value=0, step=1,
756
  label="Binarization threshold (0 = auto)",
757
  )
 
 
 
 
 
 
758
  with gr.Accordion("Axis overrides", open=False):
759
  gr.Markdown(
760
  "Leave at 0 to auto-detect from each image. "
@@ -786,7 +816,8 @@ def build_app():
786
  analyze_cv_image,
787
  inputs=[
788
  cv_img_files, cv_img_scan_rate, cv_img_E0,
789
- cv_img_threshold, cv_img_nsamples,
 
790
  cv_img_xmin, cv_img_xmax,
791
  cv_img_ymin, cv_img_ymax,
792
  ],
 
145
  return _run_ec_analysis(potentials, fluxes, sigmas_list, n_samples, preproc_text=preproc_info)
146
 
147
 
148
+ _CURRENT_UNIT_SCALES = {
149
+ "µA": 1e-6,
150
+ "mA": 1e-3,
151
+ "A": 1.0,
152
+ "nA": 1e-9,
153
+ }
154
+
155
+
156
+ def _guess_current_unit(i_values):
157
+ """Guess the current unit from the magnitude of digitized values."""
158
+ i_max = np.max(np.abs(i_values))
159
+ if i_max > 1e3:
160
+ return "nA"
161
+ if i_max > 100:
162
+ return "µA"
163
+ if i_max > 0.1:
164
+ return "µA"
165
+ if i_max > 1e-4:
166
+ return "mA"
167
+ return "A"
168
+
169
+
170
+ def analyze_cv_image(files, scan_rate_text, E0_V, threshold, current_unit,
171
+ n_samples, x_min, x_max, y_min, y_max):
172
  """Analyze CV from uploaded plot images (one per scan rate).
173
 
174
  Extracts CV curves via image digitization, then nondimensionalizes
 
201
  v is not None and v != 0 for v in [x_min, x_max, y_min, y_max]
202
  )
203
 
 
 
 
204
  D = 1e-5
205
  T = 298.15
206
  A = 0.0707
207
  C_molcm3 = 1e-6
208
  n = 1
 
 
 
 
 
 
209
 
210
+ # First pass: digitize all images and estimate E0 per image
211
+ image_data = []
212
+ e0_estimates = []
213
  for idx, f in enumerate(files):
214
  img_arr = np.array(PILImage.open(f.name).convert("RGB"))
215
  v_Vs = scan_rates[idx]
 
219
  "x_min": float(x_min), "x_max": float(x_max),
220
  "y_min": float(y_min), "y_max": float(y_max),
221
  }
 
222
  else:
223
  bounds = auto_detect_axis_bounds(img_arr)
224
  if bounds is None:
 
226
  f"Could not auto-detect axis bounds for image {idx + 1}. "
227
  "Please enter E min, E max, I min, I max under "
228
  "'Axis overrides'.")
 
229
 
230
  try:
231
  E_V, I_raw = digitize_plot(
 
236
  except Exception as exc:
237
  return _ec_error(f"Digitization failed for image {idx + 1}: {exc}")
238
 
239
+ if current_unit and current_unit != "auto":
240
+ i_unit = current_unit
241
+ elif "y_unit" in bounds:
242
+ i_unit = bounds["y_unit"]
 
 
 
243
  else:
244
+ i_unit = _guess_current_unit(I_raw)
245
+
246
+ i_scale = _CURRENT_UNIT_SCALES.get(i_unit, 1e-6)
247
+ i_A = I_raw * i_scale
248
+
249
+ e0_estimates.append(float(estimate_E0(E_V, i_A)))
250
+ image_data.append((E_V, i_A, v_Vs, i_unit, bounds))
251
 
252
+ # Determine E0: user-provided or median of per-image estimates
253
+ if E0_V is not None and E0_V != 0:
254
+ e0 = float(E0_V)
255
+ e0_source = "user"
256
+ else:
257
+ e0 = float(np.median(e0_estimates))
258
+ e0_source = "auto"
259
 
260
+ # Second pass: nondimensionalize with shared E0
261
+ potentials, fluxes, sigmas_list = [], [], []
262
+ preproc_parts = []
263
+ for E_V, i_A, v_Vs, i_unit, bounds in image_data:
264
  theta, flux, sigma = nondimensionalize_cv(
265
  E_V, i_A, v_Vs, e0, T, A, C_molcm3, D, n
266
  )
 
270
 
271
  preproc_parts.append(
272
  f"{v_Vs*1000:.1f} mV/s (σ={sigma:.2f}, "
273
+ f"E=[{bounds['x_min']:.3f}, {bounds['x_max']:.3f}] V, "
274
  f"I=[{bounds['y_min']:.2f}, {bounds['y_max']:.2f}] {i_unit})"
275
  )
276
 
277
  preproc_info = f"**Preprocessing ({len(files)} image{'s' if len(files) > 1 else ''}):** "
278
  preproc_info += "; ".join(preproc_parts) + ". "
279
  if e0_source == "auto":
280
+ preproc_info += f"E₀ auto-estimated as {e0:.4f} V from peak midpoints."
281
  else:
282
  preproc_info += f"E₀ = {e0:.4f} V (user-provided)."
283
 
 
779
  0, 255, value=0, step=1,
780
  label="Binarization threshold (0 = auto)",
781
  )
782
+ cv_img_current_unit = gr.Dropdown(
783
+ label="Current unit on y-axis",
784
+ choices=["auto", "µA", "mA", "A", "nA"],
785
+ value="auto",
786
+ info="Select the unit shown on the y-axis of your plot",
787
+ )
788
  with gr.Accordion("Axis overrides", open=False):
789
  gr.Markdown(
790
  "Leave at 0 to auto-detect from each image. "
 
816
  analyze_cv_image,
817
  inputs=[
818
  cv_img_files, cv_img_scan_rate, cv_img_E0,
819
+ cv_img_threshold, cv_img_current_unit,
820
+ cv_img_nsamples,
821
  cv_img_xmin, cv_img_xmax,
822
  cv_img_ymin, cv_img_ymax,
823
  ],
digitizer.py CHANGED
@@ -11,17 +11,21 @@ import numpy as np
11
 
12
 
13
  def auto_detect_axis_bounds(image_array):
14
- """Detect axis bounds from a plot image using OCR.
15
 
16
  Reads numeric tick labels, clusters them by position into x-axis
17
  (similar y-coordinate, bottom half) and y-axis (similar x-coordinate,
18
  left half), and returns the inferred data ranges.
19
 
 
 
 
20
  Args:
21
  image_array: numpy array (H, W, 3) RGB image
22
 
23
  Returns:
24
  dict with keys 'x_min', 'x_max', 'y_min', 'y_max' (all float),
 
25
  or None if detection fails.
26
  """
27
  try:
@@ -38,16 +42,19 @@ def auto_detect_axis_bounds(image_array):
38
  results = reader.readtext(image_array, detail=1)
39
 
40
  _NUM_RE = re.compile(
41
- r"^[−\-–]?\d+\.?\d*(?:[eE][+\-]?\d+)?$"
42
  )
43
 
44
  detections = []
 
45
  for bbox, text, conf in results:
46
- text = text.strip().replace(" ", "").replace("−", "-").replace("–", "-")
47
- if not _NUM_RE.match(text):
 
 
48
  continue
49
  try:
50
- val = float(text)
51
  except ValueError:
52
  continue
53
  if conf < 0.2:
@@ -69,12 +76,66 @@ def auto_detect_axis_bounds(image_array):
69
  if len(x_vals) < 2 or len(y_vals) < 2:
70
  return None
71
 
72
- return {
 
 
 
73
  "x_min": float(min(x_vals)),
74
  "x_max": float(max(x_vals)),
75
  "y_min": float(min(y_vals)),
76
  "y_max": float(max(y_vals)),
77
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78
 
79
 
80
  def _extract_axis_values(candidates, axis="x"):
 
11
 
12
 
13
  def auto_detect_axis_bounds(image_array):
14
+ """Detect axis bounds and current unit from a plot image using OCR.
15
 
16
  Reads numeric tick labels, clusters them by position into x-axis
17
  (similar y-coordinate, bottom half) and y-axis (similar x-coordinate,
18
  left half), and returns the inferred data ranges.
19
 
20
+ Also attempts to detect the y-axis unit label by OCR-ing a rotated
21
+ crop of the left margin.
22
+
23
  Args:
24
  image_array: numpy array (H, W, 3) RGB image
25
 
26
  Returns:
27
  dict with keys 'x_min', 'x_max', 'y_min', 'y_max' (all float),
28
+ and optionally 'y_unit' (str, e.g. 'µA', 'mA', 'A'),
29
  or None if detection fails.
30
  """
31
  try:
 
42
  results = reader.readtext(image_array, detail=1)
43
 
44
  _NUM_RE = re.compile(
45
+ r"^[−\-–~]?\d+\.?\d*(?:[eE][+\-]?\d+)?$"
46
  )
47
 
48
  detections = []
49
+ all_texts = []
50
  for bbox, text, conf in results:
51
+ all_texts.append(text.strip())
52
+ cleaned = (text.strip().replace(" ", "")
53
+ .replace("−", "-").replace("–", "-").replace("~", "-"))
54
+ if not _NUM_RE.match(cleaned):
55
  continue
56
  try:
57
+ val = float(cleaned)
58
  except ValueError:
59
  continue
60
  if conf < 0.2:
 
76
  if len(x_vals) < 2 or len(y_vals) < 2:
77
  return None
78
 
79
+ # Detect y-axis unit from all OCR text and from rotated left margin
80
+ y_unit = _detect_current_unit(image_array, reader, all_texts)
81
+
82
+ result = {
83
  "x_min": float(min(x_vals)),
84
  "x_max": float(max(x_vals)),
85
  "y_min": float(min(y_vals)),
86
  "y_max": float(max(y_vals)),
87
  }
88
+ if y_unit:
89
+ result["y_unit"] = y_unit
90
+ return result
91
+
92
+
93
+ def _detect_current_unit(image_array, reader, all_texts):
94
+ """Try to detect the current unit from the y-axis label.
95
+
96
+ First checks all OCR text for unit patterns. If not found,
97
+ rotates the left margin 90° CW and re-runs OCR to read
98
+ the rotated y-axis label.
99
+ """
100
+ import cv2
101
+
102
+ combined = " ".join(all_texts).lower()
103
+ for pattern, unit in [
104
+ ("µa", "µA"), ("ua", "µA"), ("μa", "µA"),
105
+ ("(ma)", "mA"), ("ma)", "mA"), ("i/ma", "mA"),
106
+ ("(na)", "nA"), ("na)", "nA"),
107
+ ("(a)", "A"),
108
+ ]:
109
+ if pattern in combined:
110
+ return unit
111
+
112
+ H, W = image_array.shape[:2]
113
+ left_strip = image_array[:, : int(W * 0.08), :]
114
+ rotated = cv2.rotate(left_strip, cv2.ROTATE_90_CLOCKWISE)
115
+
116
+ try:
117
+ rot_results = reader.readtext(rotated, detail=1)
118
+ except Exception:
119
+ return None
120
+
121
+ rot_text_raw = " ".join(t.strip() for _, t, _ in rot_results)
122
+ rot_text_lower = rot_text_raw.lower()
123
+
124
+ # Check case-sensitive patterns first (µA vs mA)
125
+ for pattern, unit in [
126
+ ("µA", "µA"), ("µa", "µA"), ("uA", "µA"), ("μA", "µA"),
127
+ ("MA", "µA"), # OCR often misreads µ as M
128
+ ("mA", "mA"),
129
+ ("nA", "nA"),
130
+ ]:
131
+ if pattern in rot_text_raw:
132
+ return unit
133
+
134
+ # Fallback: case-insensitive but less reliable
135
+ if "ua" in rot_text_lower:
136
+ return "µA"
137
+
138
+ return None
139
 
140
 
141
  def _extract_axis_values(candidates, axis="x"):