Skip to content

Commit

Permalink
more tests fro hex_to_rgb
Browse files Browse the repository at this point in the history
  • Loading branch information
sebi06 committed Feb 7, 2025
1 parent 44207a7 commit 94f1c99
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 17 deletions.
19 changes: 19 additions & 0 deletions src/czitools/_tests/test_channelinfo.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from pathlib import Path
from czitools.metadata_tools import czi_metadata as czimd
from czitools.metadata_tools.channel import hex_to_rgb
import pytest
from typing import List, Dict
from pylibCZIrw import czi as pyczi
Expand Down Expand Up @@ -135,3 +136,21 @@ def test_channelinfo(
assert czi_channels.isRGB == is_rgb
assert czi_channels.consistent_pixeltypes == is_consistent
assert czi_channels.pixeltypes == pxtypes


@pytest.mark.parametrize(
"hex_string, results",
[
("#80808000", (128, 128, 0)),
("#FFFF7E000", (255, 126, 0)),
("00FF3", (128, 128, 128)),
("FF00FF", (255, 0, 255)),
("##FF00FF", (255, 0, 255)),
("#FF00FF33", (0, 255, 51)),
("#", (128, 128, 128)),
("", (128, 128, 128)),
],
)
def test_channelinfo_hexstring(hex_string: str, results: tuple[int, int, int]) -> None:

assert hex_to_rgb(hex_string) == results
58 changes: 41 additions & 17 deletions src/czitools/metadata_tools/channel.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,19 @@
from typing import Union, List, Dict, Optional
# -*- coding: utf-8 -*-

#################################################################
# File : channel.py
# Author : sebi06
#
#################################################################

from typing import Union, List, Dict
from dataclasses import dataclass, field
from box import Box, BoxList
import os
from czitools.utils import logging_tools, pixels
from czitools.utils.box import get_czimd_box
from pylibCZIrw import czi as pyczi
import numpy as np
from pathlib import Path

logger = logging_tools.set_logging()

Expand Down Expand Up @@ -36,8 +43,6 @@ class CziChannelInfo:
Extracts and appends channel display information.
_calculate_display_settings() -> Dict:
Calculates and returns the display settings for each channel.
_hex_to_rgb(hex_string: str) -> tuple[int, int, int]:
Converts a hexadecimal color string to an RGB tuple.
"""

czisource: Union[str, os.PathLike[str], Box]
Expand Down Expand Up @@ -115,7 +120,7 @@ def __post_init__(self):
except AttributeError:
disp = None

# calulate the ChannelDisplaySetting
# calculate the ChannelDisplaySetting
self.czi_disp_settings = self._calculate_display_settings()

elif not czi_box.has_disp:
Expand Down Expand Up @@ -161,7 +166,7 @@ def _calculate_display_settings(self) -> Dict:
for channel_index in range(num_channels):

# Get RGB values based on a RGB hexstring. Inside a CZI per channel one gets #AARRGGBB.
r, g, b = self._hex_to_rgb(self.colors[channel_index][3:])
r, g, b = hex_to_rgb(self.colors[channel_index][3:])

if self.isRGB[channel_index]:
tinting_mode = pyczi.TintingMode.none
Expand All @@ -187,20 +192,39 @@ def _calculate_display_settings(self) -> Dict:

return display_settings_dict

def _hex_to_rgb(self, hex_string: str) -> tuple[int, int, int]:
"""
Convert a hexadecimal color string to an RGB tuple.
Args:
hex_string (str): A string representing a color in hexadecimal format (e.g., '#RRGGBB').
Returns:
tuple: A tuple containing the RGB values (r, g, b) as integers.
"""
# Remove the '#' character
hex_string = hex_string.lstrip("#")

def hex_to_rgb(hex_string: str) -> tuple[int, int, int]:
"""
Convert a hexadecimal color string to an RGB tuple.
Args:
hex_string (str): A string representing a color in hexadecimal format (e.g., '#RRGGBB').
Returns:
tuple: A tuple containing the RGB values (r, g, b) as integers.
"""

# Remove the '#' characters
hex_string = hex_string.replace("#", "")

# check the length of the string
if len(hex_string) != 6:
# remove alpha values
hex_string = hex_string[2:]

try:
# Convert hex string to integer values
r = int(hex_string[0:2], 16)
g = int(hex_string[2:4], 16)
b = int(hex_string[4:6], 16)

return r, g, b
except ValueError:

# Set RGB values to 128 if conversion fails
r = 128
g = 128
b = 128

logger.error(
f"Invalid RGB values detected. Conversion of hex string {hex_string} to RGB failed. Setting RGB values to 128."
)

return r, g, b

0 comments on commit 94f1c99

Please sign in to comment.