user1299784 user1299784 - 2 months ago 11x
Python Question

Scipy: UnicodeDecodeError while loading image file

def image_to_laplacian(filename):
with open(filename, 'r', encoding="latin-1") as f:
s =
img = sc.misc.imread(f)


UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte

"images/bw_3x3.png" is a 3x3 image I produced in Pinta. I tried opening a cat.jpg I got from Google Images, but I got the same error.

I also tried to use
as an argument to open, based on something I read on SO; I was able to open the file, but I'm
read failed with the exception

OSError: cannot identify image file <_io.TextIOWrapper name='images/bw_3x3.png' mode='r' encoding='latin-1'>


The line that is causing the error is

s =

In 'r' mode this tries to read the data as a string, but it's a image file, so it will fail. You can use 'rb' instead. Definitely remove the encoding=latin because that's only relevant for text files.

Also, note that according to the documentation:

name : str or file object

The file name or file object to be read.

So you can dispense with opening a file and just give it a filepath as a string. The following should work:

img = sc.misc.imread(filename)