# initialize the class labels
classLabels = ["cat", "dog", "panda"]

# grab the list of images in the dataset and randomly sample indexes into image path list
print("[INFO] sampling images...")
imagePaths = list(paths.list_images(args["dataset"]))
idxs = np.random.randint(0, len(imagePaths), size=(10, ))
imagePaths = np.array(imagePaths)[idxs]

# initialize the image preprocessors
sp = SimplePreprocessor(32, 32)
iap = ImageToArrayPreprocessor()

# load the dataset from disk and scale the raw pixel intensities to range [0, 1]
sdl = SimpleDatasetLoader(preprocessors=[sp, iap])
(data, labels) = sdl.load(imagePaths)
data = data.astype("float") / 255.0

# load the pre-trained network
print("[INFO] loading pre-trained network...")
model = load_model(args["model"])

# make predictions on image
print("[INFO] predicting...")
preds = model.predict(data, batch_size=32).argmax(axis=1)

# loop over the sample images
for (i, imagePath) in enumerate(imagePaths):
    # load the example image draw its prediction, and display it to our screen
    image = cv2.imread(imagePath)
    cv2.putText(image, "Label: {}".format(classLabels[preds[i]]), (10, 30),
Exemple #2
0
ap.add_argument('-d', '--dataset', required=True,
                help='Path to input dataset')
ap.add_argument('-n', '--neighbors', required=False, type=int, default=1,
                help='# of nearest neighbors for classification')
ap.add_argument('-j', '--jobs', required=False, type=int, default=-1,
                help='# of jobs for k-NN distance (-1 uses all available cores)')
args = vars(ap.parse_args())

# Get list of image paths
image_paths = list(paths.list_images(args['dataset']))

# Initialize SimplePreprocessor and SimpleDatasetLoader and load data and labels
print('[INFO]: Images loading....')
sp = SimplePreprocessor(32, 32)
sdl = SimpleDatasetLoader(preprocessors=[sp])
(data, labels) = sdl.load(image_paths, verbose=500)

# Reshape from (3000, 32, 32, 3) to (3000, 32*32*3=3072)
data = data.reshape((data.shape[0], 3072))


# Print information about memory consumption
print('[INFO]: Features Matrix: {:.1f}MB'.format(
    float(data.nbytes / (1024*1000.0))))

# Encode labels as integers
le = LabelEncoder()
labels = le.fit_transform(labels)

# Split data into training (75%) and testing (25%) data
(train_x, test_x, train_y, test_y) = train_test_split(
model_name = input("Please input name of pretrained ImageNet model to use: ")
if model_name not in MODELS.keys():
    raise AssertionError(
        "The model name should either be xception, resnet50, inception")

input_shape = (224, 224)
preprocess = imagenet_utils.preprocess_input
if model_name in ("xception", "inception"):
    input_shape = (299, 299)
    preprocess = preprocess_input
(height, width) = input_shape

Network = MODELS[model_name]
model = Network(weights="imagenet")

#importing the dataset and exploring its possibilities
imagePaths = list(
    paths.list_images(
        r"C:\Users\Michael\Desktop\Data Science\DL4CVStarterBundle-master\DL4CVStarterBundle-master\datasets\animals"
    ))
sp = SimplePreprocessor(height, width)
sdl = SimpleDatasetLoader(preprocessors=[sp])
(dataset, _) = sdl.load(imagePaths)
images = preprocess(dataset)
preds = model.predict(dataset)
P = imagenet_utils.decode_predictions(preds)

model = Xception()
plot_model(model, to_file="Xception.png", show_shapes=True)
ann_viz(model, title="some neural network model", filename="picture.gv")
Exemple #4
0
##prepare the image data generator for data augmentaion
#aug = ImageDataGenerator(rotation_range=30, width_shift_range = 0.1, height_shift_range = 0.1,
#                         shear_range = 0.2, zoom_range = 0.2, horizontal_flip = True, fill_mode = "nearest")

#preparing the data and the list of images
imagePaths = list(paths.list_images(r"C:\Users\H P ENVY\Desktop\Data Science\My directory set-up for Computer-Vision\datasets\Flowers17"))
classNames = [pt.split(os.path.sep)[-2] for pt in imagePaths]
classNames = [str(x) for x in np.unique(classNames)]
#baseModel  = VGG16()
aap = AspectAwarePreprocessor(224,224)
isp = ImageToArrayPreprocessor()

#load the dataset from disk and then 
sdl = SimpleDatasetLoader(preprocessors = [aap, isp])
(data, labels) = sdl.load(imagePaths, verbose = 1)
data = data.astype("float") / 255.0

#split the dataset into the required stages
(trainX, testX, trainY, testY) = train_test_split(data, labels, test_size = 0.25, random_state = 42)

#Binarize the labels
trainY = LabelBinarizer().fit_transform(trainY)
testY = LabelBinarizer().fit_transform(testY)

#introduce the baseModel, buiid the headmodel, introduce the class objects
#baseModel = inception_v3.InceptionV3
baseModel = VGG16(weights = "imagenet", include_top = False, input_tensor  = Input(shape = (224,224,3)))
headModel = FCHeadNet.build(baseModel, len(classNames), 256)
model = Model(inputs  = baseModel.input , outputs = headModel)
Exemple #5
0
from keras.callbacks import LearningRateScheduler, ModelCheckpoint
from keras.utils import plot_model
import pydot
from keras import backend as K
import numpy as np
import matplotlib.pyplot as plt
from ann_visualizer.visualize import ann_viz

#importing and preprocessing the dataset
imagePaths = list(
    paths.list_images(
        r'C:\Users\Michael\Desktop\Data Science\DL4CVStarterBundle-master\DL4CVStarterBundle-master\datasets\animals'
    ))
sp = SimplePreprocessor(32, 32)
sdl = SimpleDatasetLoader(preprocessors=[sp])
(dataset, labels) = sdl.load(imagePaths, verbose=1000)
dataset = dataset.astype('float') / 255.0
trainX, testX, trainY, testY = train_test_split(dataset,
                                                labels,
                                                random_state=42,
                                                test_size=0.25)
lb = LabelBinarizer()
trainY = lb.fit_transform(trainY)
testY = lb.fit_transform(testY)

#build the ML model and use Learning_rate _decay
sgd = SGD(lr=0.01, momentum=0.9, nesterov=True)
#model = LeNet.build(width=32, height=32, depth=3, classes = 3)
model = MiniVGGNet.build(width=32, height=32, depth=3, classes=3)
model.compile(optimizer=sgd,
              loss="categorical_crossentropy",
Exemple #6
0
from keras.optimizers import SGD
from keras.models import load_model
from imutils import paths
import matplotlib.pyplot as plt
import numpy as np
import cv2

#miporting the dataset and preprocessing
imagePaths = list(
    paths.list_images(
        r'C:\Users\Michael\Desktop\Data Science\DL4CVStarterBundle-master\DL4CVStarterBundle-master\datasets\animals'
    ))
sp = SimplePreprocessor(32, 32)
ita = ImageToArrayPreprocessor()
sdl = SimpleDatasetLoader(preprocessors=[sp])
(dataset, labels) = sdl.load(imagePaths, verbose=500)
dataset = dataset.astype("float") / 255.0

trainX, testX, trainY, testY = train_test_split(dataset,
                                                labels,
                                                test_size=0.25,
                                                random_state=42)
lb = LabelBinarizer()
trainY = lb.fit_transform(trainY)
testY = lb.fit_transform(testY)

#training the network
print("[INFO] Uploading model")
sgd = SGD(lr=0.005)
model = ShallowNet.build(32, 32, 3, 3)
model.compile(optimizer=sgd,
                "--model",
                required=True,
                help="path to the output model")
args = vars(ap.parse_args())

# grab the list of images we'll be describing
print("[INFO] loading images...")
imagePaths = list(paths.list_images(args["dataset"]))

# initialize the image preprocessors
sp = SimplePreprocessor(32, 32)
iap = ImageToArrayPreprocessor()

# load the dataset from disk then scale the raw pixel intensities to the range [0, 1]
sdl = SimpleDatasetLoader(preprocessors=[sp, iap])
(data, label) = sdl.load(imagePaths, verbose=500)
data = data.astype("float") / 255.0

# partition the data into training and testing splits using 75% for the training and remaining 25% for testing
(trainX, testX, trainY, testY) = train_test_split(data,
                                                  label,
                                                  test_size=0.25,
                                                  random_state=42)

# convert the labels from integers to vectors
trainY = LabelBinarizer().fit_transform(trainY)
testY = LabelBinarizer().fit_transform(testY)

# initialize the optimizer module
print("[INFO] compiling the model...")
opt = SGD(lr=0.0009)