File size: 7,166 Bytes
8f59aab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Simple test script - Test model on sample images without masks
Phiên bản đơn giản - test mô hình trên ảnh mẫu mà không cần mask
"""

import os
import argparse
from pathlib import Path
import numpy as np
from PIL import Image
import json
from tqdm import tqdm

import torch
import torch.nn.functional as F
from transformers import SegformerForSemanticSegmentation, SegformerImageProcessor

class SimpleSegmentationTester:
    def __init__(self, model_path, device="auto"):
        self.device = torch.device("cuda" if device == "auto" and torch.cuda.is_available() else "cpu")
        
        print(f"🖥️  Device: {self.device}")
        print(f"📁 Loading model from: {model_path}")
        
        try:
            # Load model
            self.model = SegformerForSemanticSegmentation.from_pretrained(model_path)
            self.model.to(self.device)
            self.model.eval()
            
            # Create default processor (from nvidia/segformer-b0-finetuned-cityscapes-1024-1024)
            self.processor = SegformerImageProcessor(
                do_resize=True,
                size={"height": 512, "width": 512},
                do_normalize=True,
                image_mean=[0.485, 0.456, 0.406],
                image_std=[0.229, 0.224, 0.225],
                do_reduce_labels=False
            )
            
            print("✓ Model loaded successfully")
        except Exception as e:
            print(f"✗ Error loading model: {e}")
            raise
    
    def predict_single(self, image_path, return_probs=False):
        """Dự đoán trên một ảnh"""
        try:
            # Load image
            image = Image.open(image_path).convert("RGB")
            original_size = image.size[::-1]  # (H, W)
            
            # Process image
            inputs = self.processor(images=image, return_tensors="pt")
            
            # Inference
            with torch.no_grad():
                outputs = self.model(pixel_values=inputs["pixel_values"].to(self.device))
                logits = outputs.logits
            
            # Interpolate to original size
            upsampled_logits = F.interpolate(
                logits,
                size=original_size,
                mode="bilinear",
                align_corners=False
            )
            
            pred_mask = upsampled_logits.argmax(dim=1)[0].cpu().numpy()
            
            if return_probs:
                probs = torch.softmax(upsampled_logits, dim=1)[0].cpu().numpy()
                return pred_mask, probs
            
            return pred_mask
        except Exception as e:
            print(f"✗ Error predicting on {image_path}: {e}")
            return None
    
    def process_images(self, image_dir, output_dir=None):
        """Xử lý tất cả ảnh trong thư mục"""
        image_dir = Path(image_dir)
        
        if not image_dir.exists():
            print(f"✗ Directory not found: {image_dir}")
            return False
        
        image_paths = sorted(list(image_dir.glob("*.png"))) + sorted(list(image_dir.glob("*.jpg")))
        
        if not image_paths:
            print(f"✗ No images found in {image_dir}")
            return False
        
        print(f"\n📊 Processing {len(image_paths)} images...")
        
        if output_dir:
            output_dir = Path(output_dir)
            output_dir.mkdir(parents=True, exist_ok=True)
        
        results = []
        
        for img_path in tqdm(image_paths):
            img_id = img_path.stem
            
            # Predict
            pred_mask = self.predict_single(img_path)
            
            if pred_mask is None:
                continue
            
            # Count detected organs
            total_pixels = pred_mask.size
            detected_organs = {
                'large_bowel': int((pred_mask == 1).sum()),
                'small_bowel': int((pred_mask == 2).sum()),
                'stomach': int((pred_mask == 3).sum()),
                'background': int((pred_mask == 0).sum()),
                'total_pixels': total_pixels
            }
            
            result = {
                'image_id': img_id,
                'detected_organs': detected_organs,
                'total_pixels': total_pixels
            }
            results.append(result)
            
            # Save prediction mask if output_dir provided
            if output_dir:
                # Colorize prediction
                pred_colored = np.zeros((*pred_mask.shape, 3), dtype=np.uint8)
                
                # Colors: 1=red, 2=green, 3=blue, 0=black
                pred_colored[pred_mask == 1] = [255, 0, 0]      # Large bowel - Red
                pred_colored[pred_mask == 2] = [0, 154, 23]     # Small bowel - Green
                pred_colored[pred_mask == 3] = [0, 127, 255]    # Stomach - Blue
                
                pred_img = Image.fromarray(pred_colored)
                pred_img.save(output_dir / f"{img_id}_pred.png")
        
        # Print summary
        print("\n" + "="*60)
        print("📈 Prediction Summary")
        print("="*60)
        
        if results:
            print(f"\nProcessed {len(results)} images successfully\n")
            
            # Statistics
            for idx, result in enumerate(results, 1):
                print(f"{idx}. {result['image_id']}")
                organs = result['detected_organs']
                total = organs['large_bowel'] + organs['small_bowel'] + organs['stomach']
                if total > 0:
                    print(f"   - Large bowel: {organs['large_bowel']:,} pixels")
                    print(f"   - Small bowel: {organs['small_bowel']:,} pixels")
                    print(f"   - Stomach: {organs['stomach']:,} pixels")
                    print(f"   - Total organs: {total:,} pixels ({100*total/organs['total_pixels']:.1f}%)")
                else:
                    print(f"   - No organs detected")
        
        # Save results
        if output_dir:
            with open(output_dir / "predictions.json", 'w') as f:
                json.dump(results, f, indent=2)
            print(f"\n✓ Predictions saved to {output_dir}")
            print(f"  - Colored masks: {output_dir}/*_pred.png")
            print(f"  - Results JSON: {output_dir}/predictions.json")
        
        return True

def main():
    parser = argparse.ArgumentParser(description="Simple test on sample images")
    parser.add_argument("--model", type=str, required=True,
                       help="Path to trained model")
    parser.add_argument("--images", type=str, required=True,
                       help="Path to images directory")
    parser.add_argument("--output-dir", type=str, default=None,
                       help="Output directory for results")
    
    args = parser.parse_args()
    
    # Initialize tester
    tester = SimpleSegmentationTester(args.model)
    
    # Process images
    success = tester.process_images(args.images, args.output_dir)
    
    return success

if __name__ == "__main__":
    success = main()
    exit(0 if success else 1)