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()