gragas01
gragas01

Reputation: 25

Python: float() argument must be a string or a number

I need to load an image to the array. Then I want to show it by pyplot. The problem is somewhere in between.

I tried different types of imread. I got to install only the one from pyplot which my cause problem.

import numpy as np
from matplotlib.pyplot import imread

images = []
img = imread('1.png')
img = np.array(img.resize(224,224))
images.append(img)

images_arr = np.asarray(images)
images_arr = images_arr.astype('float32')

plt.figure(figsize=[5, 5])
curr_img = np.reshape(images_arr[0], (224,224))
plt.imshow(curr_img, cmap='gray')
plt.show()

There is the error:

images_arr = images_arr.astype('float32')
TypeError: float() argument must be a string or a number, not 'NoneType'

Upvotes: 0

Views: 692

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121574

The img.resize() method resizes your data in place and returns None. Don't use the return value to create an array, just use img directly. It's a numpy array already:

img = imread('1.png')
img.resize(224,224)  # alters the array in-place, returns None
images.append(img)   # so just use the array directly.

If you wanted a copy of the data, resized, use numpy.resize()`:

img = imread('1.png')
resized_img = np.resize(img, (224,224))
images.append(resized_img)

Note that the matplotlib.pyplot.imread() function is nothing more than an alias for matplotlib.image.imread().

Upvotes: 2

Related Questions