如何修改Python cv2仪表盘绘制代码支持自定义渐变色和位置参数

完整修改代码
import cv2 import numpy def draw_indicator(img, percentage, x=10, y=None, bottom_color=(0, 255, 0), top_color=(0, 0, 255)): # 基础配置参数 levels = 10 indicator_width = 80 indicator_height = 220 level_width = indicator_width - 20 level_height = int((indicator_height - 20) / levels - 5) # 未传y坐标时默认放在图片左下角,和原逻辑保持兼容 if y is None: y = img.shape[0] - indicator_height - 10 # 渐变颜色计算:ratio从0到1对应从底部颜色过渡到顶部颜色 def get_level_color(ratio): b = int(bottom_color[0] * (1 - ratio) + top_color[0] * ratio) g = int(bottom_color[1] * (1 - ratio) + top_color[1] * ratio) r = int(bottom_color[2] * (1 - ratio) + top_color[2] * ratio) return (b, g, r) # 绘制仪表盘黑色外背景 cv2.rectangle( img, (x, y), (x + indicator_width, y + indicator_height), (0, 0, 0), cv2.FILLED ) # 绘制带渐变效果的进度刻度 active_level_count = int(percentage * levels) for i in range(active_level_count): # 计算当前刻度的上下边界坐标,从下往上排列 level_bottom_y = y + indicator_height - 20 - i * (level_height + 5) level_top_y = level_bottom_y - level_height cv2.rectangle( img, (x + 10, level_top_y), (x + 10 + level_width, level_bottom_y), get_level_color(i / (levels - 1)), cv2.FILLED ) # 测试代码 if __name__ == "__main__": # 示例:自定义放在x=50,y=30位置,实现浅绿到深绿的渐变效果 img = numpy.ones((400, 400, 3), dtype=numpy.uint8) * 255 # 白色测试背景 draw_indicator( img, percentage=0.7, x=50, y=30, bottom_color=(144, 238, 144), top_color=(0, 100, 0) ) # 也可以兼容原调用方式:draw_indicator(img, 0.7) cv2.imshow("indicator test", img) cv2.waitKey(0) cv2.destroyAllWindows()
修改说明
- 新增4个可缺省入参,兼容原有调用逻辑:
x:仪表盘左上角的水平坐标,默认值为10y:仪表盘左上角的垂直坐标,未传值时默认放在图片左下角bottom_color:最底部刻度的颜色,BGR格式,默认值为纯绿色top_color:最顶部刻度的颜色,BGR格式,默认值为纯红色
- 替换原有固定颜色逻辑,通过BGR三通道线性插值实现从底部颜色到顶部颜色的平滑渐变
- 所有绘制坐标全部改为基于传入的x、y参数计算,支持在图片任意位置放置仪表盘
- 注意OpenCV默认使用BGR颜色顺序,传入自定义颜色时不要和RGB顺序混淆
内容的提问来源于stack exchange,提问作者angel_30
相关产品推荐
相关产品推荐

