File size: 6,949 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
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):
    """
    Save image segments
    
    Args:
        image_path (str): Original image path
        segments (list): List of (start_y, end_y) tuples
        output_dir (str): Output directory
    """
    
    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, :]
        output_path = os.path.join(output_dir, f"{base_name}_segment_{i}.png")
        cv2.imwrite(output_path, segment)
    
    print(f"Saved {len(segments)} segments")

def auto_batch_process_images(input_dir, output_dir="segmented_images"):
    """
    Automatically batch process all images in the input directory without manual approval
    
    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(f"Processing automatically without manual approval...")
    print("=" * 50)
    
    # Statistics
    processed_count = 0
    failed_count = 0
    total_segments = 0
    
    for i, image_path in enumerate(image_files, 1):
        filename = Path(image_path).name
        print(f"\nProcessing {i}/{len(image_files)}: {filename}")
        
        # Process the image
        segments, visualization = process_single_image(image_path)
        
        if segments is None:
            print(f"Failed to process {image_path}")
            failed_count += 1
            continue
        
        if len(segments) == 0:
            print(f"No segments found in {image_path}")
            failed_count += 1
            continue
        
        # Automatically save segments
        save_segments(image_path, segments, output_dir)
        processed_count += 1
        total_segments += len(segments)
        
        print(f"Successfully processed with {len(segments)} segments")
    
    print("\n" + "=" * 50)
    print("Automatic batch processing complete!")
    print(f"Total images: {len(image_files)}")
    print(f"Successfully processed: {processed_count}")
    print(f"Failed: {failed_count}")
    print(f"Total segments created: {total_segments}")
    print(f"Output directory: {output_dir}")

def main():
    # Set input directory to the extracted pages
    input_dir = str(Path(__file__).parent / "extracted_pages")
    output_dir = "segmented_images"
    
    if not os.path.exists(input_dir):
        print(f"Error: Input directory {input_dir} not found")
        return
    
    print("Starting automatic batch image processing...")
    print(f"Input directory: {input_dir}")
    print(f"Output directory: {output_dir}")
    
    auto_batch_process_images(input_dir, output_dir)

if __name__ == "__main__":
    main()