Search code examples
pythonimagematplotlibiogoogle-colaboratory

Matplotlib savefig exporting as blank image in colab


Hello I am using Google Colab to do some image processing on images.

After doing said processing and doing some evaluations I want to save figure with matplotlib.

Here is my code:


def get_images():
  frame_images = glob.glob("/content/images/*.jpg")
  for n in sorted(frame_images):
    print(n)
    images = matplotlib.pyplot.imread(n)
    yield (images)

def process():
    frames_in_sharp = 0
    sharpened_image = None
    dark_frames = 0
    capture = True
    frame_count = 0
    for (frame) in get_images():
        lower = frame.max()

        if lower < 120:
            dark_frames += 1

            if dark_frames > 18 and sharpened_image is not None:
              
                
                fig1 = matplotlib.pyplot.imshow(sharpened_image, cmap = "jet")
                matplotlib.pyplot.savefig(f"/pictures/{frame_count}.png", dpi=1000)
                matplotlib.pyplot.show()
                matplotlib.pyplot.draw()
                frames_in_sharp = 0
                sharpened_image = None
        else:
            if capture and dark_frames > 18:

                sharpened_image = numpy.asarray(cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY), numpy.uint32)
                frames_in_sharp = 1


            dark_frames = 0

        if frames_in_sharp > 0:
            frames_in_sharp += 1
            plus_frame = numpy.asarray(cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY), numpy.uint32)
            values_k = numpy.zeros(numpy.shape(sharpened_image), numpy.uint)
            numpy.copyto(values_k, plus_frame, where = plus_frame > 10)
            sharpened_image += values_k


       
        frame_count+=1


process()

When I run this and try other different combinations I have found online, I keep getting a blank white file written. matplotlib.pyplot.imshow shows the image correctly.

What am I doing wrong?


Solution

  • Ola @devman3211 o/

    I'm a Google Colab user too :)

    • Have you check if the plot respect your condition?

    • If yes, try to change not sharpened_image is None for sharpened_image is not None.

    You have to respect a certain order of priority, update your code considering the following:

    #first generate your plot
    fig1 = plt.imshow(#whatever you want to plot)
    
    #then save it
    plt.savefig('test.png', dpi=1000)
    
    #finally .show() or .draw() it in this order
    plt.show()
    plt.draw()
    

    Proof of work: enter image description here

    Result (for fun): enter image description here