我有一個顯示視頻并顯示其灰度直方圖的代碼,我想添加 2 條水平線:一條用于直方圖的實際最大值,另一條用于最后一個最大值。因此,我嘗試繪制 3 條 hlines:一條為實際最大值,一條為綠色,最后一條為綠色,第三條為白色,以洗掉我不再需要的線,因為已找到新的最大值。但是第三行沒有達到我的預期,舊的最大線仍然可見,看起來顏色組合,因為線是淺綠色,我不知道如何洗掉它們。
也許有更好的方法來做我想做的事,但我不知道。

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_old = 0
max_med = 0
x = np.linspace(0, 255, 256)
y = np.linspace(0.1, 100000, 256)
plt.ion()
#FPS variables
prev_frame_time = 0
new_frame_time = 0
#plt.subplots() is a function that returns a tuple containing a figure and axes object(s)
figure, ax = plt.subplots(1, 1, figsize=(10, 8))
line1, = ax.plot(x, y)
ax.set_yscale('log')
"""ax.autoscale()"""
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 #Police du texte
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])
line1.set_ydata(histogram)
max_new = np.amax(histogram[150:256])
if max_new > max_med :
plt.hlines(max_old, 0, 255, 'w')
plt.hlines(max_med, 0, 255, 'g')
plt.hlines(max_new, 0, 255, 'r')
max_old = max_med
max_med = 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')
uj5u.com熱心網友回復:
您可以通過將它們的 set_visible 屬性設定為 false 來隱藏這些線。
redline=plt.hlines(max_new, 0, 255, 'r')
....
redline.set_visible(False)
正如@tmdavison 提到的,通過 redline.remove() 洗掉它們
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/350076.html
標籤:Python matplotlib 视频处理 简历2
