load_img, keras.preprocessing.image, TypeError: требуется целое число (получил тип str) - PullRequest
1 голос
/ 20 марта 2020

я строю классификатор изображений , используя некоторые изображения рукописных чисел , которые у меня есть в формате PNG
изображения, которые я хочу проверить у него другое измерение, но все около 200 по ширине и 60-50 по высоте, я попытался создать небольшой набор данных, состоящий всего из 2 чисел, с обучающим набором для обоих чисел и набором проверки.
пожалуйста, обратите внимание что imab newb ie для классификации изображений xD!
Заранее спасибо Вот полный код того, как я загрузил свой набор данных и сделал модель

from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras import backend as K


# dimensions of our images.
img_width, img_height = 200, 55

train_data_dir = 'C:/Users/ADEM/Desktop/msi_youssef/PFE/test/numbers/data/train'
validation_data_dir = 'C:/Users/ADEM/Desktop/msi_youssef/PFE/test/numbers/data/validation'
nb_train_samples = 140
nb_validation_samples = 30
epochs = 10 # how much time you want to train your model on the data
batch_size = 16

if K.image_data_format() == 'channels_first':
    input_shape = (3, img_width, img_height)
else:
    input_shape = (img_width, img_height, 3)

model = Sequential()
model.add(Conv2D(32, (3, 3), input_shape=input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(32, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Flatten())
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(1))
model.add(Activation('sigmoid'))

model.compile(loss='binary_crossentropy',optimizer='rmsprop',metrics=['accuracy'])

# this is the augmentation configuration we will use for training
train_datagen = ImageDataGenerator(
    rescale=1. / 255,
    shear_range=0.1,
    zoom_range=0.05,
    horizontal_flip=False)

# this is the augmentation configuration we will use for testing:
# only rescaling
test_datagen = ImageDataGenerator(rescale=1. / 255)

train_generator = train_datagen.flow_from_directory(
    train_data_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode='binary')

validation_generator = test_datagen.flow_from_directory(
    validation_data_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode='binary')

model.fit_generator(
    train_generator,
    steps_per_epoch=nb_train_samples // batch_size,
    epochs=epochs,
    validation_data=validation_generator,
    validation_steps=nb_validation_samples // batch_size)

model.save('first_try.h5')

и вот как я хотел проверить модель

from tensorflow.keras.preprocessing.image import load_img
from tensorflow.keras.preprocessing.image import img_to_array
from tensorflow.keras.models import load_model


# load and prepare the image
def load_image(filename):
    # load the image
    img = load_img(filename, color_mode="grayscale", target_size='None',interpolation='nearest')
    # convert to array
    img = img_to_array(img)
    # reshape into a single sample with 1 channel
    img = img.reshape(1, 255, 55, 1)
    # prepare pixel data
    img = img.astype('float32')
    img = img / 255.0
    return img




# load an image and predict the class
def run_example():
    # load the image
    img = load_image('C:/Users/ADEM/Desktop/msi_youssef/PFE/dataset/10/kz.png')
    # load model
    model = load_model('C:/Users/ADEM/Desktop/msi_youssef/PFE/other_shit/first_try.h5')
    # predict the class
    digit = model.predict_classes(img)
    print(digit[0])


# entry point, run the example
run_example()

вот ошибка:

TypeError                                 Traceback (most recent call last)
<ipython-input-15-d7128de19125> in <module>
     32 
     33 # entry point, run the example
---> 34 run_example()

<ipython-input-15-d7128de19125> in run_example()
     23 def run_example():
     24     # load the image
---> 25     img = load_image('C:/Users/ADEM/Desktop/msi_youssef/PFE/dataset/10/kz.png')
     26     # load model
     27     model = load_model('C:/Users/ADEM/Desktop/msi_youssef/PFE/other_shit/first_try.h5')

<ipython-input-15-d7128de19125> in load_image(filename)
      7 def load_image(filename):
      8     # load the image
----> 9     img = load_img(filename, color_mode="grayscale", target_size='None',interpolation='nearest')
     10     # convert to array
     11     img = img_to_array(img)

~\Anaconda3\lib\site-packages\keras_preprocessing\image\utils.py in load_img(path, grayscale, color_mode, target_size, interpolation)
    130                         ", ".join(_PIL_INTERPOLATION_METHODS.keys())))
    131             resample = _PIL_INTERPOLATION_METHODS[interpolation]
--> 132             img = img.resize(width_height_tuple, resample)
    133     return img
    134 

~\Anaconda3\lib\site-packages\PIL\Image.py in resize(self, size, resample, box)
   1886         self.load()
   1887 
-> 1888         return self._new(self.im.resize(size, resample, box))
   1889 
   1890     def rotate(

TypeError: an integer is required (got type str)

1 Ответ

0 голосов
/ 20 марта 2020

В приведенном выше коде просто измените None на None в методе load_image. Ни один из них не является отдельным типом данных в Python.

img = load_img(filename, color_mode="grayscale", target_size=None,interpolation='nearest')

Извините, у меня недостаточно средств для комментирования, поэтому я ответил на него. Дайте мне знать, если это поможет.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...