Skip to content

Instantly share code, notes, and snippets.

@Erol444
Created May 14, 2023 18:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Erol444/747d5a8b711f3f8e3ce0c08931f5c7a2 to your computer and use it in GitHub Desktop.
Save Erol444/747d5a8b711f3f8e3ce0c08931f5c7a2 to your computer and use it in GitHub Desktop.
Comparing distinctipy method vs new method. Distinctipy need more than 2 sec to generate 64 colors.
import numpy as np
import colorsys
import cv2
import math
import time
def generate_colors(number_of_colors, pastel=0.5):
colors = []
# Calculate the number of hues and value steps
steps = math.ceil(math.sqrt(number_of_colors))
for i in range(steps):
hue = i / steps
for j in range(steps):
value = 0.6 + (j / steps) * 0.4 # This will give a value between 0.6 and 1
r, g, b = colorsys.hsv_to_rgb(hue, pastel, value)
r, g, b = int(r * 255), int(g * 255), int(b * 255)
colors.append((r, g, b))
# Randomize colors
np.random.shuffle(colors)
# Return only the first `number_of_colors` colors
return colors[:number_of_colors]
def draw_color_rectangles(colors, name: str):
# Calculate grid dimensions
grid_size = int(np.ceil(np.sqrt(len(colors))))
# Define the size of the image and each rectangle
rect_width, rect_height = 75, 75
img_width, img_height = grid_size * rect_width, grid_size * rect_height
# Create a white background image
img = np.ones((img_height, img_width, 3), dtype=np.uint8) * 255
# Draw the rectangles
for i in range(grid_size):
for j in range(grid_size):
idx = i * grid_size + j
if idx < len(colors):
color = colors[idx]
pt1 = (j * rect_width, i * rect_height)
pt2 = ((j + 1) * rect_width, (i + 1) * rect_height)
cv2.rectangle(img, pt1, pt2, color, -1) # -1 for filled rectangle
# Show the image
cv2.imshow(name, img)
def get_distinctipy_colors(n):
import distinctipy
start = time.time()
colors = np.array(distinctipy.get_colors(n_colors=n, rng=123123, pastel_factor=0.5))[..., ::-1]
print(f'get_distinctipy_colors: {time.time() - start} seconds')
return [distinctipy.get_rgb256(clr) for clr in colors] # List of (b,g,r), 0..255
draw_color_rectangles(generate_colors(64), 'new method')
draw_color_rectangles(get_distinctipy_colors(64), 'distinctipy')
cv2.waitKey(0)
cv2.destroyAllWindows()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment