Home > database >  How do I save multiple histograms to different (separate) files?
How do I save multiple histograms to different (separate) files?

Time:06-01

I'm trying to save a bunch of histograms as images. And this is what I did so far.

for i in range(len(images)):
    histogram, bin_edges = np.histogram(images[i].ravel(), 256, [0, 256])
    plt.plot(histogram)
    plt.show()

Output of the above code:

Output of the above code

This output is fine, but I want to save these as images.

I used plt.savefig() but this isn't the result I'm looking for.

for i in range(len(images)):
    histogram, bin_edges = np.histogram(images[i].ravel(), 256, [0, 256])
    plt.plot(histogram)
    plt.savefig("histograms/hist_frame" str(count) ".png")
    count =1

Output of the above code:

output of the above code.

How do I save these histograms in separate files?

CodePudding user response:

Your current code is plotting every histogram on the same figure, In order to have multiple figures, you need to create a new figure for each plot:

for i in range(len(images)):
  plt.figure()
  histogram, bin_edges = np.histogram(images[i].ravel(), 256, [0, 256])
  plt.plot(histogram)
  plt.savefig("histograms/hist_frame" str(count) ".png")
  count =1

Note that if showing the plot, plt.show() should follow plt.savefig(), otherwise the file image will be blank.

  • Related