|
|
import cv2 |
|
|
import numpy as np |
|
|
import os |
|
|
from pathlib import Path |
|
|
import glob |
|
|
import json |
|
|
|
|
|
class SegmentationEditor: |
|
|
def __init__(self, input_dir, output_dir="edited_segmented_images", start_index=0): |
|
|
self.input_dir = input_dir |
|
|
self.output_dir = output_dir |
|
|
self.image_files = sorted(glob.glob(os.path.join(input_dir, "*.png"))) |
|
|
self.current_index = start_index |
|
|
|
|
|
if not self.image_files: |
|
|
raise ValueError(f"No PNG files found in {input_dir}") |
|
|
|
|
|
if start_index >= len(self.image_files): |
|
|
raise ValueError(f"Starting index {start_index+1} is greater than total images {len(self.image_files)}") |
|
|
|
|
|
|
|
|
self.cut_lines = {} |
|
|
self.current_image = None |
|
|
self.display_image = None |
|
|
self.original_height = 0 |
|
|
self.original_width = 0 |
|
|
self.scale_factor = 1.0 |
|
|
|
|
|
|
|
|
self.mouse_y = 0 |
|
|
|
|
|
|
|
|
self.window_name = "Segmentation Editor - Left/Right: Navigate | Left Click: Add | Right Click: Delete | S: Save | ESC: Exit" |
|
|
|
|
|
print(f"Loaded {len(self.image_files)} images") |
|
|
print(f"Starting from image {start_index+1}: {Path(self.image_files[start_index]).name}") |
|
|
print("Controls:") |
|
|
print(" LEFT/RIGHT ARROW: Navigate between images (auto-saves current)") |
|
|
print(" LEFT CLICK: Add cut line at cursor position") |
|
|
print(" RIGHT CLICK: Delete nearest cut line") |
|
|
print(" S: Manually save current image segments") |
|
|
print(" ESC: Exit (auto-saves current)") |
|
|
|
|
|
def process_single_image(self, image_path): |
|
|
"""Process image to get automatic cut lines (same logic as original)""" |
|
|
img = cv2.imread(image_path) |
|
|
if img is None: |
|
|
return [] |
|
|
|
|
|
|
|
|
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) |
|
|
|
|
|
return sorted(filtered_separation_lines) |
|
|
|
|
|
def load_current_image(self): |
|
|
"""Load and process the current image""" |
|
|
if self.current_index >= len(self.image_files): |
|
|
return False |
|
|
|
|
|
image_path = self.image_files[self.current_index] |
|
|
self.current_image = cv2.imread(image_path) |
|
|
|
|
|
if self.current_image is None: |
|
|
return False |
|
|
|
|
|
self.original_height, self.original_width = self.current_image.shape[:2] |
|
|
|
|
|
|
|
|
if image_path not in self.cut_lines: |
|
|
self.cut_lines[image_path] = self.process_single_image(image_path) |
|
|
|
|
|
self.update_display() |
|
|
return True |
|
|
|
|
|
def update_display(self): |
|
|
"""Update the display image with cut lines""" |
|
|
if self.current_image is None: |
|
|
return |
|
|
|
|
|
|
|
|
self.display_image = self.current_image.copy() |
|
|
|
|
|
|
|
|
max_height = 800 |
|
|
if self.original_height > max_height: |
|
|
self.scale_factor = max_height / self.original_height |
|
|
new_width = int(self.original_width * self.scale_factor) |
|
|
self.display_image = cv2.resize(self.display_image, (new_width, max_height)) |
|
|
else: |
|
|
self.scale_factor = 1.0 |
|
|
|
|
|
|
|
|
image_path = self.image_files[self.current_index] |
|
|
if image_path in self.cut_lines: |
|
|
for line_y in self.cut_lines[image_path]: |
|
|
|
|
|
display_y = int(line_y * self.scale_factor) |
|
|
cv2.line(self.display_image, (0, display_y), |
|
|
(self.display_image.shape[1]-1, display_y), (0, 0, 255), 2) |
|
|
|
|
|
|
|
|
filename = Path(self.image_files[self.current_index]).name |
|
|
info_text = f"[{self.current_index + 1}/{len(self.image_files)}] {filename}" |
|
|
cut_count = len(self.cut_lines.get(self.image_files[self.current_index], [])) |
|
|
info_text += f" | Cut lines: {cut_count}" |
|
|
|
|
|
cv2.putText(self.display_image, info_text, (10, 30), |
|
|
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2) |
|
|
cv2.putText(self.display_image, info_text, (10, 30), |
|
|
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 0), 1) |
|
|
|
|
|
def mouse_callback(self, event, x, y, flags, param): |
|
|
"""Handle mouse events""" |
|
|
self.mouse_y = y |
|
|
|
|
|
if event == cv2.EVENT_LBUTTONDOWN: |
|
|
|
|
|
self.add_cut_line(y) |
|
|
elif event == cv2.EVENT_RBUTTONDOWN: |
|
|
|
|
|
self.delete_nearest_cut_line(y) |
|
|
return True |
|
|
|
|
|
def add_cut_line(self, display_y): |
|
|
"""Add a cut line at the specified display position""" |
|
|
|
|
|
original_y = int(display_y / self.scale_factor) |
|
|
|
|
|
image_path = self.image_files[self.current_index] |
|
|
if image_path not in self.cut_lines: |
|
|
self.cut_lines[image_path] = [] |
|
|
|
|
|
|
|
|
self.cut_lines[image_path].append(original_y) |
|
|
self.cut_lines[image_path].sort() |
|
|
|
|
|
print(f"Added cut line at y={original_y}") |
|
|
self.update_display() |
|
|
|
|
|
def delete_nearest_cut_line(self, display_y): |
|
|
"""Delete the cut line nearest to the specified position""" |
|
|
original_y = int(display_y / self.scale_factor) |
|
|
|
|
|
image_path = self.image_files[self.current_index] |
|
|
if image_path not in self.cut_lines or not self.cut_lines[image_path]: |
|
|
return |
|
|
|
|
|
|
|
|
cut_lines = self.cut_lines[image_path] |
|
|
nearest_line = min(cut_lines, key=lambda line: abs(line - original_y)) |
|
|
|
|
|
|
|
|
if abs(nearest_line - original_y) <= 50: |
|
|
self.cut_lines[image_path].remove(nearest_line) |
|
|
print(f"Deleted cut line at y={nearest_line}") |
|
|
self.update_display() |
|
|
else: |
|
|
print("No cut line near click position") |
|
|
|
|
|
def save_segments(self, image_index=None, silent=False): |
|
|
"""Save segments for specified image (or current image if None)""" |
|
|
if image_index is None: |
|
|
image_index = self.current_index |
|
|
|
|
|
if image_index >= len(self.image_files): |
|
|
return |
|
|
|
|
|
image_path = self.image_files[image_index] |
|
|
if image_path not in self.cut_lines: |
|
|
if not silent: |
|
|
print("No cut lines to save") |
|
|
return |
|
|
|
|
|
img = cv2.imread(image_path) |
|
|
base_name = Path(image_path).stem |
|
|
|
|
|
os.makedirs(self.output_dir, exist_ok=True) |
|
|
|
|
|
|
|
|
existing_segments = glob.glob(os.path.join(self.output_dir, f"{base_name}_segment_*.png")) |
|
|
for old_segment in existing_segments: |
|
|
os.remove(old_segment) |
|
|
|
|
|
|
|
|
segments = [] |
|
|
cut_lines = sorted(self.cut_lines[image_path]) |
|
|
|
|
|
start_y = 0 |
|
|
for line_y in cut_lines: |
|
|
if line_y > start_y + 20: |
|
|
segments.append((start_y, line_y)) |
|
|
start_y = line_y + 1 |
|
|
|
|
|
|
|
|
if start_y < img.shape[0] - 20: |
|
|
segments.append((start_y, img.shape[0])) |
|
|
|
|
|
|
|
|
for i, (start_y, end_y) in enumerate(segments): |
|
|
segment = img[start_y:end_y, :] |
|
|
output_path = os.path.join(self.output_dir, f"{base_name}_segment_{i}.png") |
|
|
cv2.imwrite(output_path, segment) |
|
|
|
|
|
if not silent: |
|
|
print(f"Saved {len(segments)} segments for {base_name}") |
|
|
|
|
|
|
|
|
cut_lines_file = os.path.join(self.output_dir, f"{base_name}_cut_lines.json") |
|
|
with open(cut_lines_file, 'w') as f: |
|
|
json.dump(self.cut_lines[image_path], f) |
|
|
|
|
|
def navigate(self, direction): |
|
|
"""Navigate to previous (-1) or next (1) image with auto-save""" |
|
|
|
|
|
if hasattr(self, 'current_index') and self.current_index < len(self.image_files): |
|
|
current_image_path = self.image_files[self.current_index] |
|
|
if current_image_path in self.cut_lines: |
|
|
self.save_segments(self.current_index, silent=True) |
|
|
|
|
|
new_index = self.current_index + direction |
|
|
if 0 <= new_index < len(self.image_files): |
|
|
self.current_index = new_index |
|
|
return self.load_current_image() |
|
|
return False |
|
|
|
|
|
def run(self): |
|
|
"""Main editor loop""" |
|
|
if not self.load_current_image(): |
|
|
print("Failed to load first image") |
|
|
return |
|
|
|
|
|
cv2.namedWindow(self.window_name, cv2.WINDOW_AUTOSIZE | cv2.WINDOW_GUI_NORMAL) |
|
|
cv2.setMouseCallback(self.window_name, self.mouse_callback) |
|
|
|
|
|
print(f"\nStarting editor with {len(self.image_files)} images") |
|
|
print("=" * 60) |
|
|
|
|
|
while True: |
|
|
cv2.imshow(self.window_name, self.display_image) |
|
|
key = cv2.waitKey(1) & 0xFF |
|
|
|
|
|
if key == 27: |
|
|
|
|
|
current_image_path = self.image_files[self.current_index] |
|
|
if current_image_path in self.cut_lines: |
|
|
self.save_segments(self.current_index, silent=True) |
|
|
print("Exiting editor...") |
|
|
break |
|
|
elif key == 81 or key == 2: |
|
|
if self.navigate(-1): |
|
|
filename = Path(self.image_files[self.current_index]).name |
|
|
print(f"Previous: {filename}") |
|
|
else: |
|
|
print("Already at first image") |
|
|
elif key == 83 or key == 3: |
|
|
if self.navigate(1): |
|
|
filename = Path(self.image_files[self.current_index]).name |
|
|
print(f"Next: {filename}") |
|
|
else: |
|
|
print("Already at last image") |
|
|
elif key == ord('s') or key == ord('S'): |
|
|
self.save_segments() |
|
|
|
|
|
cv2.destroyAllWindows() |
|
|
|
|
|
def main(): |
|
|
input_dir = os.path.join(os.path.dirname(__file__), "extracted_pages") |
|
|
output_dir = "edited_segmented_images" |
|
|
|
|
|
if not os.path.exists(input_dir): |
|
|
print(f"Error: Input directory {input_dir} not found") |
|
|
return |
|
|
|
|
|
|
|
|
try: |
|
|
start_num = int(input("Enter starting image number (1-based): ")) |
|
|
if start_num < 1: |
|
|
print("Error: Image number must be at least 1") |
|
|
return |
|
|
except ValueError: |
|
|
print("Error: Please enter a valid number") |
|
|
return |
|
|
|
|
|
try: |
|
|
editor = SegmentationEditor(input_dir, output_dir, start_index=start_num-1) |
|
|
editor.run() |
|
|
except Exception as e: |
|
|
print(f"Error: {e}") |
|
|
|
|
|
if __name__ == "__main__": |
|
|
main() |