ascota_core.color¶
The color module provides functionality for color correction and
color-based clustering. It aligns input images to a standard reference
using detected color cards, also contains functions to cluster and group similar
looking images. This ensures that downstream analysis works with normalized and
comparable color values.
Color correction and color grading algorithms. Also includes color based clustering algorithms.
srgb_to_linear ¶
srgb_to_linear(x)
Convert sRGB color values to linear RGB.
Applies the inverse sRGB gamma correction curve to convert from sRGB color space to linear RGB color space for proper color processing calculations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ndarray
|
Input array of sRGB values in range [0.0, 1.0]. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Array of linear RGB values in range [0.0, 1.0] with same shape as input. |
Source code in src/ascota_core/color.py
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | |
linear_to_srgb ¶
linear_to_srgb(x)
Convert linear RGB color values to sRGB.
Applies the sRGB gamma correction curve to convert from linear RGB color space to sRGB color space for display or output purposes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ndarray
|
Input array of linear RGB values in range [0.0, 1.0]. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Array of sRGB values in range [0.0, 1.0] with same shape as input. |
Source code in src/ascota_core/color.py
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | |
bgr_linear_to_lab_u8 ¶
bgr_linear_to_lab_u8(bgr_lin)
Convert linear BGR image to 8-bit LAB color space.
Converts a linear BGR image to LAB color space for perceptually uniform color operations. The output is in 8-bit format suitable for OpenCV operations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bgr_lin
|
ndarray
|
Linear BGR image array with values in range [0.0, 1.0]. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
8-bit LAB image array with shape matching input. |
Source code in src/ascota_core/color.py
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | |
lab_u8_to_bgr_linear ¶
lab_u8_to_bgr_linear(lab8)
Convert 8-bit LAB image to linear BGR color space.
Converts a LAB color space image back to linear BGR format for further processing or color correction operations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lab8
|
ndarray
|
8-bit LAB image array. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Linear BGR image array with values in range [0.0, 1.0]. |
Source code in src/ascota_core/color.py
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 | |
to_uint8_preview ¶
to_uint8_preview(bgr_lin)
Convert linear BGR image to 8-bit RGB PIL Image for preview.
Converts a linear BGR image to sRGB color space and creates a PIL Image suitable for display or preview purposes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bgr_lin
|
ndarray
|
Linear BGR image array with values in range [0.0, 1.0]. |
required |
Returns:
| Type | Description |
|---|---|
Image
|
PIL Image in RGB format with 8-bit precision. |
Source code in src/ascota_core/color.py
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 | |
to_png16_bytes ¶
to_png16_bytes(bgr_lin)
Convert linear BGR image to 16-bit PNG bytes.
Converts a linear BGR image to sRGB color space and encodes it as a 16-bit PNG in bytes format for high-quality output or storage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bgr_lin
|
ndarray
|
Linear BGR image array with values in range [0.0, 1.0]. |
required |
Returns:
| Type | Description |
|---|---|
bytes
|
PNG-encoded bytes of the 16-bit image. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If PNG encoding fails. |
Source code in src/ascota_core/color.py
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 | |
_build_monotone_quantile_mapping ¶
_build_monotone_quantile_mapping(src_vals, tgt_vals, n_knots=257)
Build monotonic quantile mapping between source and target values.
Creates a monotonic mapping from source values to target values using quantiles. This is used for histogram matching and color transfer operations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
src_vals
|
ndarray
|
Source values to map from. |
required |
tgt_vals
|
ndarray
|
Target values to map to. |
required |
n_knots
|
int
|
Number of quantile knots to use for the mapping. Defaults to 257. |
257
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Tuple of (source_quantiles, target_quantiles) as float32 arrays for |
ndarray
|
use with np.interp(). |
Source code in src/ascota_core/color.py
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 | |
apply_manual_adjustments_linear ¶
apply_manual_adjustments_linear(
bgr_lin, brightness=0, contrast=1.0, gamma=1.0, r_gain=1.0, g_gain=1.0, b_gain=1.0
)
Apply manual color adjustments to a linear BGR image.
Applies brightness, contrast, gamma, and per-channel gain adjustments to a linear BGR image. All adjustments are performed in sRGB space before converting back to linear.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bgr_lin
|
ndarray
|
Linear BGR image array with values in range [0.0, 1.0]. |
required |
brightness
|
int
|
Brightness adjustment in range [-255, 255]. Defaults to 0. |
0
|
contrast
|
float
|
Contrast multiplier, values > 1.0 increase contrast. Defaults to 1.0. |
1.0
|
gamma
|
float
|
Gamma correction value, values < 1.0 brighten midtones. Defaults to 1.0. |
1.0
|
r_gain
|
float
|
Red channel gain multiplier. Defaults to 1.0. |
1.0
|
g_gain
|
float
|
Green channel gain multiplier. Defaults to 1.0. |
1.0
|
b_gain
|
float
|
Blue channel gain multiplier. Defaults to 1.0. |
1.0
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Adjusted linear BGR image array with same shape as input. |
Source code in src/ascota_core/color.py
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 | |
lab_mean_std_transfer_linear ¶
lab_mean_std_transfer_linear(src_bgr_lin, tgt_bgr_lin, src_mask, tgt_mask)
Transfer color statistics using LAB mean and standard deviation.
Performs color transfer by matching the mean and standard deviation of each LAB channel within the masked regions. This method preserves luminance relationships while adjusting color characteristics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
src_bgr_lin
|
ndarray
|
Source linear BGR image array. |
required |
tgt_bgr_lin
|
ndarray
|
Target linear BGR image array. |
required |
src_mask
|
ndarray
|
Boolean mask for source image region of interest. |
required |
tgt_mask
|
ndarray
|
Boolean mask for target image region of interest. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Color-corrected linear BGR image array with same shape as source. |
Source code in src/ascota_core/color.py
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 | |
monotone_lut_ab_only ¶
monotone_lut_ab_only(src_bgr_lin, tgt_bgr_lin, src_mask, tgt_mask, n_knots=257)
Apply monotonic LUT mapping to A and B channels only in LAB space.
Performs color transfer by applying quantile-based monotonic lookup tables to the A and B channels in LAB color space, while preserving the L channel. This method focuses on chromaticity transfer without affecting luminance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
src_bgr_lin
|
ndarray
|
Source linear BGR image array. |
required |
tgt_bgr_lin
|
ndarray
|
Target linear BGR image array. |
required |
src_mask
|
ndarray
|
Boolean mask for source image region of interest. |
required |
tgt_mask
|
ndarray
|
Boolean mask for target image region of interest. |
required |
n_knots
|
int
|
Number of quantile knots for the LUT mapping. Defaults to 257. |
257
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Color-corrected linear BGR image array with same shape as source. |
Source code in src/ascota_core/color.py
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 | |
masked_histogram_match_rgb_linear ¶
masked_histogram_match_rgb_linear(src_bgr_lin, tgt_bgr_lin, src_mask, tgt_mask, n_knots=1025)
Perform histogram matching in RGB space using masked regions.
Applies quantile-based histogram matching to each RGB channel independently using only the pixels within the specified mask regions. This method provides comprehensive color transfer across all channels.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
src_bgr_lin
|
ndarray
|
Source linear BGR image array. |
required |
tgt_bgr_lin
|
ndarray
|
Target linear BGR image array. |
required |
src_mask
|
ndarray
|
Boolean mask for source image region of interest. |
required |
tgt_mask
|
ndarray
|
Boolean mask for target image region of interest. |
required |
n_knots
|
int
|
Number of quantile knots for histogram matching. Defaults to 1025. |
1025
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Color-corrected linear BGR image array with same shape as source. |
Source code in src/ascota_core/color.py
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 | |
_pil_to_bgr_linear ¶
_pil_to_bgr_linear(img_pil)
Convert PIL Image to linear BGR array.
Converts a PIL Image to linear BGR format suitable for color processing operations. The conversion goes through RGB -> sRGB -> linear RGB -> BGR.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
img_pil
|
Image
|
Input PIL Image in any supported format. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Linear BGR image array with values in range [0.0, 1.0]. |
Source code in src/ascota_core/color.py
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 | |
_prepare_mask_bool ¶
_prepare_mask_bool(mask_pil, expected_shape)
Convert PIL mask to boolean array aligned to expected dimensions.
Converts a PIL mask image to a boolean array where True indicates the region of interest (card area). Resizes the mask if needed to match the expected dimensions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mask_pil
|
Image
|
PIL mask image, will be converted to grayscale. |
required |
expected_shape
|
Tuple[int, int]
|
Target dimensions as (width, height) tuple. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Boolean mask array with shape (height, width) where True indicates |
ndarray
|
the card region (pixels with value >= 200). |
Source code in src/ascota_core/color.py
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 | |
match_color_cards_from_pils ¶
match_color_cards_from_pils(
original_image,
original_masks,
target_image,
target_masks,
original_card_types,
target_card_types,
method="lab_mean_std_transfer",
n_knots=None,
debug=False,
)
Match color appearance between two images using color card references.
Performs color correction by matching the appearance of color cards between a source image and target image. The function automatically finds matching color card types and applies the specified color transfer method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
original_image
|
Image
|
Source PIL Image to correct. |
required |
original_masks
|
List[Image]
|
List of PIL mask images for detected cards in source image. |
required |
target_image
|
Image
|
Target PIL Image providing the desired color appearance. |
required |
target_masks
|
List[Image]
|
List of PIL mask images for detected cards in target image. |
required |
original_card_types
|
List[str]
|
List of card type strings corresponding to original_masks. |
required |
target_card_types
|
List[str]
|
List of card type strings corresponding to target_masks. |
required |
method
|
str
|
Color transfer method to use. One of: - "lab_mean_std_transfer" (default): Mean/std matching in LAB space - "monotone_lut": Quantile mapping on LAB A/B channels only - "histogram_matching": Full RGB histogram matching |
'lab_mean_std_transfer'
|
n_knots
|
Optional[int]
|
Number of quantile knots for LUT-based methods. If None, uses method-specific defaults (513 for monotone_lut, 1025 for histogram_matching). |
None
|
debug
|
bool
|
Enable debug output. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dictionary containing:
- matched_preview: 8-bit PIL Image preview of corrected result
- matched_png16: 16-bit PNG encoded bytes of corrected result |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no matching color card types are found in both images, or if an unknown method is specified. |
Source code in src/ascota_core/color.py
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 | |
match_color_cards_from_pipeline_outputs ¶
match_color_cards_from_pipeline_outputs(
original_pipeline_output,
target_pipeline_output,
method="lab_mean_std_transfer",
n_knots=None,
debug=False,
)
Match color cards using outputs from the image processing pipeline.
Convenience wrapper that accepts dictionaries returned by process_image_pipeline() and performs color matching between source and target images using their detected color cards.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
original_pipeline_output
|
dict
|
Dictionary from process_image_pipeline() for source image. Must contain keys: 'original_image', 'masks', 'card_types'. |
required |
target_pipeline_output
|
dict
|
Dictionary from process_image_pipeline() for target image. Must contain keys: 'original_image', 'masks', 'card_types'. |
required |
method
|
str
|
Color transfer method to use. See match_color_cards_from_pils() for options. Defaults to "lab_mean_std_transfer". |
'lab_mean_std_transfer'
|
n_knots
|
Optional[int]
|
Number of quantile knots for LUT-based methods. If None, uses method-specific defaults. |
None
|
debug
|
bool
|
Enable debug output. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dictionary with same structure as match_color_cards_from_pils(). |
Raises:
| Type | Description |
|---|---|
TypeError
|
If pipeline outputs are not dictionaries. |
ValueError
|
If required keys are missing from pipeline outputs. |
Source code in src/ascota_core/color.py
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 | |
_extract_corner_regions ¶
_extract_corner_regions(bgr_lin, corner_size=0.1)
Extract four corner regions from an image.
Extracts square regions from each corner of the image. The size of each corner region is determined by the corner_size parameter as a fraction of the smaller image dimension.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bgr_lin
|
ndarray
|
Linear BGR image array with values in range [0.0, 1.0]. |
required |
corner_size
|
float
|
Size of corner regions as fraction of smaller dimension. Defaults to 0.1 (10%). |
0.1
|
Returns:
| Type | Description |
|---|---|
List[ndarray]
|
List of 4 corner region arrays: [top_left, top_right, bottom_left, bottom_right]. |
Source code in src/ascota_core/color.py
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 | |
_select_whitest_corners ¶
_select_whitest_corners(corners, n_select=3)
Select the corners closest to white (high L*, low chroma).
Analyzes each corner region and selects the n_select corners that are closest to white. This helps avoid selecting corners that contain color cards or other colored objects.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
corners
|
List[ndarray]
|
List of corner region arrays from _extract_corner_regions(). |
required |
n_select
|
int
|
Number of corners to select. Defaults to 3. |
3
|
Returns:
| Type | Description |
|---|---|
List[ndarray]
|
List of selected corner arrays, ordered by whiteness score. |
Source code in src/ascota_core/color.py
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 | |
_extract_lighting_features ¶
_extract_lighting_features(corners)
Extract lighting feature vector from selected corner regions.
Builds a richer feature vector from the selected corners by computing mean and standard deviation of Lab* values for each corner. This creates a more robust representation of the lighting conditions in the image.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
corners
|
List[ndarray]
|
List of selected corner region arrays. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Feature vector as 1D numpy array with shape (n_corners * 6,). |
ndarray
|
Each corner contributes 6 values: mean L, mean a, mean b, std L, std a, std b. |
Source code in src/ascota_core/color.py
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 | |
_find_optimal_k_bic ¶
_find_optimal_k_bic(features, max_k=10)
Find optimal number of clusters using Bayesian Information Criterion.
Tests different values of k and selects the one that minimizes BIC, balancing model fit with complexity. Uses Gaussian Mixture Models for BIC calculation. Includes elbow detection for more robust selection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
features
|
ndarray
|
Feature matrix with shape (n_samples, n_features). |
required |
max_k
|
int
|
Maximum number of clusters to test. Defaults to 10. |
10
|
Returns:
| Type | Description |
|---|---|
int
|
Optimal number of clusters. |
Source code in src/ascota_core/color.py
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 | |
_cluster_images ¶
_cluster_images(features, k=None, max_k=None, n_runs=5)
Cluster images based on their lighting features with improved consistency.
Performs k-means clustering on the feature vectors with multiple runs and consensus voting for better consistency. If k is not provided, automatically determines the optimal k using BIC.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
features
|
ndarray
|
Feature matrix with shape (n_samples, n_features). |
required |
k
|
Optional[int]
|
Number of clusters. If None, determined automatically via BIC. |
None
|
max_k
|
Optional[int]
|
Maximum k to try when auto-selecting via BIC. |
None
|
n_runs
|
int
|
Number of k-means runs for consensus (default 5). |
5
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Array of cluster labels with length n_samples. |
Source code in src/ascota_core/color.py
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 | |
group_similar_images_by_lighting ¶
group_similar_images_by_lighting(directory, k=None, extensions=None, sensitivity=1.0, debug=False)
Group similar images from a directory based on lighting conditions.
Analyzes images in a directory and groups them based on lighting similarity. The function examines the four corners of each image, selects the three corners closest to white (to avoid color cards), extracts lighting features, and clusters the images accordingly.
Improved version with: - Better feature extraction (mean + std) - Feature normalization for consistent scaling - Multiple k-means runs with consensus for consistency - Better sensitivity control through distance-based thresholding
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directory
|
str
|
Path to directory containing images to analyze. |
required |
k
|
Optional[int]
|
Number of clusters. If None, automatically determined via BIC. |
None
|
extensions
|
List[str]
|
List of image file extensions to process. If None, uses common formats: ['.jpg', '.jpeg', '.png']. |
None
|
sensitivity
|
float
|
Float >0 controlling clustering sensitivity. Values >1 increase sensitivity (more clusters, amplifies feature differences). Values <1 decrease sensitivity (fewer clusters, mutes differences). Default 1.0. |
1.0
|
debug
|
bool
|
Enable debug output. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
List[List[str]]
|
List of lists, where each inner list contains file paths of images |
List[List[str]]
|
with similar lighting conditions. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If directory doesn't exist or contains no valid images. |
Exception
|
If image processing fails for critical errors. |
Source code in src/ascota_core/color.py
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 | |