Python+Matplotlib动态绘制直方图时旧水平参考线清除问题求助
问题根源
你原有方案的核心问题是:每次调用plt.hlines都会在画布上新增独立的线条对象,所有线条是叠加渲染而非覆盖替换,白色线条仅能覆盖同坐标的部分像素,无法彻底移除旧的线条对象,多次叠加后自然会出现颜色混杂、旧线残留的问题。
优化方案
提前初始化两条参考线对象,后续仅动态更新它们的Y轴位置即可,无需反复绘制新线也不需要手动擦除旧线,修改后的完整代码如下:
import cv2 import matplotlib.pyplot as plt import numpy as np import time video = cv2.VideoCapture('output.avi') if (video.isOpened()== False): print("Error opening video file") max_history = 0 max_current = 0 x = np.linspace(0, 255, 256) y = np.linspace(0.1, 100000, 256) plt.ion() # FPS变量 prev_frame_time = 0 new_frame_time = 0 # plt.subplots()函数返回包含画布和轴对象的元组 figure, ax = plt.subplots(1, 1, figsize=(10, 8)) line_hist, = ax.plot(x, y) # 新增:提前初始化两条参考线 line_current_max, = ax.plot([0,255], [0,0], c='r', label='当前最大值') line_history_max, = ax.plot([0,255], [0,0], c='g', label='上一次最大值') ax.set_yscale('log') while(video.isOpened()): ret, image = video.read() if ret == True: gris = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) smaller_image = cv2.resize(gris,(640,480)) # 计算FPS font = cv2.FONT_HERSHEY_SIMPLEX # 字体 new_frame_time = time.time() fps = 1/(new_frame_time - prev_frame_time) prev_frame_time = new_frame_time fps = int(fps) fps = str(fps) cv2.putText(smaller_image, fps, (7, 70), font, 3, (100, 255, 0), 3, cv2.LINE_AA) cv2.imshow('Image', smaller_image) histogram = cv2.calcHist([smaller_image], [0], None, [256], [0, 256]) line_hist.set_ydata(histogram) max_new = np.amax(histogram[150:256]) if max_new > max_current : # 更新历史最大值线位置 line_history_max.set_ydata([max_current, max_current]) # 更新当前最大值线位置 line_current_max.set_ydata([max_new, max_new]) # 刷新最大值存储变量 max_history = max_current max_current = max_new figure.canvas.draw() figure.canvas.flush_events() time.sleep(0.001) if cv2.waitKey(25) & 0xFF == ord('q'): break else : break plt.ioff() video.release() cv2.destroyAllWindows() plt.close('all')
内容的提问来源于stack exchange,提问作者lapasq
相关产品推荐
相关产品推荐

