File size: 13,488 Bytes
a98fc5a |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 |
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)}")
# Store cut lines for each image
self.cut_lines = {} # image_path -> list of y coordinates
self.current_image = None
self.display_image = None
self.original_height = 0
self.original_width = 0
self.scale_factor = 1.0
# Mouse interaction state
self.mouse_y = 0
# Window name
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 []
# Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Apply binary thresholding
_, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV)
# Create morphological kernel for dilation (10px)
kernel = np.ones((10, 10), np.uint8)
dilated = cv2.dilate(binary, kernel, iterations=1)
# Create horizontal kernel for connecting broken lines (40px horizontal)
horizontal_kernel = np.ones((1, 40), np.uint8)
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
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)
# Filter separation lines to ensure minimum 300px distance
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]
# Initialize cut lines if not already loaded
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
# Create display copy
self.display_image = self.current_image.copy()
# Scale image if too large
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
# Draw cut lines in red
image_path = self.image_files[self.current_index]
if image_path in self.cut_lines:
for line_y in self.cut_lines[image_path]:
# Scale the line position for display
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)
# Add info text
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:
# Add cut line
self.add_cut_line(y)
elif event == cv2.EVENT_RBUTTONDOWN:
# Delete nearest cut line - consume the event to prevent context menu
self.delete_nearest_cut_line(y)
return True # Consume the event
def add_cut_line(self, display_y):
"""Add a cut line at the specified display position"""
# Convert display coordinates to original image coordinates
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] = []
# Add the line and sort
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
# Find nearest cut line
cut_lines = self.cut_lines[image_path]
nearest_line = min(cut_lines, key=lambda line: abs(line - original_y))
# Only delete if within reasonable distance (50 pixels)
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)
# First, remove any existing segments for this image to avoid orphaned files
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)
# Generate segments from cut lines
segments = []
cut_lines = sorted(self.cut_lines[image_path])
start_y = 0
for line_y in cut_lines:
if line_y > start_y + 20: # Minimum segment height
segments.append((start_y, line_y))
start_y = line_y + 1
# Add final segment
if start_y < img.shape[0] - 20:
segments.append((start_y, img.shape[0]))
# Save segments
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}")
# Also save cut lines data
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"""
# Auto-save current image before navigating
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: # ESC - exit
# Auto-save current image before exiting
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: # LEFT arrow
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: # RIGHT arrow
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'): # S - save
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
# Get starting image number from user
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() |