Spaces:
Running
on
Zero
Running
on
Zero
File size: 30,366 Bytes
ca80d1d 7d583e3 ca80d1d 7d583e3 |
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 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 |
import logging
import numpy as np
import cv2
from PIL import Image
from typing import Dict, Any, Tuple, Optional, List
from dataclasses import dataclass
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
@dataclass
class QualityResult:
"""Result of a quality check."""
score: float # 0-100
passed: bool
issue: str
details: Dict[str, Any]
class QualityChecker:
"""
Automated quality validation system for generated images.
Provides checks for mask coverage, edge continuity, and color harmony.
"""
# Quality thresholds
THRESHOLD_PASS = 70
THRESHOLD_WARNING = 50
def __init__(self, strictness: str = "standard"):
"""
Initialize QualityChecker.
Args:
strictness: Quality check strictness level
"lenient" - Only check fatal issues
"standard" - All checks with moderate thresholds
"strict" - High standards required
"""
self.strictness = strictness
self._set_thresholds()
def _set_thresholds(self):
"""Set quality thresholds based on strictness level."""
if self.strictness == "lenient":
self.min_coverage = 0.03 # 3%
self.min_edge_score = 40
self.min_harmony_score = 40
elif self.strictness == "strict":
self.min_coverage = 0.10 # 10%
self.min_edge_score = 75
self.min_harmony_score = 75
else: # standard
self.min_coverage = 0.05 # 5%
self.min_edge_score = 60
self.min_harmony_score = 60
def check_mask_coverage(self, mask: Image.Image) -> QualityResult:
"""
Verify mask coverage is adequate.
Args:
mask: Grayscale mask image (L mode)
Returns:
QualityResult with coverage analysis
"""
try:
mask_array = np.array(mask.convert('L'))
height, width = mask_array.shape
total_pixels = height * width
# Count foreground pixels
fg_pixels = np.count_nonzero(mask_array > 127)
coverage_ratio = fg_pixels / total_pixels
# Check for isolated small regions (noise)
_, binary = cv2.threshold(mask_array, 127, 255, cv2.THRESH_BINARY)
num_labels, labels, stats, _ = cv2.connectedComponentsWithStats(binary, connectivity=8)
# Count significant regions (> 1% of image)
min_region_size = total_pixels * 0.01
significant_regions = sum(1 for i in range(1, num_labels)
if stats[i, cv2.CC_STAT_AREA] > min_region_size)
# Calculate fragmentation (many small regions = bad)
fragmentation_penalty = max(0, (num_labels - 1 - significant_regions) * 2)
# Score calculation
coverage_score = min(100, coverage_ratio * 200) # 50% coverage = 100 score
final_score = max(0, coverage_score - fragmentation_penalty)
# Determine pass/fail
passed = coverage_ratio >= self.min_coverage and significant_regions >= 1
issue = ""
if coverage_ratio < self.min_coverage:
issue = f"Low foreground coverage ({coverage_ratio:.1%})"
elif significant_regions == 0:
issue = "No significant foreground regions detected"
elif fragmentation_penalty > 20:
issue = f"Fragmented mask with {num_labels - 1} isolated regions"
return QualityResult(
score=final_score,
passed=passed,
issue=issue,
details={
"coverage_ratio": coverage_ratio,
"foreground_pixels": fg_pixels,
"total_regions": num_labels - 1,
"significant_regions": significant_regions
}
)
except Exception as e:
logger.error(f"❌ Mask coverage check failed: {e}")
return QualityResult(score=0, passed=False, issue=str(e), details={})
def check_edge_continuity(self, mask: Image.Image) -> QualityResult:
"""
Check if mask edges are continuous and smooth.
Args:
mask: Grayscale mask image
Returns:
QualityResult with edge analysis
"""
try:
mask_array = np.array(mask.convert('L'))
# Find edges using morphological gradient
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
gradient = cv2.morphologyEx(mask_array, cv2.MORPH_GRADIENT, kernel)
# Get edge pixels
edge_pixels = gradient > 20
edge_count = np.count_nonzero(edge_pixels)
if edge_count == 0:
return QualityResult(
score=50,
passed=False,
issue="No edges detected in mask",
details={"edge_count": 0}
)
# Check edge smoothness using Laplacian
laplacian = cv2.Laplacian(mask_array, cv2.CV_64F)
edge_laplacian = np.abs(laplacian[edge_pixels])
# High Laplacian values indicate jagged edges
smoothness = 100 - min(100, np.std(edge_laplacian) * 0.5)
# Check for gaps in edges
# Dilate and erode to find disconnections
dilated = cv2.dilate(gradient, kernel, iterations=1)
eroded = cv2.erode(dilated, kernel, iterations=1)
gaps = cv2.subtract(dilated, eroded)
gap_ratio = np.count_nonzero(gaps) / max(edge_count, 1)
# Calculate final score
gap_penalty = min(40, gap_ratio * 100)
final_score = max(0, smoothness - gap_penalty)
passed = final_score >= self.min_edge_score
issue = ""
if final_score < self.min_edge_score:
if smoothness < 60:
issue = "Jagged or rough edges detected"
elif gap_ratio > 0.3:
issue = "Discontinuous edges with gaps"
else:
issue = "Poor edge quality"
return QualityResult(
score=final_score,
passed=passed,
issue=issue,
details={
"edge_count": edge_count,
"smoothness": smoothness,
"gap_ratio": gap_ratio
}
)
except Exception as e:
logger.error(f"❌ Edge continuity check failed: {e}")
return QualityResult(score=0, passed=False, issue=str(e), details={})
def check_color_harmony(
self,
foreground: Image.Image,
background: Image.Image,
mask: Image.Image
) -> QualityResult:
"""
Evaluate color harmony between foreground and background.
Args:
foreground: Original foreground image
background: Generated background image
mask: Combination mask
Returns:
QualityResult with harmony analysis
"""
try:
fg_array = np.array(foreground.convert('RGB'))
bg_array = np.array(background.convert('RGB'))
mask_array = np.array(mask.convert('L'))
# Get foreground and background regions
fg_region = mask_array > 127
bg_region = mask_array <= 127
if not np.any(fg_region) or not np.any(bg_region):
return QualityResult(
score=50,
passed=True,
issue="Cannot analyze harmony - insufficient regions",
details={}
)
# Convert to LAB for perceptual analysis
fg_lab = cv2.cvtColor(fg_array, cv2.COLOR_RGB2LAB).astype(np.float32)
bg_lab = cv2.cvtColor(bg_array, cv2.COLOR_RGB2LAB).astype(np.float32)
# Calculate average colors
fg_avg_l = np.mean(fg_lab[fg_region, 0])
fg_avg_a = np.mean(fg_lab[fg_region, 1])
fg_avg_b = np.mean(fg_lab[fg_region, 2])
bg_avg_l = np.mean(bg_lab[bg_region, 0])
bg_avg_a = np.mean(bg_lab[bg_region, 1])
bg_avg_b = np.mean(bg_lab[bg_region, 2])
# Calculate color differences
delta_l = abs(fg_avg_l - bg_avg_l)
delta_a = abs(fg_avg_a - bg_avg_a)
delta_b = abs(fg_avg_b - bg_avg_b)
# Overall color difference (Delta E approximation)
delta_e = np.sqrt(delta_l**2 + delta_a**2 + delta_b**2)
# Score calculation
# Moderate difference is good (20-60 Delta E)
# Too similar or too different is problematic
if delta_e < 10:
harmony_score = 60 # Too similar, foreground may get lost
issue = "Foreground and background colors too similar"
elif delta_e > 80:
harmony_score = 50 # Too different, may look unnatural
issue = "High color contrast may look unnatural"
elif 20 <= delta_e <= 60:
harmony_score = 100 # Ideal range
issue = ""
else:
harmony_score = 80
issue = ""
# Check for extreme contrast (very dark fg on very bright bg or vice versa)
brightness_contrast = abs(fg_avg_l - bg_avg_l)
if brightness_contrast > 100:
harmony_score = max(40, harmony_score - 30)
issue = "Extreme brightness contrast between foreground and background"
passed = harmony_score >= self.min_harmony_score
return QualityResult(
score=harmony_score,
passed=passed,
issue=issue,
details={
"delta_e": delta_e,
"delta_l": delta_l,
"delta_a": delta_a,
"delta_b": delta_b,
"fg_luminance": fg_avg_l,
"bg_luminance": bg_avg_l
}
)
except Exception as e:
logger.error(f"❌ Color harmony check failed: {e}")
return QualityResult(score=0, passed=False, issue=str(e), details={})
def run_all_checks(
self,
foreground: Image.Image,
background: Image.Image,
mask: Image.Image,
combined: Optional[Image.Image] = None
) -> Dict[str, Any]:
"""
Run all quality checks and return comprehensive results.
Args:
foreground: Original foreground image
background: Generated background
mask: Combination mask
combined: Final combined image (optional)
Returns:
Dictionary with all check results and overall score
"""
logger.info("🔍 Running quality checks...")
results = {
"checks": {},
"overall_score": 0,
"passed": True,
"warnings": [],
"errors": []
}
# Run individual checks
coverage_result = self.check_mask_coverage(mask)
results["checks"]["mask_coverage"] = {
"score": coverage_result.score,
"passed": coverage_result.passed,
"issue": coverage_result.issue,
"details": coverage_result.details
}
edge_result = self.check_edge_continuity(mask)
results["checks"]["edge_continuity"] = {
"score": edge_result.score,
"passed": edge_result.passed,
"issue": edge_result.issue,
"details": edge_result.details
}
harmony_result = self.check_color_harmony(foreground, background, mask)
results["checks"]["color_harmony"] = {
"score": harmony_result.score,
"passed": harmony_result.passed,
"issue": harmony_result.issue,
"details": harmony_result.details
}
# Calculate overall score (weighted average)
weights = {
"mask_coverage": 0.4,
"edge_continuity": 0.3,
"color_harmony": 0.3
}
total_score = (
coverage_result.score * weights["mask_coverage"] +
edge_result.score * weights["edge_continuity"] +
harmony_result.score * weights["color_harmony"]
)
results["overall_score"] = round(total_score, 1)
# Determine overall pass/fail
results["passed"] = all([
coverage_result.passed,
edge_result.passed,
harmony_result.passed
])
# Collect warnings and errors
for check_name, check_data in results["checks"].items():
if check_data["issue"]:
if check_data["passed"]:
results["warnings"].append(f"{check_name}: {check_data['issue']}")
else:
results["errors"].append(f"{check_name}: {check_data['issue']}")
logger.info(f"📊 Quality check complete - Score: {results['overall_score']}, Passed: {results['passed']}")
return results
def get_quality_summary(self, results: Dict[str, Any]) -> str:
"""
Generate human-readable quality summary.
Args:
results: Results from run_all_checks
Returns:
Summary string
"""
score = results["overall_score"]
passed = results["passed"]
if score >= 90:
grade = "Excellent"
elif score >= 75:
grade = "Good"
elif score >= 60:
grade = "Acceptable"
elif score >= 40:
grade = "Needs Improvement"
else:
grade = "Poor"
summary = f"Quality: {grade} ({score:.0f}/100)"
if results["errors"]:
summary += f"\nIssues: {'; '.join(results['errors'])}"
elif results["warnings"]:
summary += f"\nNotes: {'; '.join(results['warnings'])}"
return summary
# =========================================================================
# INPAINTING-SPECIFIC QUALITY CHECKS
# =========================================================================
def check_inpainting_edge_continuity(
self,
original: Image.Image,
inpainted: Image.Image,
mask: Image.Image,
ring_width: int = 5
) -> QualityResult:
"""
Check edge continuity at inpainting boundary.
Calculates color distribution similarity between the ring zones
on each side of the mask boundary in Lab color space.
Parameters
----------
original : PIL.Image
Original image before inpainting
inpainted : PIL.Image
Result after inpainting
mask : PIL.Image
Inpainting mask (white = inpainted area)
ring_width : int
Width in pixels for the ring zones on each side
Returns
-------
QualityResult
Edge continuity assessment
"""
try:
# Convert to arrays
orig_array = np.array(original.convert('RGB'))
inpaint_array = np.array(inpainted.convert('RGB'))
mask_array = np.array(mask.convert('L'))
# Find boundary using morphological gradient
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
dilated = cv2.dilate(mask_array, kernel, iterations=ring_width)
eroded = cv2.erode(mask_array, kernel, iterations=ring_width)
# Inner ring (inside inpainted region, near boundary)
inner_ring = (mask_array > 127) & (eroded <= 127)
# Outer ring (outside inpainted region, near boundary)
outer_ring = (mask_array <= 127) & (dilated > 127)
if not np.any(inner_ring) or not np.any(outer_ring):
return QualityResult(
score=50,
passed=True,
issue="Unable to detect boundary rings",
details={"ring_width": ring_width}
)
# Convert to Lab for perceptual comparison
inpaint_lab = cv2.cvtColor(inpaint_array, cv2.COLOR_RGB2LAB).astype(np.float32)
# Get Lab values for each ring from the inpainted image
inner_lab = inpaint_lab[inner_ring]
outer_lab = inpaint_lab[outer_ring]
# Calculate statistics for each channel
inner_mean = np.mean(inner_lab, axis=0)
outer_mean = np.mean(outer_lab, axis=0)
inner_std = np.std(inner_lab, axis=0)
outer_std = np.std(outer_lab, axis=0)
# Calculate differences
mean_diff = np.abs(inner_mean - outer_mean)
std_diff = np.abs(inner_std - outer_std)
# Calculate Delta E (simplified)
delta_e = np.sqrt(np.sum(mean_diff ** 2))
# Score calculation
# Low Delta E = good continuity
# Target: Delta E < 10 is excellent, < 20 is good
if delta_e < 5:
continuity_score = 100
elif delta_e < 10:
continuity_score = 90
elif delta_e < 20:
continuity_score = 75
elif delta_e < 30:
continuity_score = 60
elif delta_e < 50:
continuity_score = 40
else:
continuity_score = max(20, 100 - delta_e)
# Penalize for large std differences (inconsistent textures)
std_penalty = min(20, np.mean(std_diff) * 0.5)
final_score = max(0, continuity_score - std_penalty)
passed = final_score >= 60
issue = ""
if final_score < 60:
if delta_e > 30:
issue = f"Visible color discontinuity at boundary (Delta E: {delta_e:.1f})"
elif np.mean(std_diff) > 20:
issue = "Texture mismatch at boundary"
else:
issue = "Poor edge blending"
return QualityResult(
score=final_score,
passed=passed,
issue=issue,
details={
"delta_e": delta_e,
"mean_diff_l": mean_diff[0],
"mean_diff_a": mean_diff[1],
"mean_diff_b": mean_diff[2],
"std_diff_avg": np.mean(std_diff),
"inner_pixels": np.count_nonzero(inner_ring),
"outer_pixels": np.count_nonzero(outer_ring)
}
)
except Exception as e:
logger.error(f"Inpainting edge continuity check failed: {e}")
return QualityResult(score=0, passed=False, issue=str(e), details={})
def check_inpainting_color_harmony(
self,
original: Image.Image,
inpainted: Image.Image,
mask: Image.Image
) -> QualityResult:
"""
Check color harmony between inpainted region and surrounding area.
Compares color statistics of the inpainted region with adjacent
non-inpainted regions to assess visual coherence.
Parameters
----------
original : PIL.Image
Original image
inpainted : PIL.Image
Inpainted result
mask : PIL.Image
Inpainting mask
Returns
-------
QualityResult
Color harmony assessment
"""
try:
inpaint_array = np.array(inpainted.convert('RGB'))
mask_array = np.array(mask.convert('L'))
# Define regions
inpaint_region = mask_array > 127
# Get adjacent region (dilated mask minus original mask)
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (15, 15))
dilated = cv2.dilate(mask_array, kernel, iterations=2)
adjacent_region = (dilated > 127) & (mask_array <= 127)
if not np.any(inpaint_region) or not np.any(adjacent_region):
return QualityResult(
score=50,
passed=True,
issue="Insufficient regions for comparison",
details={}
)
# Convert to Lab
inpaint_lab = cv2.cvtColor(inpaint_array, cv2.COLOR_RGB2LAB).astype(np.float32)
# Extract region colors
inpaint_colors = inpaint_lab[inpaint_region]
adjacent_colors = inpaint_lab[adjacent_region]
# Calculate color statistics
inpaint_mean = np.mean(inpaint_colors, axis=0)
adjacent_mean = np.mean(adjacent_colors, axis=0)
inpaint_std = np.std(inpaint_colors, axis=0)
adjacent_std = np.std(adjacent_colors, axis=0)
# Color histogram comparison
hist_scores = []
for i in range(3): # L, a, b channels
hist_inpaint, _ = np.histogram(
inpaint_colors[:, i], bins=32, range=(0, 255)
)
hist_adjacent, _ = np.histogram(
adjacent_colors[:, i], bins=32, range=(0, 255)
)
# Normalize
hist_inpaint = hist_inpaint.astype(np.float32) / (np.sum(hist_inpaint) + 1e-6)
hist_adjacent = hist_adjacent.astype(np.float32) / (np.sum(hist_adjacent) + 1e-6)
# Bhattacharyya coefficient (1 = identical, 0 = completely different)
bc = np.sum(np.sqrt(hist_inpaint * hist_adjacent))
hist_scores.append(bc)
avg_hist_score = np.mean(hist_scores)
# Calculate harmony score
mean_diff = np.linalg.norm(inpaint_mean - adjacent_mean)
if mean_diff < 10 and avg_hist_score > 0.8:
harmony_score = 100
elif mean_diff < 20 and avg_hist_score > 0.7:
harmony_score = 85
elif mean_diff < 30 and avg_hist_score > 0.6:
harmony_score = 70
elif mean_diff < 50:
harmony_score = 55
else:
harmony_score = max(30, 100 - mean_diff)
# Boost score if histogram similarity is high
histogram_bonus = (avg_hist_score - 0.5) * 20 # -10 to +10
final_score = max(0, min(100, harmony_score + histogram_bonus))
passed = final_score >= 60
issue = ""
if final_score < 60:
if mean_diff > 40:
issue = "Significant color mismatch with surrounding area"
elif avg_hist_score < 0.5:
issue = "Color distribution differs from context"
else:
issue = "Poor color integration"
return QualityResult(
score=final_score,
passed=passed,
issue=issue,
details={
"mean_color_diff": mean_diff,
"histogram_similarity": avg_hist_score,
"inpaint_luminance": inpaint_mean[0],
"adjacent_luminance": adjacent_mean[0]
}
)
except Exception as e:
logger.error(f"Inpainting color harmony check failed: {e}")
return QualityResult(score=0, passed=False, issue=str(e), details={})
def check_inpainting_artifact_detection(
self,
inpainted: Image.Image,
mask: Image.Image
) -> QualityResult:
"""
Detect common inpainting artifacts like blurriness or color bleeding.
Parameters
----------
inpainted : PIL.Image
Inpainted result
mask : PIL.Image
Inpainting mask
Returns
-------
QualityResult
Artifact detection results
"""
try:
inpaint_array = np.array(inpainted.convert('RGB'))
mask_array = np.array(mask.convert('L'))
inpaint_region = mask_array > 127
if not np.any(inpaint_region):
return QualityResult(
score=50,
passed=True,
issue="No inpainted region detected",
details={}
)
# Extract inpainted region pixels
gray = cv2.cvtColor(inpaint_array, cv2.COLOR_RGB2GRAY)
# Calculate sharpness (Laplacian variance)
laplacian = cv2.Laplacian(gray, cv2.CV_64F)
inpaint_laplacian = laplacian[inpaint_region]
sharpness = np.var(inpaint_laplacian)
# Get surrounding region for comparison
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (10, 10))
dilated = cv2.dilate(mask_array, kernel, iterations=1)
surrounding = (dilated > 127) & (mask_array <= 127)
if np.any(surrounding):
surrounding_laplacian = laplacian[surrounding]
surrounding_sharpness = np.var(surrounding_laplacian)
sharpness_ratio = sharpness / (surrounding_sharpness + 1e-6)
else:
sharpness_ratio = 1.0
# Check for color bleeding (abnormal saturation at edges)
hsv = cv2.cvtColor(inpaint_array, cv2.COLOR_RGB2HSV)
saturation = hsv[:, :, 1]
# Find boundary pixels
boundary_kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
boundary = cv2.morphologyEx(mask_array, cv2.MORPH_GRADIENT, boundary_kernel) > 0
if np.any(boundary):
boundary_saturation = saturation[boundary]
saturation_std = np.std(boundary_saturation)
else:
saturation_std = 0
# Calculate score
sharpness_score = 100
if sharpness_ratio < 0.3:
sharpness_score = 40 # Much blurrier than surroundings
elif sharpness_ratio < 0.6:
sharpness_score = 60
elif sharpness_ratio < 0.8:
sharpness_score = 80
bleeding_penalty = min(20, saturation_std * 0.5)
final_score = max(0, sharpness_score - bleeding_penalty)
passed = final_score >= 60
issue = ""
if sharpness_ratio < 0.5:
issue = "Inpainted region appears blurry"
elif saturation_std > 40:
issue = "Possible color bleeding at edges"
elif final_score < 60:
issue = "Detected visual artifacts"
return QualityResult(
score=final_score,
passed=passed,
issue=issue,
details={
"sharpness": sharpness,
"sharpness_ratio": sharpness_ratio,
"boundary_saturation_std": saturation_std
}
)
except Exception as e:
logger.error(f"Inpainting artifact detection failed: {e}")
return QualityResult(score=0, passed=False, issue=str(e), details={})
def run_inpainting_checks(
self,
original: Image.Image,
inpainted: Image.Image,
mask: Image.Image
) -> Dict[str, Any]:
"""
Run all inpainting-specific quality checks.
Parameters
----------
original : PIL.Image
Original image before inpainting
inpainted : PIL.Image
Result after inpainting
mask : PIL.Image
Inpainting mask
Returns
-------
dict
Comprehensive quality assessment for inpainting
"""
logger.info("Running inpainting quality checks...")
results = {
"checks": {},
"overall_score": 0,
"passed": True,
"warnings": [],
"errors": []
}
# Run inpainting-specific checks
edge_result = self.check_inpainting_edge_continuity(original, inpainted, mask)
results["checks"]["edge_continuity"] = {
"score": edge_result.score,
"passed": edge_result.passed,
"issue": edge_result.issue,
"details": edge_result.details
}
harmony_result = self.check_inpainting_color_harmony(original, inpainted, mask)
results["checks"]["color_harmony"] = {
"score": harmony_result.score,
"passed": harmony_result.passed,
"issue": harmony_result.issue,
"details": harmony_result.details
}
artifact_result = self.check_inpainting_artifact_detection(inpainted, mask)
results["checks"]["artifact_detection"] = {
"score": artifact_result.score,
"passed": artifact_result.passed,
"issue": artifact_result.issue,
"details": artifact_result.details
}
# Calculate overall score (weighted)
weights = {
"edge_continuity": 0.4,
"color_harmony": 0.35,
"artifact_detection": 0.25
}
total_score = (
edge_result.score * weights["edge_continuity"] +
harmony_result.score * weights["color_harmony"] +
artifact_result.score * weights["artifact_detection"]
)
results["overall_score"] = round(total_score, 1)
# Determine overall pass/fail
results["passed"] = all([
edge_result.passed,
harmony_result.passed,
artifact_result.passed
])
# Collect issues
for check_name, check_data in results["checks"].items():
if check_data["issue"]:
if check_data["passed"]:
results["warnings"].append(f"{check_name}: {check_data['issue']}")
else:
results["errors"].append(f"{check_name}: {check_data['issue']}")
logger.info(f"Inpainting quality: {results['overall_score']:.1f}, Passed: {results['passed']}")
return results
|