Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
import cv2
# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--input", required=True,
help="path to input directory of images")
ap.add_argument("-m", "--model", required=True,
help="path to input model")
args = vars(ap.parse_args())
# load the pre-trained network
print("[INFO] loading pre-trained network...")
model = load_model(args["model"])
# randomy sample a few of the input images
imagePaths = list(paths.list_images(args["input"]))
imagePaths = np.random.choice(imagePaths, size=(10,),
replace=False)
# loop over the image paths
for imagePath in imagePaths:
# load the image and convert it to grayscale, then pad the image
# to ensure digits caught only the border of the image are
# retained
image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.copyMakeBorder(gray, 20, 20, 20, 20,
cv2.BORDER_REPLICATE)
# threshold the image to reveal the digits
thresh = cv2.threshold(gray, 0, 255,
cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]
import cv2
import os
# Construct the argument parse and parse the arguments.
ap = argparse.ArgumentParser()
ap.add_argument("-d", "--dataset", required=True, help="path to input dataset of faces.")
ap.add_argument("-o", "--output", required=True, help="path to output plot.")
ap.add_argument("-m", "--model", required=True, help="path to output model.")
args = vars(ap.parse_args())
# Initialize the list of data and labels.
data = []
labels = []
count = 1
# Loop over the input images.
for imagePath in sorted(list(paths.list_images(args["dataset"]))):
print("[INFO] loading and pre-process images -- no.{}".format(count))
# Load the image, pre-process it and then store it in the data list.
image = cv2.imread(imagePath)
# Convert image to gray-scale.
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Resize image size from original 64*64 to 28*28 pixels.
image = imutils.resize(image, width=28)
# Convert image to an array compatible with keras and its channel ordering.
image = img_to_array(image)
# Update training set.
data.append(image)
# Extract the class label from the image path since the dir's name is its label and update the labels list.
label = imagePath.split(os.path.sep)[-3]
label = "smiling" if label == "positives" else "not_smiling"
labels.append(label)
import numpy as np
import argparse
import cv2
import os
# Construct the argument parse and parse the arguments.
ap = argparse.ArgumentParser()
ap.add_argument("-d", "--dataset", required=True, help="path to input dataset")
ap.add_argument("-o", "--output", required=True, help="path to output plot and model")
args = vars(ap.parse_args())
# Initialize the data and labels.
data = []
labels = []
# Loop over the input images.
for imagePath in paths.list_images(args["dataset"]):
# Load the image, pre-process it, and store it in the data list.
image = cv2.imread(imagePath)
# Convert image to gray-scale.
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
image = preprocess(image, 28,28)
# Convert image to an array compatible with keras and its channel ordering.
image = img_to_array(image)
data.append(image)
# Extract the class label from the image path and update the labels list.
label = imagePath.split(os.path.sep)[-2]
labels.append(label)
# Scale the raw pixel intensities to the range [0, 1].
data = np.array(data, dtype="float") / 255.0
labels = np.array(labels)
# Data set split as 4:1.
import numpy as np
import argparse
import os
ap = argparse.ArgumentParser()
ap.add_argument('-d','--dataset',required=True,help='path to input dataset')
args = vars(ap.parse_args())
print('[INFO] moving image to label folder.....')
im = IM.MoveImageToLabel(dataPath=args['dataset'])
im.makeFolder()
im.move()
print("[INFO] loading images...")
imagePaths = [ x for x in list(paths.list_images(args['dataset'])) if x.split(os.path.sep)[-2] !='jpg']
classNames = [pt.split(os.path.sep)[-2] for pt in imagePaths ]
classNames = [str(x) for x in np.unique(classNames)]
aap = AAP.AspectAwarePreprocesser(64,64)
iap = IAP.ImageToArrayPreprocess()
sdl = SDL.SimpleDatasetLoader(preprocessors = [aap,iap])
(data,labels) = sdl.load(imagePaths,verbose = 500)
data = data.astype('float') / 255.0
(trainX,testX,trainY,testY) = train_test_split(data,labels,test_size=0.25,random_state =43)
trainY = LabelBinarizer().fit_transform(trainY)
testY = LabelBinarizer().fit_transform(testY)
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from pyimagesearch.preprocessing import SimplePreprocessor
from pyimagesearch.datasets import SimpleDatasetLoader
from imutils import paths
import argparse
# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-d", "--dataset", required=True,
help="path to input dataset")
args = vars(ap.parse_args())
# grab the list of images paths
print("[INFO] loading images...")
imagePaths = list(paths.list_images(args["dataset"]))
# initialize the image preprocessor, load the dataset from disk,
# and reshape the data matrix
sp = SimplePreprocessor(32, 32)
sdl = SimpleDatasetLoader(preprocessors=[sp])
(data, labels) = sdl.load(imagePaths, verbose=500)
data = data.reshape((data.shape[0], 3072))
# encode the labels as integers
le = LabelEncoder()
labels = le.fit_transform(labels)
# partition the data into training and testing splits using 75% of
# the data for training and the remaining 25% for testing
(trainX, testX, trainY, testY) = train_test_split(data, labels,
test_size=0.25, random_state=42)
import glob
import numpy as np
import argparse
import os
# Construct the argument parse and parse the arguments.
ap = argparse.ArgumentParser()
ap.add_argument("-d", "--dataset", default="../../sourceCode/practitionerBundle/PBCode/datasets/flowers17/images",
help="path to input dataset")
ap.add_argument("-a", "--augment", action='store_true', help="whether to use data augmentaion")
args = vars(ap.parse_args())
CLASSES = len(glob.glob("{}/*".format(args["dataset"])))
# Grab the list of images that we'll be describing, then extract the class label names from the image paths.
print("[INFO] loading images...")
imagePaths = list(paths.list_images(args["dataset"]))
classNames = [path.split(os.path.sep)[-2] for path in imagePaths]
classNames = [str(x) for x in np.unique(classNames)]
# Initialize the image preprocessors.
# Resize image to 64 * 64 for input.
aap = AspectAwarePreprocessor(64, 64)
# Convert image to Keras-compatible arrays.
iap = ImageToArrayPreprocessor()
# Load the dataset from disk then scale the raw pixel intensities to the range [0, 1] by dividing the raw pixel intensities by 255.
sdl = SimpleDatasetLoader(preprocessors=[aap, iap])
(data, labels) = sdl.load(imagePaths, verbose=500)
data = data.astype("float") / 255.0
# Convert the labels from integers to vectors.
# Keras.utils.to_categorical() can just transform "integer" label to one-hot code array.
"""
from imutils import paths
from icecream import ic
import argparse
import imutils
import cv2
import os
# Construct the argument parse and parse the arguments.
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--input", required=True, help="path to input directory of images.")
ap.add_argument("-o", "--output", required=True, help="path to output directory of annotations.")
args = vars(ap.parse_args())
# Grab the image paths then initialize the dictionary of character counts.
imagePaths = list(paths.list_images(args["input"]))
counts = {}
# Loop over the image paths.
for (i, imagePath) in enumerate(imagePaths):
# Display an update to the user
print("[INFO] processing image {}/{}".format(i+1, len(imagePaths)))
try:
# Load the image and covert it to gray-scale.
image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Padding the image with 8 pixels in every direction to ensure digits caught on the border of the image are retained.
#(just in case any of digits images are touching the border of the image.
gray = cv2.copyMakeBorder(gray, 8, 8, 8, 8, cv2.BORDER_REPLICATE)
# Threshold the image to reveal the digits(A typical assumption when working with many image processing functions with OpenCV).
from keras.optimizers import SGD
from sklearn.metrics import classification_report
from sklearn.metrics import accuracy_score
# override truncated images error
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
# define constants and parameters
train_data_dir = "train"
test_data_dir = "test"
TRAIN = len(list(paths.list_images(train_data_dir)))
TEST = len(list(paths.list_images(test_data_dir)))
BS = 10
EPOCHS = 20
img_width, img_height = 300, 300
# create model skeleton
base_model = VGG19(weights = "imagenet", include_top=False,
input_shape = (img_width, img_height, 3))
x = base_model.output
x = Flatten()(x)
x = Dense(1024, activation = "relu")(x)
x = Dropout(0.4)(x)
x = Dense(256, activation = "relu")(x)
x = Dropout(0.1)(x)
preds = Dense(2, activation = "softmax")(x)
def load_caltech_faces(datasetPath, min_faces=10, face_size=(47, 62), equal_samples=True,
test_size=0.33, seed=42, flatten=False):
# grab the image paths associated with the faces, then load the bounding box data
imagePaths = sorted(list(paths.list_images(datasetPath)))
bbData = io.loadmat("{}/ImageData.mat".format(datasetPath))
bbData = bbData["SubDir_Data"].T
# set the random seed, then initialize the data matrix and labels
random.seed(seed)
data = []
labels = []
# loop over the image paths
for (i, imagePath) in enumerate(imagePaths):
# load the image and convert it to grayscale
image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# grab the bounding box associated with the current image, extract the face
# ROI, and resize it to a canonical size
from sklearn.cross_validation import train_test_split
from sklearn.metrics import classification_report
from imutils import paths
import numpy as np
import argparse
import cv2
# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--images", required=True, help="path to the image dataset")
ap.add_argument("-m", "--masks", required=True, help="path to the image masks")
args = vars(ap.parse_args())
# grab the image and mask paths
imagePaths = sorted(list(paths.list_images(args["images"])))
maskPaths = sorted(list(paths.list_images(args["masks"])))
# initialize the list of data and class label targets
data = []
target = []
# initialize the image descriptor
desc = RGBHistogram([8, 8, 8])
# loop over the image and mask paths
for (imagePath, maskPath) in zip(imagePaths, maskPaths):
# load the image and mask
image = cv2.imread(imagePath)
mask = cv2.imread(maskPath)
mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)
# describe the image