santhoshkammari commited on
Commit
226b8b6
·
verified ·
1 Parent(s): cc52c7a

Upload test_split_by_images_folder.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. test_split_by_images_folder.py +295 -0
test_split_by_images_folder.py ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Visualize predictions from trained model on local images folder
3
+ """
4
+ import torch
5
+ from torch.utils.data import Dataset
6
+ import torchvision.transforms as transforms
7
+ from split_model import SplitModel
8
+ from PIL import Image, ImageDraw
9
+ import numpy as np
10
+ import glob
11
+ import os
12
+
13
+ class LocalImageDataset(Dataset):
14
+ """Dataset for loading images from a local folder"""
15
+ def __init__(self, image_folder):
16
+ self.image_paths = sorted(glob.glob(os.path.join(image_folder, "*.png")) +
17
+ glob.glob(os.path.join(image_folder, "*.jpg")) +
18
+ glob.glob(os.path.join(image_folder, "*.jpeg")))
19
+
20
+ if len(self.image_paths) == 0:
21
+ raise ValueError(f"No images found in {image_folder}")
22
+
23
+ self.transform = transforms.Compose([
24
+ transforms.Resize((960, 960)),
25
+ transforms.ToTensor(),
26
+ transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
27
+ ])
28
+
29
+ print(f"Found {len(self.image_paths)} images in {image_folder}")
30
+
31
+ def __len__(self):
32
+ return len(self.image_paths)
33
+
34
+ def __getitem__(self, idx):
35
+ image_path = self.image_paths[idx]
36
+ image = Image.open(image_path).convert('RGB')
37
+ image_transformed = self.transform(image)
38
+ return image_transformed, image, image_path
39
+
40
+ def get_middle_of_groups(binary_array):
41
+ """
42
+ Find groups of consecutive 1's and return only the middle index of each group.
43
+ Example: [0,0,1,1,1,1,1,0,0,1,1,0] -> [0,0,0,0,1,0,0,0,1,0,0]
44
+ """
45
+ result = np.zeros_like(binary_array)
46
+ i = 0
47
+ n = len(binary_array)
48
+
49
+ while i < n:
50
+ if binary_array[i] == 1:
51
+ # Found start of a group
52
+ start = i
53
+ while i < n and binary_array[i] == 1:
54
+ i += 1
55
+ end = i - 1
56
+
57
+ # Get middle index
58
+ middle = (start + end) // 2
59
+ result[middle] = 1
60
+ else:
61
+ i += 1
62
+
63
+ return result
64
+
65
+ def visualize_prediction(model, dataset, idx, device, output_folder, threshold=0.5):
66
+ """Visualize prediction for a single image (no ground truth)"""
67
+ model.eval()
68
+
69
+ # Get sample
70
+ image_tensor, original_image, image_path = dataset[idx]
71
+
72
+ # Predict
73
+ with torch.no_grad():
74
+ image_batch = image_tensor.unsqueeze(0).to(device)
75
+ h_pred, v_pred = model(image_batch) # [1, 480]
76
+
77
+ # Upsample to 960 for visualization
78
+ h_pred = h_pred.repeat_interleave(2, dim=1) # [1, 960]
79
+ v_pred = v_pred.repeat_interleave(2, dim=1) # [1, 960]
80
+
81
+ h_pred = h_pred.squeeze(0).cpu()
82
+ v_pred = v_pred.squeeze(0).cpu()
83
+
84
+ # Apply threshold
85
+ h_binary = (h_pred > threshold).float().numpy()
86
+ v_binary = (v_pred > threshold).float().numpy()
87
+
88
+ # Get only middle of grouped 1's for cleaner visualization
89
+ h_binary_clean = get_middle_of_groups(h_binary)
90
+ v_binary_clean = get_middle_of_groups(v_binary)
91
+
92
+ # Count predictions (use cleaned version)
93
+ h_splits = h_binary_clean.sum()
94
+ v_splits = v_binary_clean.sum()
95
+ pred_rows = int(h_splits) + 1
96
+ pred_cols = int(v_splits) + 1
97
+
98
+ print(f"\nImage {idx}: {os.path.basename(image_path)}")
99
+ print(f" H Splits: {h_splits:.0f} | Pred Rows: {pred_rows}")
100
+ print(f" V Splits: {v_splits:.0f} | Pred Cols: {pred_cols}")
101
+ print(f" Total Cells: {pred_rows * pred_cols}")
102
+ print(f" H pred range: [{h_pred.min():.3f}, {h_pred.max():.3f}]")
103
+ print(f" V pred range: [{v_pred.min():.3f}, {v_pred.max():.3f}]")
104
+
105
+ # Visualize
106
+ W, H = original_image.size
107
+
108
+ # Zoom factor for larger images
109
+ zoom_factor = 1.5
110
+ W_zoomed = int(W * zoom_factor)
111
+ H_zoomed = int(H * zoom_factor)
112
+
113
+ # Resize images for better visibility
114
+ original_zoomed = original_image.resize((W_zoomed, H_zoomed), Image.LANCZOS)
115
+
116
+ # Info panel dimensions
117
+ info_height = 150
118
+ label_height = 60
119
+ padding = 40
120
+
121
+ try:
122
+ from PIL import ImageFont
123
+ font_title = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 32)
124
+ font_text = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 24)
125
+ font_label = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 28)
126
+ except:
127
+ font_title = None
128
+ font_text = None
129
+ font_label = None
130
+
131
+ # Create visualization with 3 images stacked vertically
132
+ total_width = W_zoomed + padding * 2
133
+ total_height = info_height + (label_height + H_zoomed) * 3 + padding * 5
134
+ vis_image = Image.new('RGB', (total_width, total_height), 'white')
135
+ draw = ImageDraw.Draw(vis_image)
136
+
137
+ # Info Panel at top
138
+ info_x = padding
139
+ info_y = padding
140
+
141
+ draw.rectangle([info_x, info_y, total_width - padding, info_y + info_height],
142
+ fill='#e3f2fd', outline='#1565c0', width=4)
143
+
144
+ draw.text((info_x + 20, info_y + 20), "PREDICTED SPLITS", fill='#0d47a1', font=font_title)
145
+ draw.text((info_x + 20, info_y + 70), f"Rows: {pred_rows}", fill='black', font=font_text)
146
+ draw.text((info_x + 20, info_y + 105), f"Columns: {pred_cols}", fill='black', font=font_text)
147
+ draw.text((info_x + 300, info_y + 70), f"H Splits: {int(h_splits)}", fill='#c62828', font=font_text)
148
+ draw.text((info_x + 300, info_y + 105), f"V Splits: {int(v_splits)}", fill='#1565c0', font=font_text)
149
+
150
+ # 1. Original image (top)
151
+ y_pos = info_height + padding * 2
152
+ draw.rectangle([padding, y_pos, total_width - padding, y_pos + label_height],
153
+ fill='#f5f5f5', outline='#666666', width=2)
154
+ draw.text((padding + 20, y_pos + 15), "Original Image", fill='#333333', font=font_label)
155
+
156
+ vis_image.paste(original_zoomed, (padding, y_pos + label_height))
157
+
158
+ # 2. Raw predictions (middle) - with all thick lines
159
+ y_pos = info_height + padding * 3 + label_height + H_zoomed
160
+ draw.rectangle([padding, y_pos, total_width - padding, y_pos + label_height],
161
+ fill='#fff3e0', outline='#ff9800', width=2)
162
+ draw.text((padding + 20, y_pos + 15), "Raw Model Predictions (All 1's)", fill='#e65100', font=font_label)
163
+
164
+ # Create raw prediction image with all 1's (before cleaning)
165
+ raw_pred_image = original_image.copy()
166
+ draw_raw = ImageDraw.Draw(raw_pred_image)
167
+
168
+ # Draw ALL predicted horizontal lines (red) - raw, not cleaned
169
+ for y in range(960):
170
+ if h_binary[y] == 1:
171
+ y_scaled = int(y * H / 960)
172
+ draw_raw.line([(0, y_scaled), (W, y_scaled)], fill='#ff0000', width=2)
173
+
174
+ # Draw ALL predicted vertical lines (blue) - raw, not cleaned
175
+ for x in range(960):
176
+ if v_binary[x] == 1:
177
+ x_scaled = int(x * W / 960)
178
+ draw_raw.line([(x_scaled, 0), (x_scaled, H)], fill='#0000ff', width=2)
179
+
180
+ # Zoom raw prediction image
181
+ raw_pred_zoomed = raw_pred_image.resize((W_zoomed, H_zoomed), Image.LANCZOS)
182
+ vis_image.paste(raw_pred_zoomed, (padding, y_pos + label_height))
183
+
184
+ # 3. Cleaned predictions (bottom) - only middle lines
185
+ y_pos = info_height + padding * 4 + (label_height + H_zoomed) * 2
186
+ draw.rectangle([padding, y_pos, total_width - padding, y_pos + label_height],
187
+ fill='#e3f2fd', outline='#1565c0', width=2)
188
+ draw.text((padding + 20, y_pos + 15), "Cleaned Predictions (Middle Only)", fill='#0d47a1', font=font_label)
189
+
190
+ # Create cleaned prediction image
191
+ pred_image = original_image.copy()
192
+ draw_pred = ImageDraw.Draw(pred_image)
193
+
194
+ # Draw predicted horizontal lines (red) - using cleaned version
195
+ for y in range(960):
196
+ if h_binary_clean[y] == 1:
197
+ y_scaled = int(y * H / 960)
198
+ draw_pred.line([(0, y_scaled), (W, y_scaled)], fill='#ff0000', width=3)
199
+
200
+ # Draw predicted vertical lines (blue) - using cleaned version
201
+ for x in range(960):
202
+ if v_binary_clean[x] == 1:
203
+ x_scaled = int(x * W / 960)
204
+ draw_pred.line([(x_scaled, 0), (x_scaled, H)], fill='#0000ff', width=3)
205
+
206
+ # Zoom prediction image
207
+ pred_zoomed = pred_image.resize((W_zoomed, H_zoomed), Image.LANCZOS)
208
+ vis_image.paste(pred_zoomed, (padding, y_pos + label_height))
209
+
210
+ # Save to output folder
211
+ base_name = os.path.splitext(os.path.basename(image_path))[0]
212
+ output_path = os.path.join(output_folder, f'prediction_{base_name}.png')
213
+ vis_image.save(output_path)
214
+ print(f" Saved: {output_path}")
215
+
216
+ return pred_rows, pred_cols
217
+
218
+ def main():
219
+ import argparse
220
+ parser = argparse.ArgumentParser(description='Visualize table split predictions on local images')
221
+ parser.add_argument('--image-folder', type=str, required=True,
222
+ help='Path to folder containing images')
223
+ parser.add_argument('--output-folder', type=str, default='predictions_output',
224
+ help='Path to folder for saving predictions (default: predictions_output)')
225
+ parser.add_argument('--model-path', type=str, default=None,
226
+ help='Path to trained model checkpoint (if not specified, will search common locations)')
227
+ parser.add_argument('--threshold', type=float, default=0.5,
228
+ help='Threshold for binary predictions (default: 0.5)')
229
+ parser.add_argument('--num-images', type=int, default=-1,
230
+ help='Number of images to process (-1 for all)')
231
+ args = parser.parse_args()
232
+
233
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
234
+ print(f"Device: {device}")
235
+
236
+ # Create output folder
237
+ os.makedirs(args.output_folder, exist_ok=True)
238
+ print(f"Output folder: {args.output_folder}")
239
+
240
+ # Load dataset from local folder
241
+ print(f"\nLoading images from: {args.image_folder}")
242
+ dataset = LocalImageDataset(args.image_folder)
243
+
244
+ # Load model
245
+ print("\nLoading model...")
246
+ model = SplitModel().to(device)
247
+
248
+ # Try to find the best model
249
+ if args.model_path:
250
+ checkpoint_path = args.model_path
251
+ else:
252
+ possible_paths = [
253
+ 'best_split_model.pth',
254
+ '/home/ng6309/datascience/santhosh/experiments/tablet/best_split_model.pth',
255
+ '/home/ng6309/datascience/santhosh/experiments/tablet/runs/tablet_split_20251006_214335/best_split_model.pth',
256
+ ]
257
+
258
+ checkpoint_path = None
259
+ for path in possible_paths:
260
+ if os.path.exists(path):
261
+ checkpoint_path = path
262
+ break
263
+
264
+ if checkpoint_path is None or not os.path.exists(checkpoint_path):
265
+ print("ERROR: No trained model found! Please specify --model-path or ensure model exists in default locations")
266
+ return
267
+
268
+ print(f"Loading checkpoint from: {checkpoint_path}")
269
+ checkpoint = torch.load(checkpoint_path, map_location=device)
270
+ model.load_state_dict(checkpoint['model_state_dict'])
271
+
272
+ print(f"\nModel trained for {checkpoint['epoch']} epochs")
273
+ print(f"Val loss: {checkpoint['val_loss']:.4f}")
274
+ if 'val_h_f1' in checkpoint:
275
+ print(f"Val H F1: {checkpoint['val_h_f1']:.3f}")
276
+ print(f"Val V F1: {checkpoint['val_v_f1']:.3f}")
277
+
278
+ # Determine number of images to process
279
+ num_samples = len(dataset) if args.num_images == -1 else min(args.num_images, len(dataset))
280
+
281
+ # Visualize images
282
+ print("\n" + "="*60)
283
+ print(f"Visualizing predictions for {num_samples} images")
284
+ print("="*60)
285
+
286
+ for idx in range(num_samples):
287
+ pred_rows, pred_cols = visualize_prediction(model, dataset, idx, device, args.output_folder, threshold=args.threshold)
288
+
289
+ print("\n" + "="*60)
290
+ print(f"Completed processing {num_samples} images")
291
+ print(f"All predictions saved to: {args.output_folder}")
292
+ print("="*60)
293
+
294
+ if __name__ == "__main__":
295
+ main()