|
|
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, add_error_suffix=False): |
|
|
""" |
|
|
Save image segments |
|
|
|
|
|
Args: |
|
|
image_path (str): Original image path |
|
|
segments (list): List of (start_y, end_y) tuples |
|
|
output_dir (str): Output directory |
|
|
add_error_suffix (bool): Whether to add 'err' suffix |
|
|
""" |
|
|
|
|
|
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, :] |
|
|
|
|
|
if add_error_suffix: |
|
|
output_path = os.path.join(output_dir, f"{base_name}_segment_{i}_err.png") |
|
|
else: |
|
|
output_path = os.path.join(output_dir, f"{base_name}_segment_{i}.png") |
|
|
|
|
|
cv2.imwrite(output_path, segment) |
|
|
|
|
|
suffix = "_err" if add_error_suffix else "" |
|
|
print(f"Saved {len(segments)} segments with suffix '{suffix}'") |
|
|
|
|
|
def batch_process_images(input_dir, output_dir="batch_segmented_images"): |
|
|
""" |
|
|
Batch process all images in the input directory with navigation support |
|
|
|
|
|
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("Controls:") |
|
|
print(" SPACE: Accept and save segments normally") |
|
|
print(" Any other key: Save segments with '_err' suffix") |
|
|
print(" UP ARROW: Go to previous image") |
|
|
print(" DOWN ARROW: Go to next image") |
|
|
print(" ESC: Exit") |
|
|
print("=" * 50) |
|
|
|
|
|
|
|
|
processed_cache = {} |
|
|
|
|
|
|
|
|
results = {} |
|
|
|
|
|
current_index = 0 |
|
|
|
|
|
while current_index < len(image_files): |
|
|
image_path = image_files[current_index] |
|
|
filename = Path(image_path).name |
|
|
|
|
|
print(f"\nViewing {current_index + 1}/{len(image_files)}: {filename}") |
|
|
|
|
|
|
|
|
if image_path in processed_cache: |
|
|
segments, visualization = processed_cache[image_path] |
|
|
else: |
|
|
|
|
|
segments, visualization = process_single_image(image_path) |
|
|
|
|
|
if segments is None: |
|
|
print(f"Failed to process {image_path}") |
|
|
current_index += 1 |
|
|
continue |
|
|
|
|
|
if len(segments) == 0: |
|
|
print(f"No segments found in {image_path}") |
|
|
current_index += 1 |
|
|
continue |
|
|
|
|
|
|
|
|
processed_cache[image_path] = (segments, visualization) |
|
|
|
|
|
|
|
|
display_viz = visualization.copy() |
|
|
height, width = display_viz.shape[:2] |
|
|
if height > 2000: |
|
|
scale = 2000 / height |
|
|
new_width = int(width * scale) |
|
|
display_viz = cv2.resize(display_viz, (new_width, 2000)) |
|
|
|
|
|
|
|
|
nav_text = f"[{current_index + 1}/{len(image_files)}] {filename}" |
|
|
status_text = "" |
|
|
if image_path in results: |
|
|
if results[image_path] == "accepted": |
|
|
status_text = " [ACCEPTED]" |
|
|
elif results[image_path] == "error": |
|
|
status_text = " [ERROR]" |
|
|
elif results[image_path] == "skipped": |
|
|
status_text = " [SKIPPED]" |
|
|
|
|
|
cv2.putText(display_viz, nav_text + status_text, (10, height - 20 if height <= 800 else 780), |
|
|
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2) |
|
|
|
|
|
|
|
|
window_title = 'SPACE=Accept | Other=Error | UP/DOWN=Navigate | ESC=Exit' |
|
|
cv2.imshow(window_title, display_viz) |
|
|
|
|
|
|
|
|
key = cv2.waitKey(0) & 0xFF |
|
|
|
|
|
if key == 27: |
|
|
print("Exiting...") |
|
|
break |
|
|
elif key == 82 or key == 0: |
|
|
if current_index > 0: |
|
|
current_index -= 1 |
|
|
print("Going to previous image") |
|
|
else: |
|
|
print("Already at first image") |
|
|
elif key == 84 or key == 1: |
|
|
current_index += 1 |
|
|
print("Going to next image") |
|
|
elif key == 32: |
|
|
print("Accepted - saving normal segments") |
|
|
save_segments(image_path, segments, output_dir, add_error_suffix=False) |
|
|
results[image_path] = "accepted" |
|
|
current_index += 1 |
|
|
else: |
|
|
print(f"Marked as error - saving with '_err' suffix (key code: {key})") |
|
|
save_segments(image_path, segments, output_dir, add_error_suffix=True) |
|
|
results[image_path] = "error" |
|
|
current_index += 1 |
|
|
|
|
|
cv2.destroyAllWindows() |
|
|
|
|
|
|
|
|
accepted_count = sum(1 for v in results.values() if v == "accepted") |
|
|
error_count = sum(1 for v in results.values() if v == "error") |
|
|
skipped_count = len(image_files) - len(results) |
|
|
|
|
|
print("\n" + "=" * 50) |
|
|
print("Batch processing complete!") |
|
|
print(f"Total images: {len(image_files)}") |
|
|
print(f"Accepted: {accepted_count}") |
|
|
print(f"Marked as error: {error_count}") |
|
|
print(f"Skipped: {skipped_count}") |
|
|
print(f"Output directory: {output_dir}") |
|
|
|
|
|
def main(): |
|
|
|
|
|
input_dir = os.path.join(os.path.dirname(__file__), "extracted_pages") |
|
|
output_dir = "batch_segmented_images" |
|
|
|
|
|
if not os.path.exists(input_dir): |
|
|
print(f"Error: Input directory {input_dir} not found") |
|
|
return |
|
|
|
|
|
print("Starting batch image processing...") |
|
|
print(f"Input directory: {input_dir}") |
|
|
print(f"Output directory: {output_dir}") |
|
|
|
|
|
batch_process_images(input_dir, output_dir) |
|
|
|
|
|
if __name__ == "__main__": |
|
|
main() |