| 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) |
| """ |
| |
| |
| 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}") |
| |
| |
| gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) |
| |
| |
| _, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV) |
| |
| |
| kernel = np.ones((10, 10), np.uint8) |
| |
| |
| dilated = cv2.dilate(binary, kernel, iterations=1) |
| |
| |
| horizontal_kernel = np.ones((1, 40), np.uint8) |
| |
| |
| dilated_horizontal = cv2.dilate(dilated, horizontal_kernel, iterations=1) |
| |
| |
| height, width = dilated_horizontal.shape |
| |
| |
| 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) |
| |
| |
| |
| 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: |
| current_group.append(cut_lines[i]) |
| else: |
| |
| middle_line = current_group[len(current_group)//2] |
| separation_lines.append(middle_line) |
| current_group = [cut_lines[i]] |
| |
| |
| if current_group: |
| middle_line = current_group[len(current_group)//2] |
| separation_lines.append(middle_line) |
| |
| |
| filtered_separation_lines = [] |
| for line_y in separation_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") |
| |
| |
| segments = [] |
| start_y = 0 |
| |
| for line_y in separation_lines: |
| if line_y > start_y + 20: |
| segments.append((start_y, line_y)) |
| start_y = line_y + 1 |
| |
| |
| if start_y < height - 20: |
| segments.append((start_y, height)) |
| |
| |
| visualization = img.copy() |
| for line_y in separation_lines: |
| cv2.line(visualization, (0, line_y), (width-1, line_y), (0, 0, 255), 3) |
| |
| |
| 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 |
| """ |
| |
| |
| image_files = glob.glob(os.path.join(input_dir, "*.png")) |
| image_files.sort() |
| |
| 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) |
| |
| |
| 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}") |
| |
| |
| 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 |
| |
| |
| 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(): |
| |
| 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() |