| 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 |
| """ |
| |
| |
| 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}") |
| |
| |
| 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) |
| |
| |
| 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() |
| |
| |
| height, width = dilated_horizontal.shape |
| |
| |
| cut_lines = [] |
| threshold = width * 0.8 |
| |
| for y in range(height): |
| |
| 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.") |
| |
| 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 |
| |
| |
| |
| 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) < 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}") |
| |
| |
| os.makedirs(output_dir, exist_ok=True) |
| |
| |
| base_name = Path(image_path).stem |
| |
| |
| 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)) |
| |
| print(f"Creating {len(segments)} segments") |
| |
| |
| 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}") |
| |
| |
| 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) |
| |
| |
| 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(): |
| |
| 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() |