Ejemplo n.º 1
0
ap = argparse.ArgumentParser()
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
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")
# 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)
Ejemplo n.º 4
0
import cv2

##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)