I
I
Ilya Neizvestnyj2019-08-24 13:20:07
Python
Ilya Neizvestnyj, 2019-08-24 13:20:07

How to send an image to a neural network?

There is a simple convolution grid, how to transfer an image from the desktop to it and visualize it after it determines what is shown. The model itself is below.

from keras import models
from keras import layers
from keras import optimizers
from keras.preprocessing.image import ImageDataGenerator
from PIL import Image
from matplotlib import pyplot as plt
import os

base_dir = "C:/Users/pikro/OneDrive/Рабочий стол/dogs_vs_cats_small"
train_dir = os.path.join(base_dir, "train")
validation_dir = os.path.join(base_dir, "validation")
test_dir = os.path.join(base_dir, "test")

model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation="relu", input_shape=(150, 150, 3)))

model.add(layers.MaxPooling2D(2, 2))
model.add(layers.Conv2D(64, (3, 3), activation="relu"))
model.add(layers.MaxPooling2D(2, 2))
model.add(layers.Conv2D(128, (3, 3), activation="relu"))
model.add(layers.MaxPooling2D(2, 2))
model.add(layers.Conv2D(128, (3, 3), activation="relu"))
model.add(layers.MaxPooling2D(2, 2))
model.add(layers.Flatten())
model.add(layers.Dense(512, activation="relu"))
model.add(layers.Dense(1, activation="sigmoid"))

model.compile(loss="binary_crossentropy", optimizer=optimizers.RMSprop(lr=1e-4), metrics=["acc"])

train_datagen = ImageDataGenerator(rescale=1. / 255)
test_datagen = ImageDataGenerator(rescale=1. / 255)

train_generator = train_datagen.flow_from_directory(train_dir, target_size=(150, 150), batch_size=20,
                                                    class_mode="binary")
validation_generator = test_datagen.flow_from_directory(validation_dir, target_size=(150, 150), batch_size=20,
                                                        class_mode="binary")

history = model.fit_generator(train_generator,
                              steps_per_epoch=100,
                              epochs=30,
                              validation_data=validation_generator,
                              validation_steps=50)

model.save("1.h5")

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Arseny Kravchenko, 2019-08-24
@Cheloved

Read the image (`cv2.imread(img_path)[:, :, ::-1]`, do the same preprocessing (see what's inside `ImageDataGenerator`), load the model (`keras.model.load_model`, it seems) and predict (`model.predict(np.expand_dims(img, 0)`)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question