-7

I have this piece of code that draws a meter for a given percentage value. How can I change it to get two parameters for bottom color and top color (i.e. a shade from color1 to color2, like light green to dark green in this example). Also, a x, y parameter specifying the coordinates of where to place this meter?

I was trying some changes, but no luck.

enter image description here

import cv2
import numpy
def draw_indicator(img, percentage):

    def percentage_to_color(p):
        return 0, 255 * p, 255 - (255 * p)

    # config
    levels = 10
    indicator_width = 80
    indicator_height = 220
    level_width = indicator_width - 20
    level_height = int((indicator_height - 20) / levels - 5)
    # draw
    img_levels = int(percentage * levels)
    cv2.rectangle(img, (10, img.shape[0] - (indicator_height + 10)), (10 + indicator_width, img.shape[0] - 10), (0, 0, 0), cv2.FILLED)

    for i in range(img_levels):
        level_y_b = int(img.shape[0] - (20 + i * (level_height + 5)))
        cv2.rectangle(img, (20, level_y_b - level_height), (20 + level_width, level_y_b), percentage_to_color(i / levels), cv2.FILLED)

# test code
img = cv2.imread('a.jpg')
draw_indicator(img, 0.7)
cv2.imshow("test", img)
cv2.waitKey(10000)
Jeru Luke
  • 20,118
  • 13
  • 80
  • 87
Tina J
  • 4,983
  • 13
  • 59
  • 125

1 Answers1

0

you can easily create custom colormaps using strings of color names as endpoints (found here: Custom Colormap in Python)

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

cmap = LinearSegmentedColormap.from_list('mycmap', ['red', 'white', 'green'])

fig, ax = plt.subplots()
im = ax.imshow(np.random.random((10, 10)), cmap=cmap, interpolation='nearest')
fig.colorbar(im)
plt.show()
Cooper
  • 1
  • 1