File size: 5,616 Bytes
9869d0d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Inference script for 2D Semantic Segmentation using the trained U-Net model.
This script loads RGB images, performs inference, and visualizes the predictions 
in a compact grid format optimized for scientific papers.
"""
import os
import torch
import torch.nn as nn
import torchvision.transforms.functional as TF
import numpy as np
import cv2
import segmentation_models_pytorch as smp
import matplotlib.pyplot as plt

# --- CONFIGURATION ---
CONFIG = {
    'num_classes': 5,  # Must match training configuration
    'class_names': {0: "ground", 1: "leaf", 2: "branch", 3: "weed", 4: "obstacle"},
    'device': torch.device('cuda' if torch.cuda.is_available() else 'cpu'),
    'model_path': 'unet_efficientnetb3_semantic.pth', 
    'input_image_path': 'rosario/', 
    'output_image_path': 'semantic_results/',
    'inference_size': (480, 640), 
}

# --- IMAGE LOADING AND PREPROCESSING ---
def load_and_preprocess_image(image_path, device):
    if not os.path.exists(image_path):
        raise FileNotFoundError(f"Input image not found at: {image_path}")

    rgb_img = cv2.imread(image_path)
    if rgb_img is None:
        raise IOError(f"Could not read image at: {image_path}")
        
    rgb_img = cv2.cvtColor(rgb_img, cv2.COLOR_BGR2RGB)
    
    h, w = CONFIG['inference_size']
    original_img_for_viz = rgb_img.copy()
    rgb_img = cv2.resize(rgb_img, (w, h), interpolation=cv2.INTER_AREA)

    rgb_tensor = TF.to_tensor(rgb_img)
    rgb_tensor = rgb_tensor.unsqueeze(0).to(device)
    
    return rgb_tensor, original_img_for_viz

# --- MAIN INFERENCE FUNCTION ---
def main():
    print(f"Using device: {CONFIG['device']}")

    # --- 1. Load Model ---
    print("Loading U-Net model with EfficientNet-B3 encoder...")
    model = smp.Unet(
        encoder_name="efficientnet-b3",
        encoder_weights=None, 
        in_channels=3,
        classes=CONFIG['num_classes'],
    )
    model = model.to(CONFIG['device'])

    if not os.path.exists(CONFIG['model_path']):
        raise FileNotFoundError(f"Trained model weights not found at: {CONFIG['model_path']}")

    model.load_state_dict(torch.load(CONFIG['model_path'], map_location=CONFIG['device']))
    model.eval() 
    print(f"Model weights loaded from {CONFIG['model_path']}")

    # --- 2. Gather Images ---
    # Coleta e ordena as imagens para garantir consistência
    image_files = sorted([f for f in os.listdir(CONFIG['input_image_path']) 
                          if f.endswith(('.jpg', '.png'))])
    
    # Limita a 6 imagens como solicitado
    image_files = image_files[:6]
    num_images = len(image_files)
    
    if num_images == 0:
        print("Nenhuma imagem encontrada no diretório.")
        return

    # Listas para armazenar os pares de resultados
    results_rgb = []
    results_mask = []

    # --- 3. Perform Inference on All Images ---
    for image in image_files:
        img_path = os.path.join(CONFIG['input_image_path'], image)
        print(f"Processing: {image}...")
        
        input_tensor, original_rgb_img = load_and_preprocess_image(img_path, CONFIG['device'])
        
        with torch.no_grad():
            output = model(input_tensor)
            
        pred_mask = torch.argmax(output, dim=1).squeeze(0).cpu().numpy()
        
        orig_h, orig_w, _ = original_rgb_img.shape
        pred_mask = cv2.resize(pred_mask.astype(np.uint8), (orig_w, orig_h), interpolation=cv2.INTER_NEAREST)
        
        results_rgb.append(original_rgb_img)
        results_mask.append(pred_mask)

    # --- 4. Visualize and Save Full Grid for Paper ---
    print("Generating paper-ready figure...")
    
    # Define a figura: 2 linhas, N colunas. figsize ajustável dependendo da proporção da imagem
    # wspace e hspace em 0.02 garantem que quase não haja espaço perdido entre as imagens
    fig, axes = plt.subplots(2, num_images, figsize=(2.5 * num_images, 4.5), dpi=300, 
                             gridspec_kw={'wspace': 0.02, 'hspace': 0.02})

    cmap = plt.get_cmap('tab10', CONFIG['num_classes'])

    for i in range(num_images):
        # Linha 0: Imagens RGB de Entrada
        axes[0, i].imshow(results_rgb[i])
        axes[0, i].axis('off') # Remove eixos para economizar espaço
        
        # Linha 1: Máscaras Preditas
        im = axes[1, i].imshow(results_mask[i], cmap=cmap, vmin=0, vmax=CONFIG['num_classes']-1)
        axes[1, i].axis('off')

    # Ajusta o layout principal e adiciona a barra de cores (Colorbar)
    # A barra é posicionada na parte inferior (horizontal) para não gastar espaço lateral valioso do artigo
    plt.subplots_adjust(bottom=0.15) 
    cbar_ax = fig.add_axes([0.15, 0.05, 0.7, 0.03]) # [left, bottom, width, height]
    
    cbar = fig.colorbar(im, cax=cbar_ax, orientation='horizontal', ticks=np.arange(CONFIG['num_classes']))
    
    # Configura os nomes das classes na barra de cores
    class_labels = [CONFIG['class_names'][i] for i in range(CONFIG['num_classes'])]
    cbar.ax.set_xticklabels(class_labels, fontsize=10)
    cbar.outline.set_visible(False) # Deixa a barra mais "limpa" visualmente

    # Cria diretório se não existir e salva
    os.makedirs(CONFIG['output_image_path'], exist_ok=True)
    final_output_path = os.path.join(CONFIG['output_image_path'], "paper_figure_semantic_grid.png")
    
    # bbox_inches='tight' arranca margens em branco excedentes
    # pad_inches controla o "respiro" nas bordas da imagem final
    plt.savefig(final_output_path, dpi=300, bbox_inches='tight', pad_inches=0.01)
    print(f"Final figure saved successfully at: {final_output_path}")

if __name__ == '__main__':
    main()