import cv2 import numpy as np import os from pathlib import Path def process_image(image_path, output_dir="segmented_images"): """ Process an image by binarizing it, finding horizontal lines with 80%+ black pixels, and segmenting the image at those lines. Args: image_path (str): Path to the input image output_dir (str): Directory to save segmented images """ # Read the image img = cv2.imread(image_path) if img is None: print(f"Error: Could not read image from {image_path}") return print(f"Processing image: {image_path}") print(f"Original image shape: {img.shape}") # Convert to grayscale gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Apply binary thresholding (binarization) # Using THRESH_BINARY_INV so that text/lines become white (255) and background becomes black (0) _, 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) # Display the binary and dilated images cv2.imshow('Original', img) cv2.imshow('Binary', binary) cv2.imshow('Dilated (10px)', dilated) cv2.imshow('Dilated Horizontal (40px)', dilated_horizontal) cv2.waitKey(0) cv2.destroyAllWindows() # Get image dimensions height, width = dilated_horizontal.shape # Find lines where black pixels exceed 70% of width cut_lines = [] threshold = width * 0.8 for y in range(height): # Count black pixels (value > 0 in dilated_horizontal image, since we used THRESH_BINARY_INV) black_pixel_count = np.sum(dilated_horizontal[y, :] > 0) if black_pixel_count >= threshold: cut_lines.append(y) print(f"Found {len(cut_lines)} rows with 70%+ black pixels") if not cut_lines: print("No cut lines found. Saving original image.") # Create output directory os.makedirs(output_dir, exist_ok=True) base_name = Path(image_path).stem output_path = os.path.join(output_dir, f"{base_name}_segment_0.png") cv2.imwrite(output_path, img) return # 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) < 600: valid = False break if valid: filtered_separation_lines.append(line_y) separation_lines = filtered_separation_lines print(f"Identified {len(separation_lines)} separation lines at rows: {separation_lines}") # Create output directory os.makedirs(output_dir, exist_ok=True) # Segment the image at separation lines base_name = Path(image_path).stem # 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)) print(f"Creating {len(segments)} segments") # Save each segment 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 segment {i}: rows {start_y}-{end_y} to {output_path}") # Also save the processed binary and dilated images for debugging debug_dir = os.path.join(output_dir, "debug") os.makedirs(debug_dir, exist_ok=True) cv2.imwrite(os.path.join(debug_dir, f"{base_name}_binary.png"), binary) cv2.imwrite(os.path.join(debug_dir, f"{base_name}_dilated.png"), dilated) cv2.imwrite(os.path.join(debug_dir, f"{base_name}_dilated_horizontal.png"), dilated_horizontal) # 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), 2) cv2.imwrite(os.path.join(debug_dir, f"{base_name}_with_cutlines.png"), visualization) print(f"Processing complete. Segments saved to {output_dir}") return segments def main(): # Process the specific image image_path = "/data/scientific_research/sign_language/extracted_pages/page_1076.png" if not os.path.exists(image_path): print(f"Error: Image file {image_path} not found") return segments = process_image(image_path) if segments: print(f"\nSummary:") print(f"Original image segmented into {len(segments)} parts") for i, (start_y, end_y) in enumerate(segments): print(f" Segment {i}: rows {start_y}-{end_y} (height: {end_y-start_y}px)") if __name__ == "__main__": main()