-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsam_extraction_api.py
More file actions
1997 lines (1632 loc) · 82.6 KB
/
Copy pathsam_extraction_api.py
File metadata and controls
1997 lines (1632 loc) · 82.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
SAM Extraction API - First part of the two-API architecture
Handles contour extraction and refinement with SAM and CRF
Enhanced memory-optimized version that implements advanced CUDA memory management with FP32 precision
"""
import os
import sys
import uuid
import base64
import json
import logging
import numpy as np
import cv2
import torch
import traceback
import colorsys
import shutil
import psutil
from datetime import datetime, timezone, UTC
from flask import Flask, request, jsonify, send_file, redirect, send_from_directory
from flask_cors import CORS
from werkzeug.utils import secure_filename
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.StreamHandler(),
logging.FileHandler('sam_api.log')
]
)
logger = logging.getLogger(__name__)
# Configure CUDA for better performance
if torch.cuda.is_available():
torch.backends.cudnn.benchmark = False # Disable benchmarking for more stable memory usage
torch.backends.cudnn.deterministic = True # More deterministic behavior
torch.cuda.empty_cache()
# Set memory split size to avoid CUDA OOM errors
os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "max_split_size_mb:128,expandable_segments:True"
# Use a percentage of available GPU memory
try:
import gc
gc.collect()
torch.cuda.empty_cache()
# For older PyTorch versions
if hasattr(torch.cuda, 'set_per_process_memory_fraction'):
torch.cuda.set_per_process_memory_fraction(0.8) # Use 80% of GPU memory
except Exception as e:
logger.warning(f"Could not set CUDA memory fraction: {e}")
# Import SAM if available - don't load model yet, just check if the module exists
try:
from segment_anything import sam_model_registry, SamPredictor, SamAutomaticMaskGenerator
HAS_SAM = True
logger.info("SAM module loaded successfully")
except ImportError:
logger.warning("SAM module not available. Falling back to basic segmentation.")
HAS_SAM = False
# Try to import PyDenseCRF for proper edge refinement
try:
import pydensecrf.densecrf as dcrf
from pydensecrf.utils import unary_from_labels, create_pairwise_bilateral
HAS_CRF = True
logger.info("PyDenseCRF loaded successfully")
except ImportError:
logger.warning("PyDenseCRF not available. Using simplified edge refinement.")
HAS_CRF = False
# Try to import PIL as a fallback for image saving
try:
from PIL import Image
HAS_PIL = True
except ImportError:
HAS_PIL = False
# Create Flask app with configuration
app = Flask(__name__)
CORS(app) # Enable cross-origin requests
# App configuration
app.config.update(
MAX_CONTENT_LENGTH=16 * 1024 * 1024, # 16MB max upload size
UPLOAD_FOLDER=os.environ.get('UPLOAD_FOLDER', 'uploads'),
RESULT_FOLDER=os.environ.get('RESULT_FOLDER', 'results'),
STATIC_FOLDER=os.environ.get('STATIC_FOLDER', 'static'),
EDITOR_CONTOURS_FOLDER=os.environ.get('EDITOR_CONTOURS_FOLDER', 'contours'),
EDITOR_UPLOADS_FOLDER=os.environ.get('EDITOR_UPLOADS_FOLDER', 'uploads_editor'),
SAM_CHECKPOINT=os.environ.get('SAM_CHECKPOINT', './model/sam_vit_h_4b8939.pth'),
SAM_MODEL_TYPE=os.environ.get('SAM_MODEL_TYPE', 'vit_h'),
CLEANUP_FILES=os.environ.get('CLEANUP_FILES', 'false').lower() == 'true',
# Set to False in production!
DEBUG=os.environ.get('DEBUG', 'false').lower() == 'true',
# Added config for model unloading
UNLOAD_MODEL_AFTER_USE=os.environ.get('UNLOAD_MODEL_AFTER_USE', 'true').lower() == 'true',
# Memory optimization settings
MAX_IMAGE_SIDE=int(os.environ.get('MAX_IMAGE_SIDE', 1024)), # Max image dimension for processing
MAX_IMAGE_PIXELS=int(os.environ.get('MAX_IMAGE_PIXELS', 1000000)), # Max pixels (width*height)
# Force FP32 precision - never use half precision
USE_HALF_PRECISION=False
)
# Create necessary directories
for folder in [
app.config['UPLOAD_FOLDER'],
app.config['RESULT_FOLDER'],
app.config['STATIC_FOLDER'],
app.config['EDITOR_CONTOURS_FOLDER'],
app.config['EDITOR_UPLOADS_FOLDER']
]:
os.makedirs(folder, exist_ok=True)
class SAMExtractor:
"""SAM-based contour extraction with CRF refinement - Memory optimized with FP32 precision"""
def __init__(self, sam_checkpoint=None, model_type="vit_h", device=None):
"""Initialize the SAM Extractor - but don't load model yet"""
self.sam_model = None
self.predictor = None
self.mask_generator = None
self.sam_masks = None
self.sam_checkpoint = sam_checkpoint
self.model_type = model_type
# Current date & user - UPDATED with provided values
self.date = "2025-05-27 10:12:00" # Updated timestamp
self.user = "FETHl" # Updated user login
# Memory tracking
self.last_image_size = None
self.fallback_mode = False
self.use_half_precision = False # Always false - force FP32 precision
# Set device (CPU or CUDA)
if device is None:
self.device = "cpu" if torch.cuda.is_available() else "cuda"
else:
self.device = device
# Flag to track if model is loaded
self.model_loaded = False
logger.info(f"SAM Extractor initialized (model will be loaded on demand) with FP32 precision")
def is_model_loaded(self):
"""Check if the model is currently loaded"""
return self.model_loaded and self.sam_model is not None
def monitor_memory(self):
"""Monitor system memory and GPU memory"""
try:
# System memory usage
system_mem = psutil.virtual_memory()
system_mem_percent = system_mem.percent
# GPU memory usage
if self.device == "cuda" and torch.cuda.is_available():
gpu_mem_allocated = torch.cuda.memory_allocated() / 1024**3 # Convert to GB
gpu_mem_reserved = torch.cuda.memory_reserved() / 1024**3 # Convert to GB
total_gpu_mem = torch.cuda.get_device_properties(0).total_memory / 1024**3 # Convert to GB
gpu_mem_percent = gpu_mem_allocated / total_gpu_mem * 100
logger.debug(f"Memory stats - System: {system_mem_percent:.1f}% used, "
f"GPU: {gpu_mem_allocated:.2f}GB/{total_gpu_mem:.2f}GB ({gpu_mem_percent:.1f}% used), "
f"Reserved: {gpu_mem_reserved:.2f}GB")
# Return memory status
return {
"system_mem_percent": system_mem_percent,
"gpu_mem_allocated": gpu_mem_allocated,
"gpu_mem_reserved": gpu_mem_reserved,
"total_gpu_mem": total_gpu_mem,
"gpu_mem_percent": gpu_mem_percent
}
else:
logger.debug(f"Memory stats - System: {system_mem_percent:.1f}% used, GPU: N/A")
return {
"system_mem_percent": system_mem_percent,
"gpu_mem_allocated": 0,
"gpu_mem_reserved": 0,
"total_gpu_mem": 0,
"gpu_mem_percent": 0
}
except Exception as e:
logger.warning(f"Error monitoring memory: {e}")
return {}
def estimate_max_size(self):
"""Estimate the maximum image size we can process based on available memory"""
try:
if self.device == "cuda" and torch.cuda.is_available():
# Get total GPU memory
total_gpu_mem = torch.cuda.get_device_properties(0).total_memory / 1024**3 # GB
# Get currently used memory
allocated_mem = torch.cuda.memory_allocated() / 1024**3 # GB
# Calculate free memory with a safety margin
free_mem = total_gpu_mem - allocated_mem - 0.5 # Leave 0.5GB safety margin
# Adjusted values for FP32 precision on different memory sizes
if total_gpu_mem < 6.0: # For GPUs with less than 6GB VRAM
if free_mem <= 1.0:
return 300000 # ~550x550px
elif free_mem <= 2.0:
return 500000 # ~700x700px
else:
return 650000 # ~800x800px
else: # For GPUs with 6GB+ VRAM
if free_mem <= 2.0:
return 600000 # ~775x775px
elif free_mem <= 4.0:
return 800000 # ~895x895px
elif free_mem <= 8.0:
return 1200000 # ~1095x1095px
else:
return 1600000 # ~1265x1265px
else:
return app.config['MAX_IMAGE_PIXELS'] # Default value
except Exception as e:
logger.warning(f"Error estimating max size: {e}")
return app.config['MAX_IMAGE_PIXELS'] # Default value
def load_sam_model(self):
"""Load the SAM model from checkpoint - only when needed, using FP32 precision"""
# If model already loaded, do nothing
if self.is_model_loaded():
logger.info("SAM model already loaded, skipping load")
return True
try:
if not HAS_SAM:
logger.warning("SAM module not available, cannot load model")
return False
# Check if checkpoint exists
checkpoint_path = self.sam_checkpoint
if not checkpoint_path or not os.path.exists(checkpoint_path):
# Try to find SAM checkpoint in the current directory
checkpoint_path = app.config['SAM_CHECKPOINT']
if not os.path.exists(checkpoint_path):
logger.error(f"SAM checkpoint not found: {checkpoint_path}")
return False
logger.info(f"Loading SAM model from {checkpoint_path} with FP32 precision...")
# Clear cache before loading to ensure maximum available memory
if self.device == "cuda":
torch.cuda.empty_cache()
gc.collect()
# Load the model with explicit FP32 precision
# Use the newer recommended syntax for autocast
with torch.amp.autocast('cuda', enabled=False):
sam = sam_model_registry[self.model_type](checkpoint=checkpoint_path)
sam.to(device=self.device)
# Ensure model is in full precision
sam = sam.float()
logger.info("Using full precision (FP32) for better accuracy")
# Verify model is using FP32
for param in sam.parameters():
if param.dtype != torch.float32:
param.data = param.data.float()
self.sam_model = sam
self.predictor = SamPredictor(sam)
# Initialize mask generator with memory-efficient settings
self.mask_generator = SamAutomaticMaskGenerator(
model=sam,
points_per_side=16, # Reduced from 32 to save memory
points_per_batch=64, # Reduce batch size to save memory
pred_iou_thresh=0.86,
stability_score_thresh=0.92,
crop_n_layers=0, # Reduced cropping to save memory
crop_n_points_downscale_factor=2,
min_mask_region_area=100
)
# Set the flag to indicate model is loaded
self.model_loaded = True
# Reset fallback mode
self.fallback_mode = False
logger.info(f"SAM model loaded successfully on {self.device} with FP32 precision")
return True
except Exception as e:
logger.error(f"Error loading SAM model: {str(e)}")
logger.error(traceback.format_exc())
# Ensure flag is set to false in case of error
self.model_loaded = False
return False
def unload_model(self):
"""Unload the model and free GPU memory"""
if not self.is_model_loaded():
return # Nothing to do
logger.info("Unloading SAM model to free GPU memory")
try:
# Remove references to models
self.sam_model = None
self.predictor = None
self.mask_generator = None
# Clear CUDA cache
if self.device == "cuda":
torch.cuda.empty_cache()
gc.collect()
logger.info("SAM model unloaded successfully")
# Update flag
self.model_loaded = False
except Exception as e:
logger.error(f"Error unloading model: {str(e)}")
def process_image_for_sam(self, image):
"""
Preprocess image for SAM processing with memory-efficient resizing
Parameters:
- image: BGR image from OpenCV
Returns:
- Processed RGB image, scale factor, target dimensions
"""
height, width = image.shape[:2]
original_size = (width, height)
total_pixels = width * height
# Convert to RGB for SAM
rgb_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# Get current memory stats
mem_stats = self.monitor_memory()
# Calculate max size based on current memory
max_pixels = self.estimate_max_size()
logger.info(f"Estimated max image size: {max_pixels} pixels")
# Determine if we need to resize
if total_pixels > max_pixels:
# Calculate scale factor to fit within max_pixels
scale = np.sqrt(max_pixels / total_pixels)
# Calculate target dimensions
target_width = int(width * scale)
target_height = int(height * scale)
logger.info(f"Resizing image from {width}x{height} to {target_width}x{target_height} for processing")
# Resize image for processing
processed_image = cv2.resize(rgb_image, (target_width, target_height), interpolation=cv2.INTER_AREA)
return processed_image, scale, (target_width, target_height)
else:
# No resizing needed
return rgb_image, 1.0, original_size
def segment_automatic(self, image):
"""
Perform automatic segmentation without prompts
Parameters:
- image: BGR image (OpenCV format)
Returns:
- Binary mask as boolean array
"""
# Load model if not already loaded
if not self.is_model_loaded():
if not self.load_sam_model():
# If model can't be loaded, fall back to basic segmentation
logger.warning("SAM model could not be loaded. Using basic thresholding.")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
_, mask = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
return mask > 0
try:
# Check if image is very large
height, width = image.shape[:2]
original_size = (width, height)
# Process and resize image for SAM
processed_image, scale_factor, (target_width, target_height) = self.process_image_for_sam(image)
# Try to use automatic mask generator
try:
# Clear GPU cache before processing
if self.device == "cuda":
torch.cuda.empty_cache()
gc.collect()
# Disable any automatic mixed precision during processing
with torch.amp.autocast('cuda', enabled=False):
with torch.no_grad(): # Ensure no gradients tracked for memory efficiency
masks = self.mask_generator.generate(processed_image)
logger.info(f"SAM generated {len(masks)} masks")
except RuntimeError as e:
if "CUDA out of memory" in str(e):
logger.error(f"SAM mask generation failed: {e}")
# Set fallback mode for next time
self.fallback_mode = True
# Use a basic fallback method
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
_, mask = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
# Create a circle in the center as a default mask
center_mask = np.zeros((height, width), dtype=np.uint8)
center_x, center_y = width // 2, height // 2
radius = min(width, height) // 4
cv2.circle(center_mask, (center_x, center_y), radius, 255, -1)
# Unload model after processing if configured
if app.config['UNLOAD_MODEL_AFTER_USE']:
self.unload_model()
return center_mask > 0
else:
# Re-raise other errors
raise
# Initialize combined mask and individual masks storage
if scale_factor < 1.0: # If we resized earlier
combined_mask = np.zeros((target_height, target_width), dtype=np.uint8)
self.sam_masks = []
# Process individual masks
for i, mask_data in enumerate(masks):
mask = mask_data["segmentation"].astype(np.uint8) * 255
# Store for later processing (resized to original)
resized_mask = cv2.resize(mask, (width, height), interpolation=cv2.INTER_NEAREST)
self.sam_masks.append({
"segmentation": resized_mask > 127,
"score": mask_data.get("score", 1.0),
"area": float(np.sum(resized_mask > 0))
})
# Update combined mask
combined_mask = np.maximum(combined_mask, mask)
# Resize combined mask back to original size
final_mask = cv2.resize(combined_mask, (width, height), interpolation=cv2.INTER_NEAREST)
else:
# Process for original-sized images
combined_mask = np.zeros((height, width), dtype=np.uint8)
self.sam_masks = []
for i, mask_data in enumerate(masks):
mask = mask_data["segmentation"].astype(np.uint8) * 255
# Store for later processing
self.sam_masks.append({
"segmentation": mask > 127,
"score": mask_data.get("score", 1.0),
"area": float(np.sum(mask > 0))
})
# Update combined mask
combined_mask = np.maximum(combined_mask, mask)
final_mask = combined_mask
# Make sure we have a binary mask
binary_mask = final_mask > 127
# Unload model after processing if configured
if app.config['UNLOAD_MODEL_AFTER_USE']:
self.unload_model()
# Return the mask as binary
return binary_mask
except Exception as e:
logger.error(f"Error in automatic segmentation: {str(e)}")
logger.error(traceback.format_exc())
# Clear CUDA cache
if self.device == "cuda":
torch.cuda.empty_cache()
gc.collect()
# Create a circle in the center as a default mask
center_mask = np.zeros((height, width), dtype=np.uint8)
center_x, center_y = width // 2, height // 2
radius = min(width, height) // 4
cv2.circle(center_mask, (center_x, center_y), radius, 255, -1)
# Make sure to unload model even in case of error
if app.config['UNLOAD_MODEL_AFTER_USE']:
self.unload_model()
return center_mask > 0
def segment_with_points(self, image, points, labels=None):
"""
Segment image using point prompts
Parameters:
- image: BGR image (OpenCV format)
- points: Nx2 array of (x, y) point coordinates
- labels: N-length array of 1 (foreground) or 0 (background) (default: all 1)
Returns:
- Binary mask as boolean array
"""
# Load model if not already loaded
if not self.is_model_loaded():
logger.warning("SAM predictor not available for point prompts. Using automatic segmentation.")
return self.segment_automatic(image)
try:
# Check image dimensions
height, width = image.shape[:2]
original_size = (width, height)
# Set default labels if not provided (all foreground)
if labels is None:
labels = np.ones(len(points))
# Convert to numpy arrays if not already
input_points = np.array(points, dtype=np.float32)
input_labels = np.array(labels, dtype=np.int32)
# Process and resize image for SAM
processed_image, scale_factor, (target_width, target_height) = self.process_image_for_sam(image)
# Scale points to match the resized image if needed
if scale_factor != 1.0:
scaled_points = input_points * scale_factor
else:
scaled_points = input_points
try:
# Set the image in SAM with explicit FP32 precision
with torch.amp.autocast('cuda', enabled=False): # Ensure FP32 precision
self.predictor.set_image(processed_image)
# Free memory before prediction
if self.device == "cuda":
torch.cuda.empty_cache()
gc.collect()
# Get the mask prediction with explicit FP32 precision
with torch.amp.autocast('cuda', enabled=False): # Ensure FP32 precision
with torch.no_grad(): # Ensure no gradients tracked for memory efficiency
masks, scores, _ = self.predictor.predict(
point_coords=scaled_points,
point_labels=input_labels,
multimask_output=True # Get multiple mask predictions
)
except Exception as e:
logger.error(f"Error in point segmentation: {e}")
# Fall back to automatic segmentation
return self.segment_automatic(image)
# Store masks for contour extraction
self.sam_masks = []
if len(masks) > 0:
best_mask_idx = np.argmax(scores)
for i, mask in enumerate(masks):
if scale_factor != 1.0:
# Need to resize mask to original dimensions
resized_mask = cv2.resize((mask > 0).astype(np.uint8) * 255,
original_size, interpolation=cv2.INTER_NEAREST)
mask_for_segmentation = resized_mask > 127
else:
mask_for_segmentation = mask > 0
resized_mask = (mask > 0).astype(np.uint8) * 255
self.sam_masks.append({
"segmentation": mask_for_segmentation,
"score": float(scores[i]),
"area": float(np.sum(mask_for_segmentation))
})
# Return the best mask resized to original dimensions if needed
if scale_factor != 1.0:
best_mask = cv2.resize((masks[best_mask_idx] > 0).astype(np.uint8) * 255,
original_size, interpolation=cv2.INTER_NEAREST)
result = best_mask > 127
else:
result = masks[best_mask_idx] > 0
# Unload model after processing if configured
if app.config['UNLOAD_MODEL_AFTER_USE']:
self.unload_model()
return result
else:
logger.warning("No masks generated from points")
# Fall back to automatic segmentation
return self.segment_automatic(image)
except Exception as e:
logger.error(f"Error in point segmentation: {str(e)}")
logger.error(traceback.format_exc())
# Clear CUDA cache
if self.device == "cuda":
torch.cuda.empty_cache()
gc.collect()
# Always unload model at the end if configured
if app.config['UNLOAD_MODEL_AFTER_USE']:
self.unload_model()
# Fall back to automatic segmentation
return self.segment_automatic(image)
def _create_default_mask(self, image, points=None):
"""Create a default mask when segmentation fails"""
height, width = image.shape[:2]
# If we have points, create a mask based on those points
if points is not None and len(points) > 0:
mask = np.zeros((height, width), dtype=np.uint8)
for x, y in points:
cv2.circle(mask, (int(x), int(y)), 50, 255, -1)
return mask > 0
else:
# Otherwise create a center circle
center_mask = np.zeros((height, width), dtype=np.uint8)
center_x, center_y = width // 2, height // 2
radius = min(width, height) // 4
cv2.circle(center_mask, (center_x, center_y), radius, 255, -1)
return center_mask > 0
def segment_with_box(self, image, box):
"""
Segment image using a bounding box prompt
Parameters:
- image: BGR image (OpenCV format)
- box: 2x2 array [[x1, y1], [x2, y2]] of box corners
Returns:
- Binary mask as boolean array
"""
# Load model if not already loaded
if not self.is_model_loaded():
logger.warning("SAM predictor not available for box prompts. Using automatic segmentation.")
return self.segment_automatic(image)
try:
# Check image dimensions
height, width = image.shape[:2]
original_size = (width, height)
# Convert box to the format SAM expects [x1, y1, x2, y2]
input_box = np.array([box[0][0], box[0][1], box[1][0], box[1][1]], dtype=np.float32)
# Process and resize image for SAM
processed_image, scale_factor, (target_width, target_height) = self.process_image_for_sam(image)
# Scale box to match the resized image if needed
if scale_factor != 1.0:
scaled_box = input_box * scale_factor
else:
scaled_box = input_box
try:
# Set the image in SAM with explicit FP32 precision
with torch.amp.autocast('cuda', enabled=False):
self.predictor.set_image(processed_image)
# Free memory before prediction
if self.device == "cuda":
torch.cuda.empty_cache()
gc.collect()
# Get the mask prediction with explicit FP32 precision
with torch.amp.autocast('cuda', enabled=False):
with torch.no_grad(): # Ensure no gradients tracked for memory efficiency
masks, scores, _ = self.predictor.predict(
point_coords=None,
point_labels=None,
box=scaled_box[None, :],
multimask_output=True # Get multiple mask predictions
)
except Exception as e:
logger.error(f"Error in box segmentation: {e}")
# Fall back to automatic segmentation
return self.segment_automatic(image)
# Store masks for contour extraction
self.sam_masks = []
if len(masks) > 0:
best_mask_idx = np.argmax(scores)
for i, mask in enumerate(masks):
if scale_factor != 1.0:
# Need to resize mask to original dimensions
resized_mask = cv2.resize((mask > 0).astype(np.uint8) * 255,
original_size, interpolation=cv2.INTER_NEAREST)
mask_for_segmentation = resized_mask > 127
else:
mask_for_segmentation = mask > 0
resized_mask = (mask > 0).astype(np.uint8) * 255
self.sam_masks.append({
"segmentation": mask_for_segmentation,
"score": float(scores[i]),
"area": float(np.sum(mask_for_segmentation))
})
# Return the best mask resized to original dimensions
if scale_factor != 1.0:
best_mask = cv2.resize((masks[best_mask_idx] > 0).astype(np.uint8) * 255,
original_size, interpolation=cv2.INTER_NEAREST)
result = best_mask > 127
else:
result = masks[best_mask_idx] > 0
# Unload model after processing if configured
if app.config['UNLOAD_MODEL_AFTER_USE']:
self.unload_model()
return result
else:
logger.warning("No masks generated from box")
# Fall back to automatic segmentation
return self.segment_automatic(image)
except Exception as e:
logger.error(f"Error in box segmentation: {str(e)}")
logger.error(traceback.format_exc())
# Clear CUDA cache
if self.device == "cuda":
torch.cuda.empty_cache()
gc.collect()
# Always unload model at the end if there's an error
if app.config['UNLOAD_MODEL_AFTER_USE']:
self.unload_model()
# Fall back to automatic segmentation
return self.segment_automatic(image)
def refine_edges(self, image, mask):
"""
Refine the edges of a mask using CRF (if available) or morphological operations
Parameters:
- image: Original RGB image
- mask: Binary segmentation mask
Returns:
- Refined binary mask
"""
# Ensure mask is correct format - 2D binary mask
if len(mask.shape) > 2:
if mask.shape[2] == 1:
mask = mask[:, :, 0]
else:
# Take first channel or combine channels
mask = np.any(mask, axis=2)
# Convert mask to uint8 binary format (0 or 1)
binary_mask = (mask > 0).astype(np.uint8)
# Apply CRF if available - with error handling
if HAS_CRF:
try:
return self._apply_crf(image, binary_mask)
except Exception as e:
logger.warning(f"CRF application error: {str(e)}")
logger.warning(traceback.format_exc())
# Return original mask on failure
return mask > 0
# Morphological refinement
try:
# Ensure mask has correct shape
if binary_mask.shape[:2] != image.shape[:2]:
binary_mask = cv2.resize(binary_mask, (image.shape[1], image.shape[0]))
# Use a series of morphological operations for refinement
kernel_small = np.ones((3, 3), np.uint8)
kernel_medium = np.ones((5, 5), np.uint8)
# Close small gaps
closed = cv2.morphologyEx(binary_mask, cv2.MORPH_CLOSE, kernel_small)
# Remove small noise
opening = cv2.morphologyEx(closed, cv2.MORPH_OPEN, kernel_small)
# Smooth edges
smooth = cv2.GaussianBlur(opening, (5, 5), 0)
refined_mask = smooth > 0.5
return refined_mask
except Exception as e:
logger.error(f"Edge refinement error: {str(e)}")
logger.error(traceback.format_exc())
return mask
def _apply_crf(self, image, mask, iterations=5):
"""
Apply Conditional Random Field to refine mask edges
Parameters:
- image: RGB image
- mask: Binary mask (0 or 1)
- iterations: Number of CRF iterations
Returns:
- Refined binary mask
"""
try:
# Ensure shapes match
if image.shape[:2] != mask.shape[:2]:
mask = cv2.resize(mask, (image.shape[1], image.shape[0]))
h, w = mask.shape[:2]
# FIX: Make absolutely sure the mask only contains 0 and 1 values
# This fixes the "index 255 is out of bounds for axis 0 with size 2" error
mask_labels = np.zeros_like(mask)
mask_labels[mask > 0] = 1
# Double-check unique values
unique_values = np.unique(mask_labels)
logger.info(f"Mask labels min: {mask_labels.min()}, max: {mask_labels.max()}, unique: {unique_values}")
# Create CRF with the image dimensions
d = dcrf.DenseCRF2D(w, h, 2) # 2 labels: fg and bg
# Create unary potentials from the mask
U = unary_from_labels(mask_labels, 2, gt_prob=0.7)
d.setUnaryEnergy(U)
# Create pairwise potentials (bilateral)
# This considers both color similarity and proximity
pairwise_energy = create_pairwise_bilateral(
sdims=(80, 80), # Spatial dimensions (sigma_x, sigma_y)
schan=(13, 13, 13), # Color dimensions (sigma_r, sigma_g, sigma_b)
img=image,
chdim=2 # Color is in the 3rd dimension (RGB)
)
d.addPairwiseEnergy(pairwise_energy, compat=10)
# Add another pairwise term (Potts model)
# This penalizes small isolated regions
d.addPairwiseEnergy(
np.ones(w*h, dtype=np.float32), # Flattened array of correct size
compat=3,
kernel=dcrf.DIAG_KERNEL,
normalization=dcrf.NORMALIZE_SYMMETRIC
)
# Perform inference
Q = d.inference(iterations)
# Get the refined mask
refined_mask = np.argmax(Q, axis=0).reshape((h, w)) * 255
return refined_mask > 0
except Exception as e:
logger.warning(f"CRF application error: {str(e)}")
logger.warning(traceback.format_exc())
# Return original mask on failure
return mask > 0
def extract_contours(self, mask):
"""
Extract contours from binary mask and SAM masks if available
Parameters:
- mask: Combined binary mask
Returns:
- List of contours
"""
# Store results
all_contours = []
contour_id = 0
# Debug info
logger.info(f"Extracting contours from mask: shape={mask.shape}, "
f"min={np.min(mask)}, max={np.max(mask)}")
# Create debug image for visualization
height, width = mask.shape[:2]
debug_image = np.zeros((height, width, 3), dtype=np.uint8)
# Ensure mask is binary and not empty
binary_mask = (mask > 0).astype(np.uint8) * 255
# Check if mask is empty
if np.sum(binary_mask) == 0:
logger.warning("Empty mask detected, creating default contours")
# Create several contours across the image for better results
contours_to_add = []
# Add a rectangle covering ~60% of the image
rect_w, rect_h = int(width * 0.6), int(height * 0.6)
x1 = (width - rect_w) // 2
y1 = (height - rect_h) // 2
x2, y2 = x1 + rect_w, y1 + rect_h
contours_to_add.append({
'points': [[x1, y1], [x2, y1], [x2, y2], [x1, y2]],
'color': [0.8, 0.2, 0.2], # Red
'area': float(rect_w * rect_h)
})
# Add a circle in the center
center_x, center_y = width // 2, height // 2
radius = min(width, height) // 5
circle_points = []
for angle in range(0, 360, 10): # Every 10 degrees
x = center_x + int(radius * np.cos(np.radians(angle)))
y = center_y + int(radius * np.sin(np.radians(angle)))
circle_points.append([x, y])
contours_to_add.append({
'points': circle_points,
'color': [0.2, 0.8, 0.2], # Green
'area': float(np.pi * radius * radius)
})
# Add contours to the results
for i, contour_data in enumerate(contours_to_add):
all_contours.append({
'id': i,
'mask_id': -1,
'points': contour_data['points'],
'is_external': True,
'parent_idx': -1,
'color': contour_data['color'],
'area': contour_data['area']
})
# Save a debug image to help diagnose the issue
cv2.rectangle(debug_image, (x1, y1), (x2, y2), (0, 0, 255), 2)
cv2.circle(debug_image, (center_x, center_y), radius, (0, 255, 0), 2)
debug_path = os.path.join(app.config['RESULT_FOLDER'], f"contour_debug_{uuid.uuid4().hex[:8]}.png")
cv2.imwrite(debug_path, debug_image)
logger.info(f"Saved contour debug image to {debug_path}")
return all_contours
# 1. First, try to extract contours from individual SAM masks
if hasattr(self, 'sam_masks') and self.sam_masks and len(self.sam_masks) > 0:
logger.info(f"Using {len(self.sam_masks)} individual SAM masks for contour extraction")
for idx, mask_data in enumerate(self.sam_masks):
# Get the individual mask
individual_mask = mask_data["segmentation"].astype(np.uint8) * 255
# Make sure the mask is not empty
if np.sum(individual_mask) == 0:
continue
# Generate contour color
hue = (idx * 137.5) % 360 # Use golden angle for good distribution
r, g, b = colorsys.hsv_to_rgb(hue/360, 0.8, 0.9)
color = [float(r), float(g), float(b)]
cv_color = (int(r*255), int(g*255), int(b*255))
# Find contours in this mask
try:
# Use RETR_EXTERNAL first for cleaner boundaries
contours, _ = cv2.findContours(
individual_mask,
cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE
)
if not contours:
# Try RETR_CCOMP if no external contours
contours, hierarchy = cv2.findContours(
individual_mask,
cv2.RETR_CCOMP,
cv2.CHAIN_APPROX_SIMPLE
)
hierarchy = hierarchy[0] if hierarchy is not None else []
else:
# Simple hierarchy for external contours
hierarchy = [[-1, -1, -1, -1] for _ in range(len(contours))]