Home > Mobile >  Remove horizontal lines for histogram in a loop
Remove horizontal lines for histogram in a loop

Time:11-06

I have a code that display a video and show its greyscale histogram, and I would like to add 2 horizontal lines : one for the actual maximum value of the histogram, and one for the last maximum value. So I tried to plot 3 hlines : one in red for the actual max, one in green for the last one, and the third in white to remove a line that I dont need anymore because a new max has been found. But the third line doesnt do what I expect, the old maximum lines are still visible, it looks like colors combine because lines are light green, and I dont know how to remove them.

Maybe there is a better way to do what I want to do, but I dont know it.

Histogram result

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

CodePudding user response:

You can hide the lines by setting their set_visible attribute to false.

redline=plt.hlines(max_new, 0, 255, 'r')
....
redline.set_visible(False)

And as @tmdavison mentioned, remove them by redline.remove()

  • Related