ascota_core.imaging¶
The imaging module implements segmentation utilities and color card
detection. It leverages different models and traditional computer vision
techniques (OpenCV) to isolate pottery sherds, measurement cards, and other
regions of interest. We also use template matching to enhance detection accuracy.
This module is crucial for preparing images for subsequent color correction
and scale estimation. Also includes utilities for generating image swatches of
segmented sherds.
Image processing functions for color card detection and background removal.
This module provides functions for detecting color reference cards in images using finetuned YOLOv8 oriented bounding box models, and for generating binary masks using RMBG-1.4 background removal with optional card area exclusion.
_load_yolo_model ¶
_load_yolo_model(debug=False)
Load and cache YOLOv8 OBB model for color card detection.
Loads the YOLOv8 oriented bounding box model from the models directory and caches it at module level to avoid reloading on subsequent calls. The model is configured for color card detection with three classes: 24_color_card, 8_hybrid_card, and checker_card.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
debug
|
bool
|
If True, print debug information during model loading. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
Any
|
Loaded YOLOv8 OBB model instance. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the model file cannot be found. |
RuntimeError
|
If model loading fails. |
Source code in src/ascota_core/imaging.py
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 | |
_load_rmbg_pipeline ¶
_load_rmbg_pipeline(debug=False)
Load and cache RMBG-1.4 pipeline for background removal.
Initializes the RMBG-1.4 transformer pipeline for automated background removal and caches it at module level to avoid reloading on subsequent calls. The pipeline uses the briaai/RMBG-1.4 model from Hugging Face.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
debug
|
bool
|
If True, print debug information during pipeline initialization. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
Any
|
Configured RMBG pipeline object. |
Raises:
| Type | Description |
|---|---|
ImportError
|
If transformers library is not installed. |
RuntimeError
|
If pipeline initialization fails. |
Source code in src/ascota_core/imaging.py
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 | |
detect_color_cards ¶
detect_color_cards(image, debug=False)
Detect color cards in an image using YOLOv8 OBB model.
Processes a PIL image to detect and classify color reference cards (24-color, 8-hybrid, or checker cards) using a trained YOLOv8 oriented bounding box model. Returns detection results with pixel coordinates and classification information for each detected card.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
|
Image
|
Input PIL Image to process. Must be in RGB or RGBA format. |
required |
debug
|
bool
|
If True, print debug information during processing. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
List[Dict[str, Any]]
|
List of dictionaries, one per detected card. Each dictionary contains: - class: String class name ('24_color_card', '8_hybrid_card', or 'checker_card') - class_id: Integer class ID (0, 1, or 2) - confidence: Float confidence score in range [0.0, 1.0] - coordinates: List of 4 [x, y] coordinate pairs as pixel coordinates representing the four corners of the detected card. |
List[Dict[str, Any]]
|
Returns empty list if no cards are detected. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the YOLOv8 model file cannot be found. |
RuntimeError
|
If model loading or inference fails. |
TypeError
|
If input is not a PIL Image. |
Source code in src/ascota_core/imaging.py
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 | |
_calculate_background_color ¶
_calculate_background_color(img_array, card_coordinates, debug=False)
Calculate average background color by sampling areas outside detected cards.
Analyzes the image to determine the dominant background color by creating masks for detected cards, dilating them to avoid edge effects, and then sampling the remaining background pixels. Falls back to corner sampling if insufficient background area is available.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
img_array
|
ndarray
|
Input image as numpy array in RGB format with shape (height, width, 3). |
required |
card_coordinates
|
List[Dict[str, Any]]
|
List of detection dictionaries from detect_color_cards() to exclude from background sampling. |
required |
debug
|
bool
|
If True, print debug information about sampling process. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
Tuple[int, int, int]
|
Average background color as RGB tuple (R, G, B) with uint8 values. |
Source code in src/ascota_core/imaging.py
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 | |
_crop_out_card_regions ¶
_crop_out_card_regions(img_array, card_coordinates, background_color, debug=False)
Crop out (remove) card regions from image by filling them with background color.
Fills the polygon areas of detected color cards with the specified background color, effectively removing them from the image while maintaining the original image dimensions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
img_array
|
ndarray
|
Input image as numpy array in RGB format with shape (height, width, 3). |
required |
card_coordinates
|
List[Dict[str, Any]]
|
List of detection dictionaries from detect_color_cards(). |
required |
background_color
|
Tuple[int, int, int]
|
RGB tuple (R, G, B) to fill card regions with. |
required |
debug
|
bool
|
If True, print debug information. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Modified image array with card regions filled with background color. |
Source code in src/ascota_core/imaging.py
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 | |
_post_process_mask ¶
_post_process_mask(
binary_mask,
min_component_size_pct=2.5e-05,
max_hole_size_pct=2.9e-05,
edge_tolerance_pct=0.029283,
debug=False,
)
Post-process binary mask to clean up artifacts.
Applies several cleaning operations to the binary mask: 1. Removes edge-touching components (within tolerance) 2. Removes small isolated components (lone pixels or very small groups) 3. Fills small holes (small black regions surrounded by white)
All size parameters are specified as percentages of image dimensions to work with dynamic resolutions. Values are based on a 2048x1366 reference image: - min_component_size: 70 pixels (0.000025 = 0.0025% of total pixels) - max_hole_size: 80 pixels (0.000029 = 0.0029% of total pixels) - edge_tolerance: 40 pixels (0.029283 = 2.93% of smaller dimension)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
binary_mask
|
ndarray
|
Binary mask as numpy array with shape (height, width) and dtype uint8. Values are 0 (background) or 1 (foreground). |
required |
min_component_size_pct
|
float
|
Minimum component size as decimal fraction of total image pixels (e.g., 0.000025 = 0.0025%). Components smaller than this will be removed. |
2.5e-05
|
max_hole_size_pct
|
float
|
Maximum hole size as decimal fraction of total image pixels (e.g., 0.000029 = 0.0029%). Holes larger than this will remain. |
2.9e-05
|
edge_tolerance_pct
|
float
|
Edge tolerance as decimal fraction of smaller image dimension (e.g., 0.029283 = 2.93%). Components within this distance from any edge will be removed. |
0.029283
|
debug
|
bool
|
If True, print debug information about processing. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Post-processed binary mask with same shape and dtype as input. |
Source code in src/ascota_core/imaging.py
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 | |
remove_background_mask ¶
remove_background_mask(image, card_coordinates=None, debug=False)
Generate binary mask using RMBG-1.4 background removal with two-pass processing.
Performs background removal on a PIL image using the RMBG-1.4 model in two passes: 1. First pass: Process the input image (with cards cropped out if provided) 2. Second pass: Process the first result on a white background
The binary mask is generated from the second pass result, which typically provides better quality. The mask is inverted so that foreground objects are marked as 1 and background as 0.
If card coordinates are provided, the card regions are cropped out (filled with background color) from the image before the first pass, and removed from the first pass result before the second pass.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
|
Image
|
Input PIL Image to process. Must be in RGB or RGBA format. |
required |
card_coordinates
|
Optional[List[Dict[str, Any]]]
|
Optional list of detection dictionaries from detect_color_cards(). If provided, card polygon areas will be cropped out (filled with background color) before the first RMBG pass, and removed from the first pass result before the second pass. |
None
|
debug
|
bool
|
If True, print debug information during processing and return additional debug images. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
Union[ndarray, Tuple[ndarray, Image, Image, Image]]
|
If debug=False: Binary mask as numpy array with shape (height, width) and dtype uint8. Values are 0 (background) or 1 (foreground). The mask has the same dimensions as the original input image. The mask is generated from the second RMBG pass (white background). |
Union[ndarray, Tuple[ndarray, Image, Image, Image]]
|
If debug=True: Tuple of (binary_mask, rmbg_image, rmbg_white_bg_image) where: - binary_mask: The inverted mask from the second RMBG pass in original image dimensions - rmbg_image: The PIL Image result from the first RMBG pass - rmbg_white_bg_image: The first RMBG result layered on white background (input to the second RMBG pass) |
Raises:
| Type | Description |
|---|---|
ImportError
|
If transformers library is not installed. |
RuntimeError
|
If RMBG pipeline initialization or processing fails. |
TypeError
|
If input is not a PIL Image. |
Source code in src/ascota_core/imaging.py
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 | |
generate_swatch ¶
generate_swatch(
pil_image,
swatch_size=(1000, 500),
target_dpi=1200,
pp_cm_original=None,
pp_cm_target=None,
coarse_angle_step=15,
fine_angle_step=1,
debug=False,
)
Generate a rotated coverage-optimized swatch from a transparent image.
Given an RGBA image with transparency, this function finds a swatch (default 1000x500 pixels) centered on the object's (non-transparent area) centroid, allowing rotation to maximize the number of foreground pixels captured.
Strategy
- Ensure RGBA & build binary mask using alpha > 0 (non-transparent pixels).
- If object smaller than desired swatch, uniformly upscale image so the object's bounding box exceeds the swatch with a modest margin.
- Perform a coarse rotation search (0..179 degrees) at
coarse_angle_stepincrements. Track coverage (foreground pixels inside the candidate swatch / swatch area). - Refine around best coarse angle using
fine_angle_stepsteps. - Extract the crop (padding with transparency if crop extends beyond
image bounds). DPI metadata is set to
target_dpi.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pil_image
|
Image
|
Input PIL image (preferably RGBA) with transparent background. |
required |
swatch_size
|
Tuple[int, int]
|
Desired (width, height) of output swatch in pixels. Defaults to (1000, 500). |
(1000, 500)
|
target_dpi
|
int
|
DPI metadata to tag on the output image. Defaults to 1200. |
1200
|
pp_cm_original
|
Optional[float]
|
Original pixels-per-centimeter of the image. If provided along with pp_cm_target (>0), the image is uniformly rescaled by (pp_cm_target / pp_cm_original) before swatch generation. |
None
|
pp_cm_target
|
Optional[float]
|
Target pixels-per-centimeter to achieve prior to swatch rotation/cropping. Ignored unless pp_cm_original also provided. |
None
|
coarse_angle_step
|
int
|
Degrees per step for coarse search. Defaults to 15. |
15
|
fine_angle_step
|
int
|
Degrees per step for fine search window. Defaults to 1. |
1
|
debug
|
bool
|
Print diagnostic information if True. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
Image
|
PIL Image (RGBA) sized exactly |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no non-transparent pixels are found or swatch dimensions invalid. |
Source code in src/ascota_core/imaging.py
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 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 | |