Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add random colors generator for instance plotting #244

Merged
merged 1 commit into from
Apr 28, 2024

Conversation

anwai98
Copy link
Contributor

@anwai98 anwai98 commented Apr 26, 2024

No description provided.

@constantinpape constantinpape merged commit 357fb44 into constantinpape:main Apr 28, 2024
2 checks passed
@ajinkya-kulkarni
Copy link

This commit just popped up on my feed, thanks for it!
BTW, I have tried this before (for diff colored labels for each instance segmented blob), but I realized it often gives very "dark" colored labels.
The code I now use is this, which actually is a part of the StarDist repo.

import matplotlib
import colorsys

def random_label_cmap(n=2**16, h=(0, 1), l=(0.4, 1), s=(0.2, 0.8)):
    """
    Generates a random colormap for labeling purposes.

    Parameters:
    n (int): Number of colors in the colormap. Default is 2**16.
    h (tuple): Range of hue values (0 to 1). Default is (0, 1).
    l (tuple): Range of lightness values (0 to 1). Default is (0.4, 1).
    s (tuple): Range of saturation values (0 to 1). Default is (0.2, 0.8).

    Returns:
    matplotlib.colors.ListedColormap: A colormap object with randomly generated colors.

    The function generates colors in HLS (Hue, Lightness, Saturation) space and converts them to RGB.
    The first color in the colormap is always set to black for background or default labeling.
    """

    # Generate random values for hue, lightness, and saturation within specified ranges
    h, l, s = np.random.uniform(*h, n), np.random.uniform(*l, n), np.random.uniform(*s, n)

    # Convert HLS values to RGB values
    cols = np.stack([colorsys.hls_to_rgb(_h, _l, _s) for _h, _l, _s in zip(h, l, s)], axis=0)

    # Set the first color in the colormap to black (useful for background or default labels)
    cols[0] = 0

    # Create a ListedColormap object from the generated RGB values
    random_label_cmap = matplotlib.colors.ListedColormap(cols)

    return random_label_cmap

and then just use it as:

lbl_cmap = random_label_cmap()
plt.imshow(mask, cmap=lbl_cmap)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

3 participants