Fahimeh Orvati Nia commited on
Commit
981de0a
·
1 Parent(s): 0153931

input image faster

Browse files
sorghum_pipeline/output/manager.py CHANGED
@@ -41,6 +41,34 @@ class OutputManager:
41
  return
42
 
43
  self._save_minimal_demo_outputs(plant_data)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
  def _save_minimal_demo_outputs(self, plant_data: Dict[str, Any]) -> None:
46
  """Save only the 7 required images."""
 
41
  return
42
 
43
  self._save_minimal_demo_outputs(plant_data)
44
+
45
+ def _save_input_image_only(self, plant_key: str, plant_data: Dict[str, Any]) -> None:
46
+ """Quick save of just the input image for immediate display."""
47
+ results_dir = self.output_folder / 'results'
48
+ results_dir.mkdir(parents=True, exist_ok=True)
49
+
50
+ try:
51
+ norm_input = plant_data.get('normalized_input')
52
+ if isinstance(norm_input, np.ndarray):
53
+ vis = norm_input
54
+ if vis.ndim == 2:
55
+ vis_u8 = self._normalize_to_uint8(vis.astype(np.float64))
56
+ vis_rgb = cv2.cvtColor(vis_u8, cv2.COLOR_GRAY2RGB)
57
+ elif vis.ndim == 3 and vis.shape[2] == 3:
58
+ if vis.dtype != np.uint8:
59
+ vis_u8 = self._normalize_to_uint8(vis.astype(np.float64))
60
+ else:
61
+ vis_u8 = vis
62
+ # Assume BGR
63
+ vis_rgb = cv2.cvtColor(vis_u8, cv2.COLOR_BGR2RGB)
64
+ else:
65
+ vis_u8 = self._normalize_to_uint8(vis.astype(np.float64))
66
+ vis_rgb = cv2.cvtColor(vis_u8, cv2.COLOR_GRAY2RGB)
67
+
68
+ titled = self._add_title_banner(vis_rgb, 'Input Image')
69
+ cv2.imwrite(str(results_dir / 'input_image.png'), titled)
70
+ except Exception as e:
71
+ logger.error(f"Failed to save input image: {e}")
72
 
73
  def _save_minimal_demo_outputs(self, plant_data: Dict[str, Any]) -> None:
74
  """Save only the 7 required images."""
sorghum_pipeline/pipeline.py CHANGED
@@ -155,20 +155,27 @@ class SorghumPipeline:
155
  # Create output directories early
156
  self.output_manager.create_output_directories()
157
 
158
- # Stage 1: Create composite + Segmentation (combined for speed)
 
 
 
 
 
 
 
159
  logger.info("Stage 1: Creating composite and segmenting...")
160
  plants = self.preprocessor.create_composites(plants)
161
  plants = self._segment(plants)
162
  if progress_callback:
163
  progress_callback("segmentation", plants)
164
- # Save composite, mask, overlay, and input image
165
  for key, pdata in plants.items():
166
  self.output_manager.save_plant_results(key, pdata)
167
  yield {"plants": plants, "stage": "segmentation"}
168
 
169
- # Stage 2: Extract features (texture, vegetation, morphology)
170
  logger.info("Stage 2: Extracting features...")
171
- plants = self._extract_features(plants)
172
  if progress_callback:
173
  progress_callback("features", plants)
174
  # Save all final outputs
@@ -251,6 +258,67 @@ class SorghumPipeline:
251
 
252
  return plants
253
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
254
  def _compute_vegetation(self, spectral: Dict[str, np.ndarray], mask: np.ndarray) -> Dict[str, Any]:
255
  """Compute NDVI, GNDVI, SAVI."""
256
  out = {}
 
155
  # Create output directories early
156
  self.output_manager.create_output_directories()
157
 
158
+ # Stage 0: Save and show input image immediately
159
+ logger.info("Stage 0: Saving input image...")
160
+ for key, pdata in plants.items():
161
+ # Quick save of just the input image
162
+ self.output_manager._save_input_image_only(key, pdata)
163
+ yield {"plants": plants, "stage": "input"}
164
+
165
+ # Stage 1: Create composite + Segmentation
166
  logger.info("Stage 1: Creating composite and segmenting...")
167
  plants = self.preprocessor.create_composites(plants)
168
  plants = self._segment(plants)
169
  if progress_callback:
170
  progress_callback("segmentation", plants)
171
+ # Save composite, mask, overlay
172
  for key, pdata in plants.items():
173
  self.output_manager.save_plant_results(key, pdata)
174
  yield {"plants": plants, "stage": "segmentation"}
175
 
176
+ # Stage 2: Extract features (texture, vegetation, morphology) - run in parallel where possible
177
  logger.info("Stage 2: Extracting features...")
178
+ plants = self._extract_features_fast(plants)
179
  if progress_callback:
180
  progress_callback("features", plants)
181
  # Save all final outputs
 
258
 
259
  return plants
260
 
261
+ def _extract_features_fast(self, plants: Dict[str, Any]) -> Dict[str, Any]:
262
+ """Fast feature extraction - skip textures, minimal vegetation indices."""
263
+ for key, pdata in plants.items():
264
+ composite = pdata['composite']
265
+ mask = pdata.get('mask')
266
+
267
+ # Skip texture extraction for speed (can be added back if needed)
268
+ pdata['texture_features'] = {}
269
+ spectral = pdata.get('spectral_stack', {})
270
+
271
+ # Only compute essential texture on very downsampled green band for speed
272
+ if 'green' in spectral:
273
+ green_band = np.asarray(spectral['green'], dtype=np.float64)
274
+ if green_band.ndim == 3 and green_band.shape[-1] == 1:
275
+ green_band = green_band[..., 0]
276
+
277
+ # Downsample to 64x64 max for very fast texture computation
278
+ h, w = green_band.shape[:2]
279
+ if h > 64 or w > 64:
280
+ scale = 64 / max(h, w)
281
+ green_band = cv2.resize(green_band, None, fx=scale, fy=scale, interpolation=cv2.INTER_LINEAR)
282
+ if mask is not None:
283
+ mask_resized = cv2.resize(mask, (green_band.shape[1], green_band.shape[0]), interpolation=cv2.INTER_NEAREST)
284
+ else:
285
+ mask_resized = None
286
+ else:
287
+ mask_resized = mask
288
+
289
+ if mask_resized is not None:
290
+ valid = np.where(mask_resized > 0, green_band, np.nan)
291
+ else:
292
+ valid = green_band
293
+
294
+ v = np.nan_to_num(valid, nan=np.nanmin(valid))
295
+ m, M = np.min(v), np.max(v)
296
+ denom = (M - m) if (M - m) > 1e-6 else 1.0
297
+ gray8 = ((v - m) / denom * 255.0).astype(np.uint8)
298
+
299
+ lbp_map = self.texture_extractor.extract_lbp(gray8)
300
+ hog_map = self.texture_extractor.extract_hog(gray8)
301
+ lac1_map = self.texture_extractor.compute_local_lacunarity(gray8)
302
+ pdata['texture_features'] = {'green': {'features': {'lbp': lbp_map, 'hog': hog_map, 'lac1': lac1_map}}}
303
+
304
+ # --- Vegetation indices ---
305
+ if spectral and mask is not None:
306
+ pdata['vegetation_indices'] = self._compute_vegetation(spectral, mask)
307
+ else:
308
+ pdata['vegetation_indices'] = {}
309
+
310
+ # --- Morphology ---
311
+ try:
312
+ if mask is not None and isinstance(composite, np.ndarray):
313
+ morph = self.morphology_extractor.extract_morphology_features(composite, mask)
314
+ pdata['morphology_features'] = morph
315
+ else:
316
+ pdata['morphology_features'] = {}
317
+ except Exception:
318
+ pdata['morphology_features'] = {}
319
+
320
+ return plants
321
+
322
  def _compute_vegetation(self, spectral: Dict[str, np.ndarray], mask: np.ndarray) -> Dict[str, Any]:
323
  """Compute NDVI, GNDVI, SAVI."""
324
  out = {}
sorghum_pipeline/segmentation/manager.py CHANGED
@@ -43,13 +43,13 @@ class SegmentationManager:
43
  low_cpu_mem_usage=True, # Reduce memory usage during loading
44
  ).eval().to(self.device)
45
 
46
- # Use 512x512 for 4x speed improvement
47
  self.transform = transforms.Compose([
48
- transforms.Resize((512, 512)),
49
  transforms.ToTensor(),
50
  transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
51
  ])
52
- logger.info("BRIA model loaded")
53
 
54
  def segment_image_soft(self, image: np.ndarray) -> np.ndarray:
55
  """Segment image and return soft mask [0,1]."""
 
43
  low_cpu_mem_usage=True, # Reduce memory usage during loading
44
  ).eval().to(self.device)
45
 
46
+ # Use 384x384 for even faster speed (6x improvement over 1024x1024)
47
  self.transform = transforms.Compose([
48
+ transforms.Resize((384, 384)),
49
  transforms.ToTensor(),
50
  transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
51
  ])
52
+ logger.info(f"BRIA model loaded on device: {self.device}")
53
 
54
  def segment_image_soft(self, image: np.ndarray) -> np.ndarray:
55
  """Segment image and return soft mask [0,1]."""