Spaces:
Running
Running
moved met
Browse files
comic_panel_extractor/border_panel_extractor.py
CHANGED
|
@@ -12,7 +12,7 @@ import cv2
|
|
| 12 |
|
| 13 |
from .config import Config
|
| 14 |
from .image_processor import ImageProcessor
|
| 15 |
-
from .utils import remove_duplicate_boxes, count_panels_inside
|
| 16 |
|
| 17 |
class BorderPanelExtractor:
|
| 18 |
"""
|
|
@@ -202,47 +202,6 @@ class BorderPanelExtractor:
|
|
| 202 |
print(f"✅ Found {abs(len(unique_boxes) - len(boxes))} duplicates")
|
| 203 |
return unique_boxes
|
| 204 |
|
| 205 |
-
def extend_boxes_to_image_border(self, boxes, image_shape):
|
| 206 |
-
"""
|
| 207 |
-
Extends any side of a bounding box to the image border if it's close enough.
|
| 208 |
-
|
| 209 |
-
:param boxes: List of (x1, y1, x2, y2) tuples.
|
| 210 |
-
:param image_shape: (height, width) of the image.
|
| 211 |
-
:param threshold: Pixel threshold to snap to border.
|
| 212 |
-
:return: List of adjusted boxes.
|
| 213 |
-
"""
|
| 214 |
-
if not boxes:
|
| 215 |
-
return boxes
|
| 216 |
-
extended_boxes = [list(box) for box in boxes]
|
| 217 |
-
height, width = image_shape[:2]
|
| 218 |
-
adjusted_boxes = []
|
| 219 |
-
|
| 220 |
-
width_threshold = min(x2 - x1 for x1, y1, x2, y2 in extended_boxes)
|
| 221 |
-
height_threshold = min(y2 - y1 for x1, y1, x2, y2 in extended_boxes)
|
| 222 |
-
|
| 223 |
-
# width_threshold = self.config.min_width_ratio * width
|
| 224 |
-
# height_threshold = self.config.min_height_ratio * height
|
| 225 |
-
|
| 226 |
-
percent_threshold=0.8
|
| 227 |
-
for x1, y1, x2, y2 in boxes:
|
| 228 |
-
box_width = x2 - x1
|
| 229 |
-
box_height = y2 - y1
|
| 230 |
-
|
| 231 |
-
# Snap if close to left or top
|
| 232 |
-
if abs(x1 - 0) <= width_threshold or box_width >= percent_threshold * width:
|
| 233 |
-
x1 = 0
|
| 234 |
-
if abs(y1 - 0) <= height_threshold or box_height >= percent_threshold * height:
|
| 235 |
-
y1 = 0
|
| 236 |
-
|
| 237 |
-
# Snap if close to right or bottom
|
| 238 |
-
if abs(x2 - width) <= width_threshold or box_width >= percent_threshold * width:
|
| 239 |
-
x2 = width
|
| 240 |
-
if abs(y2 - height) <= height_threshold or box_height >= percent_threshold * height:
|
| 241 |
-
y2 = height
|
| 242 |
-
adjusted_boxes.append((x1, y1, x2, y2))
|
| 243 |
-
|
| 244 |
-
return adjusted_boxes
|
| 245 |
-
|
| 246 |
def remove_swallow_boxes(self, boxes):
|
| 247 |
filtered_boxes = []
|
| 248 |
|
|
@@ -295,7 +254,7 @@ class BorderPanelExtractor:
|
|
| 295 |
|
| 296 |
accepted_boxes = remove_duplicate_boxes(accepted_boxes)
|
| 297 |
|
| 298 |
-
accepted_boxes =
|
| 299 |
|
| 300 |
accepted_boxes = remove_duplicate_boxes(accepted_boxes)
|
| 301 |
|
|
|
|
| 12 |
|
| 13 |
from .config import Config
|
| 14 |
from .image_processor import ImageProcessor
|
| 15 |
+
from .utils import remove_duplicate_boxes, count_panels_inside, extend_boxes_to_image_border
|
| 16 |
|
| 17 |
class BorderPanelExtractor:
|
| 18 |
"""
|
|
|
|
| 202 |
print(f"✅ Found {abs(len(unique_boxes) - len(boxes))} duplicates")
|
| 203 |
return unique_boxes
|
| 204 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 205 |
def remove_swallow_boxes(self, boxes):
|
| 206 |
filtered_boxes = []
|
| 207 |
|
|
|
|
| 254 |
|
| 255 |
accepted_boxes = remove_duplicate_boxes(accepted_boxes)
|
| 256 |
|
| 257 |
+
accepted_boxes = extend_boxes_to_image_border(accepted_boxes, original_image.shape, self.config.min_width_ratio, self.config.min_height_ratio)
|
| 258 |
|
| 259 |
accepted_boxes = remove_duplicate_boxes(accepted_boxes)
|
| 260 |
|
comic_panel_extractor/config.py
CHANGED
|
@@ -1,9 +1,15 @@
|
|
| 1 |
from dataclasses import dataclass
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
@dataclass
|
| 4 |
class Config:
|
| 5 |
"""Configuration settings for the comic-to-video pipeline."""
|
|
|
|
| 6 |
input_path: str = ""
|
|
|
|
| 7 |
black_overlay_input_path: str = ""
|
| 8 |
output_folder: str = "temp_dir"
|
| 9 |
distance_threshold: int = 70
|
|
|
|
| 1 |
from dataclasses import dataclass
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
|
| 4 |
+
# Path to this script's directory
|
| 5 |
+
CURRENT_DIR = Path(__file__).parent.resolve()
|
| 6 |
|
| 7 |
@dataclass
|
| 8 |
class Config:
|
| 9 |
"""Configuration settings for the comic-to-video pipeline."""
|
| 10 |
+
org_input_path: str = ""
|
| 11 |
input_path: str = ""
|
| 12 |
+
yolo_model_path: str = (CURRENT_DIR / "best.pt").resolve()
|
| 13 |
black_overlay_input_path: str = ""
|
| 14 |
output_folder: str = "temp_dir"
|
| 15 |
distance_threshold: int = 70
|
comic_panel_extractor/constant.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
INDEX = -1
|
comic_panel_extractor/main.py
CHANGED
|
@@ -10,6 +10,7 @@ from pathlib import Path
|
|
| 10 |
import numpy as np
|
| 11 |
from .border_panel_extractor import BorderPanelExtractor
|
| 12 |
import shutil
|
|
|
|
| 13 |
|
| 14 |
class ComicPanelExtractor:
|
| 15 |
"""Main class that orchestrates the comic panel extraction process."""
|
|
@@ -27,6 +28,18 @@ class ComicPanelExtractor:
|
|
| 27 |
def extract_panels_from_comic(self) -> Tuple[List[np.ndarray], List[PanelData]]:
|
| 28 |
"""Complete pipeline to extract panels from a comic image."""
|
| 29 |
print(f"Starting panel extraction for: {self.config.input_path}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
processed_image_path = self.image_processor.group_colors(self.config.input_path)
|
| 32 |
|
|
|
|
| 10 |
import numpy as np
|
| 11 |
from .border_panel_extractor import BorderPanelExtractor
|
| 12 |
import shutil
|
| 13 |
+
from . import utils
|
| 14 |
|
| 15 |
class ComicPanelExtractor:
|
| 16 |
"""Main class that orchestrates the comic panel extraction process."""
|
|
|
|
| 28 |
def extract_panels_from_comic(self) -> Tuple[List[np.ndarray], List[PanelData]]:
|
| 29 |
"""Complete pipeline to extract panels from a comic image."""
|
| 30 |
print(f"Starting panel extraction for: {self.config.input_path}")
|
| 31 |
+
try:
|
| 32 |
+
# Get original image dimensions
|
| 33 |
+
from PIL import Image
|
| 34 |
+
with Image.open(self.config.input_path) as original_image:
|
| 35 |
+
original_width, original_height = original_image.size
|
| 36 |
+
from .llm_panel_extractor import extract_panel_via_llm
|
| 37 |
+
all_path, detected_boxes, all_processed_boxes = extract_panel_via_llm(self.config.input_path, self.config)
|
| 38 |
+
if utils.box_covered_ratio(all_processed_boxes, (original_width, original_height)) < 0.95:
|
| 39 |
+
print("LLM failed.")
|
| 40 |
+
return None, None, all_path
|
| 41 |
+
except Exception as e:
|
| 42 |
+
print(str(e))
|
| 43 |
|
| 44 |
processed_image_path = self.image_processor.group_colors(self.config.input_path)
|
| 45 |
|
comic_panel_extractor/panel_extractor.py
CHANGED
|
@@ -6,7 +6,7 @@ import cv2
|
|
| 6 |
from dataclasses import dataclass
|
| 7 |
import os
|
| 8 |
import re
|
| 9 |
-
from .utils import remove_duplicate_boxes, count_panels_inside
|
| 10 |
|
| 11 |
@dataclass
|
| 12 |
class PanelData:
|
|
@@ -200,12 +200,10 @@ class PanelExtractor:
|
|
| 200 |
def _filter_panels_by_size(self, panels: List[Tuple[int, int, int, int]], width: int, height: int) -> List[Tuple[int, int, int, int]]:
|
| 201 |
"""Filter panels by size constraints."""
|
| 202 |
new_panel = []
|
| 203 |
-
image_area = width * height
|
| 204 |
|
| 205 |
for x1, y1, x2, y2 in panels:
|
| 206 |
w = x2 - x1 # Corrected
|
| 207 |
h = y2 - y1 # Corrected
|
| 208 |
-
area = w * h
|
| 209 |
|
| 210 |
if (
|
| 211 |
w >= self.config.min_width_ratio * width and
|
|
@@ -247,6 +245,97 @@ class PanelExtractor:
|
|
| 247 |
coords.append(tuple(map(int, match.groups())))
|
| 248 |
return coords
|
| 249 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 250 |
def _save_panels(self, panels: List[Tuple[int, int, int, int]], original: np.ndarray, width: int, height: int) -> Tuple[List[np.ndarray], List[PanelData], List[str]]:
|
| 251 |
"""Save panel images and return panel data."""
|
| 252 |
original_image = cv2.imread(self.config.input_path)
|
|
@@ -301,11 +390,19 @@ class PanelExtractor:
|
|
| 301 |
continue
|
| 302 |
|
| 303 |
# 2. Skip if this panel contains ≥1 other panels
|
| 304 |
-
contained_count = count_panels_inside((x1, y1, x2, y2), already_saved_coords)
|
| 305 |
if contained_count >= 1:
|
| 306 |
print(f"⚠️ Skipping panel #{idx} — contains {contained_count} other panels inside")
|
| 307 |
continue
|
| 308 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 309 |
# Save panel
|
| 310 |
panel_img = original_image[y1:y2, x1:x2]
|
| 311 |
panel_images.append(panel_img)
|
|
|
|
| 6 |
from dataclasses import dataclass
|
| 7 |
import os
|
| 8 |
import re
|
| 9 |
+
from .utils import remove_duplicate_boxes, count_panels_inside, extend_boxes_to_image_border
|
| 10 |
|
| 11 |
@dataclass
|
| 12 |
class PanelData:
|
|
|
|
| 200 |
def _filter_panels_by_size(self, panels: List[Tuple[int, int, int, int]], width: int, height: int) -> List[Tuple[int, int, int, int]]:
|
| 201 |
"""Filter panels by size constraints."""
|
| 202 |
new_panel = []
|
|
|
|
| 203 |
|
| 204 |
for x1, y1, x2, y2 in panels:
|
| 205 |
w = x2 - x1 # Corrected
|
| 206 |
h = y2 - y1 # Corrected
|
|
|
|
| 207 |
|
| 208 |
if (
|
| 209 |
w >= self.config.min_width_ratio * width and
|
|
|
|
| 245 |
coords.append(tuple(map(int, match.groups())))
|
| 246 |
return coords
|
| 247 |
|
| 248 |
+
def limit_coord(self, new_coord, existing_coords):
|
| 249 |
+
"""
|
| 250 |
+
Trim a new panel box from any side to completely avoid overlapping with existing panels.
|
| 251 |
+
|
| 252 |
+
Args:
|
| 253 |
+
new_coord: Tuple (x1, y1, x2, y2) representing the new panel box
|
| 254 |
+
existing_coords: List of tuples [(x1, y1, x2, y2), ...] representing existing panels
|
| 255 |
+
|
| 256 |
+
Returns:
|
| 257 |
+
Tuple (x1, y1, x2, y2) representing the trimmed panel box with no overlaps
|
| 258 |
+
"""
|
| 259 |
+
if not existing_coords:
|
| 260 |
+
return new_coord
|
| 261 |
+
|
| 262 |
+
x1, y1, x2, y2 = new_coord
|
| 263 |
+
|
| 264 |
+
# Ensure valid input coordinates
|
| 265 |
+
if x2 <= x1 or y2 <= y1:
|
| 266 |
+
return new_coord
|
| 267 |
+
|
| 268 |
+
# Keep trimming until no overlaps exist
|
| 269 |
+
current_box = (x1, y1, x2, y2)
|
| 270 |
+
|
| 271 |
+
for existing_box in existing_coords:
|
| 272 |
+
ex1, ey1, ex2, ey2 = existing_box
|
| 273 |
+
cx1, cy1, cx2, cy2 = current_box
|
| 274 |
+
|
| 275 |
+
# Check if current box overlaps with this existing box
|
| 276 |
+
if self.boxes_overlap(current_box, existing_box):
|
| 277 |
+
|
| 278 |
+
# Calculate possible trim options and their resulting box sizes
|
| 279 |
+
trim_options = []
|
| 280 |
+
|
| 281 |
+
# Option 1: Trim from left (move x1 right)
|
| 282 |
+
if cx1 < ex2 and cx2 > ex2:
|
| 283 |
+
new_x1 = ex2
|
| 284 |
+
if new_x1 < cx2: # Ensure valid box
|
| 285 |
+
area = (cx2 - new_x1) * (cy2 - cy1)
|
| 286 |
+
trim_options.append(('left', (new_x1, cy1, cx2, cy2), area))
|
| 287 |
+
|
| 288 |
+
# Option 2: Trim from right (move x2 left)
|
| 289 |
+
if cx2 > ex1 and cx1 < ex1:
|
| 290 |
+
new_x2 = ex1
|
| 291 |
+
if new_x2 > cx1: # Ensure valid box
|
| 292 |
+
area = (new_x2 - cx1) * (cy2 - cy1)
|
| 293 |
+
trim_options.append(('right', (cx1, cy1, new_x2, cy2), area))
|
| 294 |
+
|
| 295 |
+
# Option 3: Trim from top (move y1 down)
|
| 296 |
+
if cy1 < ey2 and cy2 > ey2:
|
| 297 |
+
new_y1 = ey2
|
| 298 |
+
if new_y1 < cy2: # Ensure valid box
|
| 299 |
+
area = (cx2 - cx1) * (cy2 - new_y1)
|
| 300 |
+
trim_options.append(('top', (cx1, new_y1, cx2, cy2), area))
|
| 301 |
+
|
| 302 |
+
# Option 4: Trim from bottom (move y2 up)
|
| 303 |
+
if cy2 > ey1 and cy1 < ey1:
|
| 304 |
+
new_y2 = ey1
|
| 305 |
+
if new_y2 > cy1: # Ensure valid box
|
| 306 |
+
area = (cx2 - cx1) * (new_y2 - cy1)
|
| 307 |
+
trim_options.append(('bottom', (cx1, cy1, cx2, new_y2), area))
|
| 308 |
+
|
| 309 |
+
# Choose the trim option that preserves the largest area
|
| 310 |
+
if trim_options:
|
| 311 |
+
# Sort by area (descending) to keep the largest possible box
|
| 312 |
+
trim_options.sort(key=lambda x: x[2], reverse=True)
|
| 313 |
+
best_option = trim_options[0]
|
| 314 |
+
current_box = best_option[1]
|
| 315 |
+
else:
|
| 316 |
+
# If no valid trim options, return minimal box
|
| 317 |
+
return (cx1, cy1, cx1 + 1, cy1 + 1)
|
| 318 |
+
|
| 319 |
+
return current_box
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
def boxes_overlap(self, box1, box2):
|
| 323 |
+
"""
|
| 324 |
+
Check if two boxes overlap.
|
| 325 |
+
|
| 326 |
+
Args:
|
| 327 |
+
box1, box2: Tuples (x1, y1, x2, y2)
|
| 328 |
+
|
| 329 |
+
Returns:
|
| 330 |
+
Boolean indicating if boxes overlap
|
| 331 |
+
"""
|
| 332 |
+
x1, y1, x2, y2 = box1
|
| 333 |
+
ex1, ey1, ex2, ey2 = box2
|
| 334 |
+
|
| 335 |
+
return not (x2 <= ex1 or x1 >= ex2 or y2 <= ey1 or y1 >= ey2)
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
|
| 339 |
def _save_panels(self, panels: List[Tuple[int, int, int, int]], original: np.ndarray, width: int, height: int) -> Tuple[List[np.ndarray], List[PanelData], List[str]]:
|
| 340 |
"""Save panel images and return panel data."""
|
| 341 |
original_image = cv2.imread(self.config.input_path)
|
|
|
|
| 390 |
continue
|
| 391 |
|
| 392 |
# 2. Skip if this panel contains ≥1 other panels
|
| 393 |
+
contained_count = count_panels_inside((x1, y1, x2, y2), already_saved_coords, height, width)
|
| 394 |
if contained_count >= 1:
|
| 395 |
print(f"⚠️ Skipping panel #{idx} — contains {contained_count} other panels inside")
|
| 396 |
continue
|
| 397 |
|
| 398 |
+
x1, y1, x2, y2 = extend_boxes_to_image_border([(x1, y1, x2, y2)], [height, width], self.config.min_width_ratio, self.config.min_height_ratio)[0]
|
| 399 |
+
x1, y1, x2, y2 = self.limit_coord((x1, y1, x2, y2), already_saved_coords)
|
| 400 |
+
|
| 401 |
+
if not self._filter_panels_by_size(
|
| 402 |
+
[(x1, y1, x2, y2)], width, height
|
| 403 |
+
):
|
| 404 |
+
continue
|
| 405 |
+
|
| 406 |
# Save panel
|
| 407 |
panel_img = original_image[y1:y2, x1:x2]
|
| 408 |
panel_images.append(panel_img)
|
comic_panel_extractor/utils.py
CHANGED
|
@@ -1,69 +1,414 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
def remove_duplicate_boxes(boxes, compare_single=None, iou_threshold=0.7):
|
| 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 |
-
def count_panels_inside(target_box, other_boxes):
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from PIL import Image, ImageDraw
|
| 2 |
+
import imageio.v2 as imageio
|
| 3 |
+
import cv2
|
| 4 |
+
import numpy as np
|
| 5 |
+
from sklearn.cluster import KMeans
|
| 6 |
+
|
| 7 |
def remove_duplicate_boxes(boxes, compare_single=None, iou_threshold=0.7):
|
| 8 |
+
"""
|
| 9 |
+
Removes duplicate or highly overlapping boxes, keeping the larger one.
|
| 10 |
+
:param boxes: List of (x1, y1, x2, y2) boxes.
|
| 11 |
+
:param compare_single: Optional single box to compare against the list.
|
| 12 |
+
:param iou_threshold: IOU threshold to consider as duplicate.
|
| 13 |
+
:return:
|
| 14 |
+
- If compare_single is None: deduplicated list of boxes.
|
| 15 |
+
- If compare_single is provided: tuple (is_duplicate, updated_box_or_none)
|
| 16 |
+
"""
|
| 17 |
+
def compute_iou(boxA, boxB):
|
| 18 |
+
xA = max(boxA[0], boxB[0])
|
| 19 |
+
yA = max(boxA[1], boxB[1])
|
| 20 |
+
xB = min(boxA[2], boxB[2])
|
| 21 |
+
yB = min(boxA[3], boxB[3])
|
| 22 |
+
interArea = max(0, xB - xA) * max(0, yB - yA)
|
| 23 |
+
if interArea == 0:
|
| 24 |
+
return 0.0
|
| 25 |
+
boxAArea = (boxA[2] - boxA[0]) * (boxA[3] - boxA[1])
|
| 26 |
+
boxBArea = (boxB[2] - boxB[0]) * (boxB[3] - boxB[1])
|
| 27 |
+
return interArea / float(boxAArea + boxBArea - interArea)
|
| 28 |
+
|
| 29 |
+
def compute_area(box):
|
| 30 |
+
return (box[2] - box[0]) * (box[3] - box[1])
|
| 31 |
+
|
| 32 |
+
# Single comparison mode
|
| 33 |
+
if compare_single is not None:
|
| 34 |
+
single_area = compute_area(compare_single)
|
| 35 |
+
for existing_box in boxes:
|
| 36 |
+
iou = compute_iou(compare_single, existing_box)
|
| 37 |
+
if iou > iou_threshold:
|
| 38 |
+
existing_area = compute_area(existing_box)
|
| 39 |
+
if single_area > existing_area:
|
| 40 |
+
return True, compare_single # Keep new (larger) box
|
| 41 |
+
else:
|
| 42 |
+
return True, None # Existing box is better, discard new
|
| 43 |
+
return False, compare_single # No overlap found, keep it
|
| 44 |
+
|
| 45 |
+
# Bulk deduplication mode
|
| 46 |
+
unique_boxes = []
|
| 47 |
+
for box in boxes:
|
| 48 |
+
box_area = compute_area(box)
|
| 49 |
+
replaced_existing = False
|
| 50 |
+
|
| 51 |
+
# Check against existing unique boxes
|
| 52 |
+
for i, ubox in enumerate(unique_boxes):
|
| 53 |
+
if compute_iou(box, ubox) > iou_threshold:
|
| 54 |
+
ubox_area = compute_area(ubox)
|
| 55 |
+
# If current box is larger, replace the existing one
|
| 56 |
+
if box_area > ubox_area:
|
| 57 |
+
unique_boxes[i] = box
|
| 58 |
+
replaced_existing = True
|
| 59 |
+
# If existing box is larger or equal, ignore current box
|
| 60 |
+
break
|
| 61 |
+
|
| 62 |
+
# If no overlap found, add the box
|
| 63 |
+
if not replaced_existing and not any(compute_iou(box, ubox) > iou_threshold for ubox in unique_boxes):
|
| 64 |
+
unique_boxes.append(box)
|
| 65 |
+
|
| 66 |
+
print(f"✅ Found {abs(len(unique_boxes) - len(boxes))} duplicates")
|
| 67 |
+
return unique_boxes
|
| 68 |
+
|
| 69 |
+
def count_panels_inside(target_box, other_boxes, height=None, width=None):
|
| 70 |
+
x1a, y1a, x2a, y2a = target_box
|
| 71 |
+
target_area = (x2a - x1a) * (y2a - y1a)
|
| 72 |
+
count = 0
|
| 73 |
+
total_covered_area = 0
|
| 74 |
+
for x1b, y1b, x2b, y2b in other_boxes:
|
| 75 |
+
if x1a <= x1b and y1a <= y1b and x2a >= x2b and y2a >= y2b:
|
| 76 |
+
count += 1
|
| 77 |
+
|
| 78 |
+
# Only apply area threshold check if height and width are provided
|
| 79 |
+
if height is not None and width is not None:
|
| 80 |
+
if total_covered_area / target_area < 0.8:
|
| 81 |
+
return 0
|
| 82 |
+
return count
|
| 83 |
+
|
| 84 |
+
def extend_boxes_to_image_border(boxes, image_shape, min_width_ratio, min_height_ratio):
|
| 85 |
+
"""
|
| 86 |
+
Extends any side of a bounding box to the image border if it's close enough.
|
| 87 |
+
|
| 88 |
+
:param boxes: List of (x1, y1, x2, y2) tuples.
|
| 89 |
+
:param image_shape: (height, width) of the image.
|
| 90 |
+
:param threshold: Pixel threshold to snap to border.
|
| 91 |
+
:return: List of adjusted boxes.
|
| 92 |
+
"""
|
| 93 |
+
if not boxes:
|
| 94 |
+
return boxes
|
| 95 |
+
extended_boxes = [list(box) for box in boxes]
|
| 96 |
+
width, height = image_shape
|
| 97 |
+
adjusted_boxes = []
|
| 98 |
+
|
| 99 |
+
width_threshold = width * min_width_ratio
|
| 100 |
+
height_threshold = height * min_height_ratio
|
| 101 |
+
|
| 102 |
+
# width_threshold = self.config.min_width_ratio * width
|
| 103 |
+
# height_threshold = self.config.min_height_ratio * height
|
| 104 |
+
|
| 105 |
+
percent_threshold=0.8
|
| 106 |
+
for x1, y1, x2, y2 in boxes:
|
| 107 |
+
box_width = x2 - x1
|
| 108 |
+
box_height = y2 - y1
|
| 109 |
+
|
| 110 |
+
# Snap if close to left or top
|
| 111 |
+
if abs(x1 - 0) <= width_threshold or box_width >= percent_threshold * width:
|
| 112 |
+
x1 = 0
|
| 113 |
+
if abs(y1 - 0) <= height_threshold or box_height >= percent_threshold * height:
|
| 114 |
+
y1 = 0
|
| 115 |
+
|
| 116 |
+
# Snap if close to right or bottom
|
| 117 |
+
if abs(x2 - width) <= width_threshold or box_width >= percent_threshold * width:
|
| 118 |
+
x2 = width
|
| 119 |
+
if abs(y2 - height) <= height_threshold or box_height >= percent_threshold * height:
|
| 120 |
+
y2 = height
|
| 121 |
+
adjusted_boxes.append((x1, y1, x2, y2))
|
| 122 |
+
|
| 123 |
+
return adjusted_boxes
|
| 124 |
+
|
| 125 |
+
def draw_black(image_path, accepted_boxes, output_path, stripe = True) -> str:
|
| 126 |
+
orig_pil = Image.fromarray(imageio.imread(image_path))
|
| 127 |
+
width, height = orig_pil.size
|
| 128 |
+
|
| 129 |
+
# Create a global stripe pattern (black and white horizontal stripes)
|
| 130 |
+
stripe_img = Image.new("RGB", (width, height), (255, 255, 255))
|
| 131 |
+
draw = ImageDraw.Draw(stripe_img)
|
| 132 |
+
stripe_height = 10
|
| 133 |
+
|
| 134 |
+
if stripe:
|
| 135 |
+
for y in range(0, height, stripe_height):
|
| 136 |
+
if (y // stripe_height) % 2 == 0:
|
| 137 |
+
draw.rectangle([0, y, width, min(y + stripe_height, height)], fill=(0, 0, 0))
|
| 138 |
+
|
| 139 |
+
# Create a mask where accepted boxes will be applied
|
| 140 |
+
mask = Image.new("L", (width, height), 0)
|
| 141 |
+
mask_draw = ImageDraw.Draw(mask)
|
| 142 |
+
for x1, y1, x2, y2 in accepted_boxes:
|
| 143 |
+
mask_draw.rectangle([x1, y1, x2, y2], fill=255)
|
| 144 |
+
|
| 145 |
+
# Paste the striped image only where mask is white (inside accepted boxes)
|
| 146 |
+
orig_pil.paste(stripe_img, (0, 0), mask)
|
| 147 |
+
|
| 148 |
+
orig_pil.save(output_path)
|
| 149 |
+
return output_path
|
| 150 |
+
|
| 151 |
+
def extend_to_nearby_boxes(boxes, image_shape, min_width_ratio, min_height_ratio):
|
| 152 |
+
"""
|
| 153 |
+
Extends boxes to the edge of any close neighboring box without causing
|
| 154 |
+
unintended merging by using an atomic update approach.
|
| 155 |
+
|
| 156 |
+
A box is represented by (x1, y1, x2, y2).
|
| 157 |
+
"""
|
| 158 |
+
if not boxes:
|
| 159 |
+
return boxes
|
| 160 |
+
|
| 161 |
+
width, height = image_shape
|
| 162 |
+
|
| 163 |
+
width_threshold = width * min_width_ratio
|
| 164 |
+
height_threshold = height * min_height_ratio
|
| 165 |
+
|
| 166 |
+
final_boxes = []
|
| 167 |
+
# For each box, calculate its new coordinates based on the original list
|
| 168 |
+
for i in range(len(boxes)):
|
| 169 |
+
# Start with the original coordinates for the box we're currently processing
|
| 170 |
+
x1, y1, x2, y2 = boxes[i]
|
| 171 |
+
|
| 172 |
+
# These will store the closest boundaries we can extend to,
|
| 173 |
+
# initialized to the image edges.
|
| 174 |
+
closest_left_boundary = 0
|
| 175 |
+
closest_right_boundary = width
|
| 176 |
+
closest_top_boundary = 0
|
| 177 |
+
closest_bottom_boundary = height
|
| 178 |
+
|
| 179 |
+
# Find the closest neighbor on each of the four sides by checking against ALL other boxes
|
| 180 |
+
for j in range(len(boxes)):
|
| 181 |
+
if i == j:
|
| 182 |
+
continue
|
| 183 |
+
|
| 184 |
+
x1_j, y1_j, x2_j, y2_j = boxes[j]
|
| 185 |
+
|
| 186 |
+
# Check for neighbors to the RIGHT of box `i`
|
| 187 |
+
is_vert_overlap = (y1 < y2_j and y2 > y1_j) # Do they overlap vertically?
|
| 188 |
+
is_right_neighbor = (x1_j >= x2) # Is box `j` to the right of `i`?
|
| 189 |
+
if is_vert_overlap and is_right_neighbor:
|
| 190 |
+
closest_right_boundary = min(closest_right_boundary, x1_j)
|
| 191 |
+
|
| 192 |
+
# Check for neighbors to the LEFT of box `i`
|
| 193 |
+
is_left_neighbor = (x2_j <= x1) # Is box `j` to the left of `i`?
|
| 194 |
+
if is_vert_overlap and is_left_neighbor:
|
| 195 |
+
closest_left_boundary = max(closest_left_boundary, x2_j)
|
| 196 |
+
|
| 197 |
+
# Check for neighbors BELOW box `i`
|
| 198 |
+
is_horiz_overlap = (x1 < x2_j and x2 > x1_j) # Do they overlap horizontally?
|
| 199 |
+
is_bottom_neighbor = (y1_j >= y2) # Is box `j` below `i`?
|
| 200 |
+
if is_horiz_overlap and is_bottom_neighbor:
|
| 201 |
+
closest_bottom_boundary = min(closest_bottom_boundary, y1_j)
|
| 202 |
+
|
| 203 |
+
# Check for neighbors ABOVE box `i`
|
| 204 |
+
is_top_neighbor = (y2_j <= y1) # Is box `j` above `i`?
|
| 205 |
+
if is_horiz_overlap and is_top_neighbor:
|
| 206 |
+
closest_top_boundary = max(closest_top_boundary, y2_j)
|
| 207 |
+
|
| 208 |
+
# --- Apply the calculated extensions ---
|
| 209 |
+
|
| 210 |
+
# Extend right if the closest gap on the right is within the threshold
|
| 211 |
+
if 0 < (closest_right_boundary - x2) <= width_threshold:
|
| 212 |
+
x2 = closest_right_boundary
|
| 213 |
+
|
| 214 |
+
# Extend left
|
| 215 |
+
if 0 < (x1 - closest_left_boundary) <= width_threshold:
|
| 216 |
+
x1 = closest_left_boundary
|
| 217 |
+
|
| 218 |
+
# Extend down
|
| 219 |
+
if 0 < (closest_bottom_boundary - y2) <= height_threshold:
|
| 220 |
+
y2 = closest_bottom_boundary
|
| 221 |
+
|
| 222 |
+
# Extend up
|
| 223 |
+
if 0 < (y1 - closest_top_boundary) <= height_threshold:
|
| 224 |
+
y1 = closest_top_boundary
|
| 225 |
+
|
| 226 |
+
final_boxes.append(tuple(map(int, (x1, y1, x2, y2))))
|
| 227 |
+
|
| 228 |
+
return final_boxes
|
| 229 |
+
|
| 230 |
+
def convert_to_grayscale_pil(input_path, output_path):
|
| 231 |
+
with Image.open(input_path) as img:
|
| 232 |
+
gray_img = img.convert("L") # "L" mode = grayscale
|
| 233 |
+
gray_img.save(output_path)
|
| 234 |
+
|
| 235 |
+
return output_path
|
| 236 |
+
|
| 237 |
+
def convert_to_clahe(input_path, output_path):
|
| 238 |
+
# Read image from disk
|
| 239 |
+
image = cv2.imread(input_path)
|
| 240 |
+
|
| 241 |
+
if image is None:
|
| 242 |
+
raise FileNotFoundError(f"Could not read image from path: {input_path}")
|
| 243 |
+
|
| 244 |
+
# Convert to grayscale
|
| 245 |
+
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
|
| 246 |
+
|
| 247 |
+
# Apply CLAHE
|
| 248 |
+
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
|
| 249 |
+
output = clahe.apply(gray)
|
| 250 |
+
|
| 251 |
+
# Save the processed image
|
| 252 |
+
cv2.imwrite(output_path, output)
|
| 253 |
+
|
| 254 |
+
return output_path
|
| 255 |
+
|
| 256 |
+
def convert_to_lab_l(input_path, output_path):
|
| 257 |
+
# Read image from disk
|
| 258 |
+
image = cv2.imread(input_path)
|
| 259 |
+
|
| 260 |
+
if image is None:
|
| 261 |
+
raise FileNotFoundError(f"Could not read image from path: {input_path}")
|
| 262 |
+
|
| 263 |
+
output = cv2.cvtColor(image, cv2.COLOR_BGR2LAB)[:, :, 0]
|
| 264 |
+
|
| 265 |
+
# Save the processed image
|
| 266 |
+
cv2.imwrite(output_path, output)
|
| 267 |
+
|
| 268 |
+
return output_path
|
| 269 |
+
|
| 270 |
+
def convert_to_group_colors(input_path, output_path, num_clusters: int = 5):
|
| 271 |
+
# Load image
|
| 272 |
+
image = Image.open(input_path).convert("RGB")
|
| 273 |
+
np_image = np.array(image)
|
| 274 |
+
h, w = np_image.shape[:2]
|
| 275 |
+
pixels = np_image.reshape(-1, 3)
|
| 276 |
+
|
| 277 |
+
# Run KMeans
|
| 278 |
+
kmeans = KMeans(n_clusters=num_clusters, random_state=42, n_init='auto')
|
| 279 |
+
labels = kmeans.fit_predict(pixels)
|
| 280 |
+
centers = kmeans.cluster_centers_.astype(np.uint8)
|
| 281 |
+
|
| 282 |
+
# Replace pixels with their cluster center color
|
| 283 |
+
clustered_pixels = centers[labels].reshape(h, w, 3)
|
| 284 |
+
|
| 285 |
+
# Save using OpenCV (convert RGB to BGR)
|
| 286 |
+
output = clustered_pixels[:, :, ::-1]
|
| 287 |
+
|
| 288 |
+
# Save the processed image
|
| 289 |
+
cv2.imwrite(output_path, output)
|
| 290 |
+
|
| 291 |
+
return output_path
|
| 292 |
+
|
| 293 |
+
def get_black_white_ratio(image_path: str, threshold: int = 128) -> dict:
|
| 294 |
+
"""
|
| 295 |
+
Calculate the ratio of black and white pixels in a binary image.
|
| 296 |
+
|
| 297 |
+
Args:
|
| 298 |
+
image_path: Path to the image file
|
| 299 |
+
threshold: Threshold value for binarization
|
| 300 |
+
|
| 301 |
+
Returns:
|
| 302 |
+
Dictionary with pixel ratios and counts
|
| 303 |
+
"""
|
| 304 |
+
# Load and process image
|
| 305 |
+
img = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
|
| 306 |
+
if img is None:
|
| 307 |
+
raise FileNotFoundError(f"Image not found: {image_path}")
|
| 308 |
+
|
| 309 |
+
# Convert to binary
|
| 310 |
+
_, binary = cv2.threshold(img, threshold, 255, cv2.THRESH_BINARY)
|
| 311 |
+
|
| 312 |
+
# Calculate ratios
|
| 313 |
+
total_pixels = binary.size
|
| 314 |
+
white_count = np.count_nonzero(binary == 255)
|
| 315 |
+
black_count = total_pixels - white_count
|
| 316 |
+
|
| 317 |
+
return {
|
| 318 |
+
"black_ratio": black_count / total_pixels,
|
| 319 |
+
"white_ratio": white_count / total_pixels,
|
| 320 |
+
"black_count": black_count,
|
| 321 |
+
"white_count": white_count,
|
| 322 |
+
"total_pixels": total_pixels
|
| 323 |
+
}
|
| 324 |
+
|
| 325 |
+
def box_covered_ratio(boxes, image_shape) -> float:
|
| 326 |
+
"""
|
| 327 |
+
Calculate the ratio of area covered by boxes to the image area,
|
| 328 |
+
accounting for overlapping boxes by using a mask.
|
| 329 |
+
|
| 330 |
+
Args:
|
| 331 |
+
boxes (List[Tuple[int, int, int, int]]): List of (x1, y1, x2, y2) boxes.
|
| 332 |
+
image_shape (Tuple[int, int]): (width, height) of the image.
|
| 333 |
+
|
| 334 |
+
Returns:
|
| 335 |
+
float: Ratio between 0 and 1.
|
| 336 |
+
"""
|
| 337 |
+
width, height = image_shape
|
| 338 |
+
image_area = width * height
|
| 339 |
+
|
| 340 |
+
if image_area == 0 or not boxes:
|
| 341 |
+
return 0.0
|
| 342 |
+
|
| 343 |
+
# Create a white mask
|
| 344 |
+
mask = np.ones((height, width), dtype=np.uint8) * 255
|
| 345 |
+
|
| 346 |
+
# Draw black rectangles (panels)
|
| 347 |
+
for x1, y1, x2, y2 in boxes:
|
| 348 |
+
cv2.rectangle(mask, (x1, y1), (x2, y2), color=0, thickness=-1)
|
| 349 |
+
|
| 350 |
+
# Count black pixels
|
| 351 |
+
black_pixels = np.sum(mask == 0)
|
| 352 |
+
|
| 353 |
+
return black_pixels / image_area
|
| 354 |
+
|
| 355 |
+
def find_similar_remaining_regions(boxes, image_shape, debug_image_path, w_t=0.25, h_t=0.25):
|
| 356 |
+
"""
|
| 357 |
+
Find remaining regions not covered by original boxes that match any original box's
|
| 358 |
+
width and height within a given threshold.
|
| 359 |
+
|
| 360 |
+
Args:
|
| 361 |
+
boxes (List[Tuple[int, int, int, int]]): Original (x1, y1, x2, y2) boxes.
|
| 362 |
+
image_shape (Tuple[int, int]): (width, height) of the image.
|
| 363 |
+
debug_image_path (str): Path to save debug image.
|
| 364 |
+
w_t (float): Width threshold (e.g., 0.1 = ±10%)
|
| 365 |
+
h_t (float): Height threshold (e.g., 0.1 = ±10%)
|
| 366 |
+
|
| 367 |
+
Returns:
|
| 368 |
+
Tuple[List[Tuple[int, int, int, int]], np.ndarray]:
|
| 369 |
+
- List of new similar boxes
|
| 370 |
+
- Debug image with overlays
|
| 371 |
+
"""
|
| 372 |
+
width, height = image_shape
|
| 373 |
+
mask = np.ones((height, width), dtype=np.uint8) * 255
|
| 374 |
+
|
| 375 |
+
for x1, y1, x2, y2 in boxes:
|
| 376 |
+
mask[y1:y2, x1:x2] = 0
|
| 377 |
+
|
| 378 |
+
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
| 379 |
+
|
| 380 |
+
if not boxes:
|
| 381 |
+
return []
|
| 382 |
+
|
| 383 |
+
similar_boxes = []
|
| 384 |
+
debug_img = np.full((height, width, 3), 255, dtype=np.uint8)
|
| 385 |
+
|
| 386 |
+
# Draw original boxes in green
|
| 387 |
+
for x1, y1, x2, y2 in boxes:
|
| 388 |
+
cv2.rectangle(debug_img, (x1, y1), (x2, y2), (0, 255, 0), 10)
|
| 389 |
+
|
| 390 |
+
for cnt in contours:
|
| 391 |
+
x, y, w, h = cv2.boundingRect(cnt)
|
| 392 |
+
box = (x, y, x + w, y + h)
|
| 393 |
+
|
| 394 |
+
matched = False
|
| 395 |
+
for x1, y1, x2, y2 in boxes:
|
| 396 |
+
bw = x2 - x1
|
| 397 |
+
bh = y2 - y1
|
| 398 |
+
|
| 399 |
+
width_match = abs(w - bw) / bw <= w_t
|
| 400 |
+
height_match = abs(h - bh) / bh <= h_t
|
| 401 |
+
|
| 402 |
+
if width_match and height_match:
|
| 403 |
+
matched = True
|
| 404 |
+
break
|
| 405 |
+
|
| 406 |
+
if matched:
|
| 407 |
+
similar_boxes.append(box)
|
| 408 |
+
cv2.rectangle(debug_img, (x, y), (x + w, y + h), (255, 0, 0), 10) # Blue: Accepted
|
| 409 |
+
else:
|
| 410 |
+
cv2.rectangle(debug_img, (x, y), (x + w, y + h), (0, 0, 255), 10) # Red: Rejected
|
| 411 |
+
|
| 412 |
+
cv2.imwrite(debug_image_path, debug_img)
|
| 413 |
+
return similar_boxes
|
| 414 |
+
|