MichM
MichM

Reputation: 896

matplotlib: ValueError: invalid PNG header

import matplotlib.pyplot as plt

I tried to imread a png photo among many other png photos in the same folder. Some photos read with no errors using the following line, and some returns "ValueError: invalid PNG header". What could be the cause? They all look like normal photos to me.

plt.imread(filename)

Upvotes: 9

Views: 19945

Answers (2)

Shivam Kotwalia
Shivam Kotwalia

Reputation: 1493

As @MichM has already stated that somehow the header of your image has changed and it is not a valid png image. Read the image as

plt.imread(filename, 0)

If you read the Matplotlib imread's doc at https://matplotlib.org/api/_as_gen/matplotlib.pyplot.imread.html?highlight=imread#matplotlib.pyplot.imread

--> If format is provided, will try to read file of that type, otherwise the format is deduced from the filename. If nothing can be deduced, PNG is tried. <--

Upvotes: 11

MichM
MichM

Reputation: 896

It turns out someone must have manually changed the jpg files into the png extension before I got those files. These files open correctly in the picture viewer from the OS, hence look indistinguishable from the actual png files in the same batch, but they can't be processed by python scripts as png files -- because they are not. They don't have the alpha channel.

Upvotes: 2

Related Questions