简体   繁体   中英

How to change colors on my Python's cv2 diagram

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 (ie 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.

在此处输入图像描述

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)

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM