File size: 10,199 Bytes
a98fc5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import cv2
import numpy as np
import os
from pathlib import Path
import glob

def process_single_image(image_path):
    """
    Process a single image and return segmentation info
    
    Args:
        image_path (str): Path to the input image
        
    Returns:
        tuple: (segments, visualization_image)
    """
    
    # Read the image
    img = cv2.imread(image_path)
    if img is None:
        print(f"Error: Could not read image from {image_path}")
        return None, None
    
    print(f"Processing: {Path(image_path).name}")
    
    # Convert to grayscale
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    
    # Apply binary thresholding (binarization)
    _, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV)
    
    # Create morphological kernel for dilation (10px)
    kernel = np.ones((10, 10), np.uint8)
    
    # Apply dilation to expand black regions
    dilated = cv2.dilate(binary, kernel, iterations=1)
    
    # Create horizontal kernel for connecting broken lines (40px horizontal)
    horizontal_kernel = np.ones((1, 40), np.uint8)
    
    # Apply horizontal dilation to connect broken line segments
    dilated_horizontal = cv2.dilate(dilated, horizontal_kernel, iterations=1)
    
    # Get image dimensions
    height, width = dilated_horizontal.shape
    
    # Find lines where black pixels exceed 70% of width
    cut_lines = []
    threshold = width * 0.7
    
    for y in range(height):
        black_pixel_count = np.sum(dilated_horizontal[y, :] > 0)
        if black_pixel_count >= threshold:
            cut_lines.append(y)
    
    # Group consecutive cut lines to find actual separation boundaries
    # Also enforce minimum 600px distance between separation lines
    separation_lines = []
    if cut_lines:
        current_group = [cut_lines[0]]
        
        for i in range(1, len(cut_lines)):
            if cut_lines[i] - cut_lines[i-1] <= 5:  # Lines within 5 pixels are considered same group
                current_group.append(cut_lines[i])
            else:
                # End of current group, add middle line
                middle_line = current_group[len(current_group)//2]
                separation_lines.append(middle_line)
                current_group = [cut_lines[i]]
        
        # Don't forget the last group
        if current_group:
            middle_line = current_group[len(current_group)//2]
            separation_lines.append(middle_line)
    
    # Filter separation lines to ensure minimum 600px distance
    filtered_separation_lines = []
    for line_y in separation_lines:
        # Check if this line is at least 600px away from all previously accepted lines
        valid = True
        for prev_line in filtered_separation_lines:
            if abs(line_y - prev_line) < 300:
                valid = False
                break
        
        if valid:
            filtered_separation_lines.append(line_y)
    
    separation_lines = filtered_separation_lines
    
    print(f"Found {len(separation_lines)} separation lines")
    
    # Define segment boundaries
    segments = []
    start_y = 0
    
    for line_y in separation_lines:
        if line_y > start_y + 20:  # Minimum segment height of 20 pixels
            segments.append((start_y, line_y))
        start_y = line_y + 1
    
    # Add the last segment
    if start_y < height - 20:
        segments.append((start_y, height))
    
    # Create visualization showing cut lines
    visualization = img.copy()
    for line_y in separation_lines:
        cv2.line(visualization, (0, line_y), (width-1, line_y), (0, 0, 255), 3)
    
    # Add text showing number of segments
    cv2.putText(visualization, f'Segments: {len(segments)}', (10, 30), 
                cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
    
    return segments, visualization

def save_segments(image_path, segments, output_dir, add_error_suffix=False):
    """
    Save image segments
    
    Args:
        image_path (str): Original image path
        segments (list): List of (start_y, end_y) tuples
        output_dir (str): Output directory
        add_error_suffix (bool): Whether to add 'err' suffix
    """
    
    img = cv2.imread(image_path)
    base_name = Path(image_path).stem
    
    os.makedirs(output_dir, exist_ok=True)
    
    for i, (start_y, end_y) in enumerate(segments):
        segment = img[start_y:end_y, :]
        
        if add_error_suffix:
            output_path = os.path.join(output_dir, f"{base_name}_segment_{i}_err.png")
        else:
            output_path = os.path.join(output_dir, f"{base_name}_segment_{i}.png")
            
        cv2.imwrite(output_path, segment)
    
    suffix = "_err" if add_error_suffix else ""
    print(f"Saved {len(segments)} segments with suffix '{suffix}'")

def batch_process_images(input_dir, output_dir="batch_segmented_images"):
    """
    Batch process all images in the input directory with navigation support
    
    Args:
        input_dir (str): Directory containing input images
        output_dir (str): Directory to save output segments
    """
    
    # Find all PNG files in the input directory
    image_files = glob.glob(os.path.join(input_dir, "*.png"))
    image_files.sort()  # Sort to process in order
    
    if not image_files:
        print(f"No PNG files found in {input_dir}")
        return
    
    print(f"Found {len(image_files)} images to process")
    print("Controls:")
    print("  SPACE: Accept and save segments normally")
    print("  Any other key: Save segments with '_err' suffix")
    print("  UP ARROW: Go to previous image")
    print("  DOWN ARROW: Go to next image")
    print("  ESC: Exit")
    print("=" * 50)
    
    # Cache processed results to avoid reprocessing when navigating
    processed_cache = {}
    
    # Statistics
    results = {}  # image_path -> "accepted" | "error" | "skipped" | None
    
    current_index = 0
    
    while current_index < len(image_files):
        image_path = image_files[current_index]
        filename = Path(image_path).name
        
        print(f"\nViewing {current_index + 1}/{len(image_files)}: {filename}")
        
        # Check if already processed
        if image_path in processed_cache:
            segments, visualization = processed_cache[image_path]
        else:
            # Process the image
            segments, visualization = process_single_image(image_path)
            
            if segments is None:
                print(f"Failed to process {image_path}")
                current_index += 1
                continue
            
            if len(segments) == 0:
                print(f"No segments found in {image_path}")
                current_index += 1
                continue
            
            # Cache the result
            processed_cache[image_path] = (segments, visualization)
        
        # Resize visualization for display if too large
        display_viz = visualization.copy()
        height, width = display_viz.shape[:2]
        if height > 2000:
            scale = 2000 / height
            new_width = int(width * scale)
            display_viz = cv2.resize(display_viz, (new_width, 2000))
        
        # Add navigation info to display
        nav_text = f"[{current_index + 1}/{len(image_files)}] {filename}"
        status_text = ""
        if image_path in results:
            if results[image_path] == "accepted":
                status_text = " [ACCEPTED]"
            elif results[image_path] == "error":
                status_text = " [ERROR]"
            elif results[image_path] == "skipped":
                status_text = " [SKIPPED]"
        
        cv2.putText(display_viz, nav_text + status_text, (10, height - 20 if height <= 800 else 780), 
                    cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2)
        
        # Show the visualization with cut lines
        window_title = 'SPACE=Accept | Other=Error | UP/DOWN=Navigate | ESC=Exit'
        cv2.imshow(window_title, display_viz)
        
        # Wait for user input
        key = cv2.waitKey(0) & 0xFF
        
        if key == 27:  # ESC key - exit
            print("Exiting...")
            break
        elif key == 82 or key == 0:  # UP arrow key (82 on Linux, 0 on some systems)
            if current_index > 0:
                current_index -= 1
                print("Going to previous image")
            else:
                print("Already at first image")
        elif key == 84 or key == 1:  # DOWN arrow key (84 on Linux, 1 on some systems)
            current_index += 1
            print("Going to next image")
        elif key == 32:  # SPACE key - accept
            print("Accepted - saving normal segments")
            save_segments(image_path, segments, output_dir, add_error_suffix=False)
            results[image_path] = "accepted"
            current_index += 1
        else:
            print(f"Marked as error - saving with '_err' suffix (key code: {key})")
            save_segments(image_path, segments, output_dir, add_error_suffix=True)
            results[image_path] = "error"
            current_index += 1
    
    cv2.destroyAllWindows()
    
    # Count final results
    accepted_count = sum(1 for v in results.values() if v == "accepted")
    error_count = sum(1 for v in results.values() if v == "error")
    skipped_count = len(image_files) - len(results)
    
    print("\n" + "=" * 50)
    print("Batch processing complete!")
    print(f"Total images: {len(image_files)}")
    print(f"Accepted: {accepted_count}")
    print(f"Marked as error: {error_count}")
    print(f"Skipped: {skipped_count}")
    print(f"Output directory: {output_dir}")

def main():
    # Set input directory to the extracted pages
    input_dir = os.path.join(os.path.dirname(__file__), "extracted_pages")
    output_dir = "batch_segmented_images"
    
    if not os.path.exists(input_dir):
        print(f"Error: Input directory {input_dir} not found")
        return
    
    print("Starting batch image processing...")
    print(f"Input directory: {input_dir}")
    print(f"Output directory: {output_dir}")
    
    batch_process_images(input_dir, output_dir)

if __name__ == "__main__":
    main()