Search code examples
pythonimagenumpyimage-resizing

Python AttributeError: 'numpy.ndarray' object has no attribute 'append'


I am trying to parse a folder with contains csv file (These csv files are pixel images position) and store them into a numpy array. When I try to perform this action, I have an error: AttributeError: 'numpy.ndarray' object has no attribute 'append'. I understand that NumPy arrays do not have an append().

However in my code I used the method: images.append(img)

Could you tell what I am doing badly in?

Here my code:

# Create an empty list to store the images
images = []

# Iterate over the CSV files in the img_test folder
for file in os.listdir("img_test"):
    if file.endswith(".txt"):
        # Read the CSV file into a dataframe
        df = pd.read_csv(os.path.join("img_test", file), delim_whitespace=True, header=None, dtype=float)

        # Convert the dataframe to a NumPy array
        image = df.to_numpy()

        # Extract the row and column indices and the values
        rows, cols, values = image[:, 0], image[:, 1], image[:, 2]

        # Convert the row and column indices to integers
        rows = rows.astype(int)
        cols = cols.astype(int)

        # Create a 2D array of the correct shape filled with zeros
        img = np.zeros((1024, 1024))

        # Assign the values to the correct positions in the array
        img[rows, cols] = values

        # Resize the image to 28x28
        img = cv2.resize(img, (28, 28))

        # Reshape the array to a 3D array with a single channel
        img = img.reshape(28, 28, 1)

        # Append the image to the list
        images.append(img)

    # Convert the list of images to a NumPy array
    images = np.concatenate(images, axis=0)

Solution

  • The indentation of the last line is wrong. You may want to concatenate after the end of the for loop