1

I'm trying to iterate through a directory and resize every image using scikit-image but I keep getting the following error:

b'scene01601.png'
Traceback (most recent call last):
  File "preprocessingdatacopy.py", line 16, in <module>
    image_resized = resize(filename, (128, 128))
  File "/home/briannagopaul/PycharmProjects/DogoAutoencoder/venv/lib/python3.6/site-packages/skimage/transform/_warps.py", line 104, in resize
    input_shape = image.shape
AttributeError: 'str' object has no attribute 'shape'

My code:

import skimage
from sklearn import preprocessing
from skimage import data, color
import os
from skimage.transform import resize, rescale
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import os
directory_in_str = "/home/briannagopaul/imagemickey/"
directory = os.fsencode(directory_in_str)
for file in os.listdir(directory):
    print(file)
    filename = os.fsdecode(file)
    if filename.endswith(".png"):
        image_resized = resize(filename, (128, 128))
        img = mpimg.imread(file)
        imgplot = plt.imshow(img)
        plt.show()
        filename.shape()

iiooii
  • 551
  • 2
  • 9
  • 15
  • 2
    It looks like you're trying to get the shape of the fileNAME rather than the actual FILE. The filename is a string, which doesn't have the `shape()` attribute. You're going to have to load the actual file into a variable, then call `shape()` on that variable – Jason K Lai Aug 06 '19 at 20:34
  • Thanks for the help. I tried using ```x = file.open()``` and then resized x and got the same error. Do you have any suggestions on how I should go about loading the file? @JasonKLai – iiooii Aug 06 '19 at 20:39

1 Answers1

4

First off, unless the code is run in the same directory as the image, you are going to want to specify the directory in the filename:

for file in os.listdir(directory):
    print(file)
    filename = directory_in_str + os.fsdecode(file)

But to address your question, you are already reading the image via the mpimg.imread line and storing this image as a numpy array called img. With that img variable, you can run it through the rest of your lines:

    if filename.endswith(".png"):
        img = mpimg.imread(filename)
        image_resized = resize(img, (128, 128))
        imgplot = plt.imshow(img)
        plt.show()
        print(img.shape)

Note that I changed two separate calls to filename to img instead. That's because filename is simply the name of the file and not the actual file, which in your case was called img.

Jason K Lai
  • 1,500
  • 5
  • 15