简体   繁体   中英

How to load a jpg image to a 3d rgb numpy array

I have made a tensorflow model and have trained and tested it on directories of image using the model.fit_generator method. But know I want to use it on a single image and there aren't any methods i can find that allow this so i decided to use numpy arrays by converting a jpg image to 3d rgb numpy array. How would you do this?

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

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

model.add(Convolution2D(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'])


nb_epoch = 1
nb_train_samples = 2048
nb_validation_samples = 832

#model.fit_generator(
#    train_generator,
#    samples_per_epoch=nb_train_samples,
#   nb_epoch=nb_epoch,
#   validation_data=validation_generator,   
#  nb_val_samples=nb_validation_samples)

Try using PIL (pip install Pillow):

from PIL import Image 
import numpy as np
im = Image.open("test.jpg")
im = np.array(im,dtype=np.float32)

And then to predict:

#Assuming batch size of 1 and data is normalised
y = model.predict(np.expand_dims(im/255,0))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM