本文整理匯總了Python中keras.applications.imagenet_utils.preprocess_input方法的典型用法代碼示例。如果您正苦於以下問題:Python imagenet_utils.preprocess_input方法的具體用法?Python imagenet_utils.preprocess_input怎麽用?Python imagenet_utils.preprocess_input使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類keras.applications.imagenet_utils
的用法示例。
在下文中一共展示了imagenet_utils.preprocess_input方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: __getitem__
# 需要導入模塊: from keras.applications import imagenet_utils [as 別名]
# 或者: from keras.applications.imagenet_utils import preprocess_input [as 別名]
def __getitem__(self, idx):
images, masks = [], []
for (image_path, mask_path) in zip(self.image_path_list[idx * self.batch_size: (idx + 1) * self.batch_size],
self.mask_path_list[idx * self.batch_size: (idx + 1) * self.batch_size]):
image = cv2.imread(image_path, 1)
mask = cv2.imread(mask_path, 0)
image = self._padding(image)
mask = self._padding(mask)
# augumentation
augmentation = self.transformer(image=image, mask=mask)
image = augmentation['image']
mask = self._get_result_map(augmentation['mask'])
images.append(image)
masks.append(mask)
images = np.array(images)
masks = np.array(masks)
images = pinput(images)
return images, masks
開發者ID:JACKYLUO1991,項目名稱:Face-skin-hair-segmentaiton-and-skin-color-evaluation,代碼行數:26,代碼來源:data_loader.py
示例2: display_heatmap
# 需要導入模塊: from keras.applications import imagenet_utils [as 別名]
# 或者: from keras.applications.imagenet_utils import preprocess_input [as 別名]
def display_heatmap(new_model, img_path, ids, preprocessing=None):
# The quality is reduced.
# If you have more than 8GB of RAM, you can try to increase it.
img = image.load_img(img_path, target_size=(800, 1280))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
if preprocessing is not None:
x = preprocess_input(x)
out = new_model.predict(x)
heatmap = out[0] # Removing batch axis.
if K.image_data_format() == 'channels_first':
heatmap = heatmap[ids]
if heatmap.ndim == 3:
heatmap = np.sum(heatmap, axis=0)
else:
heatmap = heatmap[:, :, ids]
if heatmap.ndim == 3:
heatmap = np.sum(heatmap, axis=2)
plt.imshow(heatmap, interpolation="none")
plt.show()
示例3: helper_test
# 需要導入模塊: from keras.applications import imagenet_utils [as 別名]
# 或者: from keras.applications.imagenet_utils import preprocess_input [as 別名]
def helper_test(model):
img_path = "../examples/dog.jpg"
new_model = to_heatmap(model)
# Loading the image
img = image.load_img(img_path, target_size=(800, 800))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
out = new_model.predict(x)
s = "n02084071" # Imagenet code for "dog"
ids = synset_to_dfs_ids(s)
heatmap = out[0]
if K.image_data_format() == 'channels_first':
heatmap = heatmap[ids]
heatmap = np.sum(heatmap, axis=0)
else:
heatmap = heatmap[:, :, ids]
heatmap = np.sum(heatmap, axis=2)
print(heatmap.shape)
assert heatmap.shape[0] == heatmap.shape[1]
K.clear_session()
示例4: test_preprocess_input
# 需要導入模塊: from keras.applications import imagenet_utils [as 別名]
# 或者: from keras.applications.imagenet_utils import preprocess_input [as 別名]
def test_preprocess_input():
# Test image batch
x = np.random.uniform(0, 255, (2, 10, 10, 3))
assert utils.preprocess_input(x).shape == x.shape
out1 = utils.preprocess_input(x, 'channels_last')
out2 = utils.preprocess_input(np.transpose(x, (0, 3, 1, 2)),
'channels_first')
assert_allclose(out1, out2.transpose(0, 2, 3, 1))
# Test single image
x = np.random.uniform(0, 255, (10, 10, 3))
assert utils.preprocess_input(x).shape == x.shape
out1 = utils.preprocess_input(x, 'channels_last')
out2 = utils.preprocess_input(np.transpose(x, (2, 0, 1)),
'channels_first')
assert_allclose(out1, out2.transpose(1, 2, 0))
示例5: image_batch_preprocess
# 需要導入模塊: from keras.applications import imagenet_utils [as 別名]
# 或者: from keras.applications.imagenet_utils import preprocess_input [as 別名]
def image_batch_preprocess(imgBatch, params, meanVals):
"""
Apply preprocessing operations to the image data that also need to be applied during inference
:param imgBatch: numpy array containing image data
:param params: input parameters from params.py
:param meanVals: used for mean subtraction if non-rgb imagery
:return: numpy array containing preprocessed image data
"""
if params.NUM_CHANNELS==3:
imgBatch = imagenet_utils.preprocess_input(imgBatch)
imgBatch = imgBatch / 255.0
else:
for c in range(params.NUM_CATEGORIES):
imgBatch[:,:,:,c] -= meanVals[c]
imgBatch = imgBatch / params.MAX_VAL
return imgBatch
示例6: preprocess
# 需要導入模塊: from keras.applications import imagenet_utils [as 別名]
# 或者: from keras.applications.imagenet_utils import preprocess_input [as 別名]
def preprocess(self, raw_inputs):
"""
Args:
raw_inputs (list of Images): a list of PIL Image objects
Returns:
array (float32): num images * height * width * num channels
"""
image_arrays = []
for raw_im in raw_inputs:
im = raw_im.resize(VGG16_DIM[:2], Image.ANTIALIAS)
im = im.convert('RGB')
arr = np.array(im).astype('float32')
image_arrays.append(arr)
all_raw_inputs = np.array(image_arrays)
return imagenet_utils.preprocess_input(all_raw_inputs)
示例7: preprocess_input
# 需要導入模塊: from keras.applications import imagenet_utils [as 別名]
# 或者: from keras.applications.imagenet_utils import preprocess_input [as 別名]
def preprocess_input(x):
"""Preprocesses a numpy array encoding a batch of images.
This function applies the "Inception" preprocessing which converts
the RGB values from [0, 255] to [-1, 1]. Note that this preprocessing
function is different from `imagenet_utils.preprocess_input()`.
# Arguments
x: a 4D numpy array consists of RGB values within [0, 255].
# Returns
Preprocessed array.
"""
x /= 128.
x -= 1.
return x.astype(np.float32)
示例8: preprocess_input
# 需要導入模塊: from keras.applications import imagenet_utils [as 別名]
# 或者: from keras.applications.imagenet_utils import preprocess_input [as 別名]
def preprocess_input(x):
"""Preprocesses a numpy array encoding a batch of images.
# Arguments
x: a 4D numpy array consists of RGB values within [0, 255].
# Returns
Preprocessed array.
"""
return imagenet_utils.preprocess_input(x, mode='tf')
示例9: data_loader
# 需要導入模塊: from keras.applications import imagenet_utils [as 別名]
# 或者: from keras.applications.imagenet_utils import preprocess_input [as 別名]
def data_loader(q, ):
for start in tqdm(range(0, len(filenames), batch_size)):
x_batch = []
end = min(start + batch_size, len(filenames))
filenames_batch = filenames[start:end]
for filename in filenames_batch:
img = load_img(filename)
stacked_channels = []
for i in range(args.stacked_channels):
channel_path = os.path.join(args.stacked_channels_dir,
str(i),
filename.split('/')[-1].replace('.jpg', '.png'))
stacked_channel = load_img(channel_path, grayscale=True)
stacked_channels.append(stacked_channel)
stacked_img = np.dstack((img, *stacked_channels))
x_batch.append(img_to_array(stacked_img))
x_batch = preprocess_input(np.array(x_batch, np.float32), mode=args.preprocessing_function)
if args.pred_tta:
x_batch = do_tta(x_batch, args.pred_tta)
padded_x = np.zeros((batch_size, 1280, 1920, args.stacked_channels + 3))
padded_x[:, :, 1:-1, :] = x_batch
q.put((filenames_batch, padded_x))
for gpu in gpus:
q.put((None, None))
示例10: build_batch_generator
# 需要導入模塊: from keras.applications import imagenet_utils [as 別名]
# 或者: from keras.applications.imagenet_utils import preprocess_input [as 別名]
def build_batch_generator(filenames, img_dir=None, batch_size=None,
shuffle=False, transformations=None,
out_size=None, crop_size=None, mask_dir=None, aug=False):
mask_function = ImageWithMaskFunction(out_size=out_size, crop_size=crop_size, mask_dir=mask_dir)
while True:
# @TODO: Should we fixate the seed here?
if shuffle:
filenames = sklearn.utils.shuffle(filenames)
for start in range(0, len(filenames), batch_size):
batch_x = []
end = min(start + batch_size, len(filenames))
train_batch = filenames[start:end]
for filename in train_batch:
img = imread(os.path.join(img_dir, filename))
stacked_channels = []
for i in range(args.stacked_channels):
channel_path = os.path.join(args.stacked_channels_dir,
str(i),
filename.replace('.jpg', '.png'))
stacked_channel = imread(channel_path, mode='L')
stacked_channels.append(stacked_channel)
stacked_img = np.dstack((img, *stacked_channels))
batch_x.append(stacked_img)
batch_x = np.array(batch_x, np.float32)
batch_x, masks = mask_function.mask_pred(batch_x, train_batch, range(batch_size), aug)
if crop_size is None:
# @TODO: Remove hardcoded padding
batch_x, masks = pad(batch_x, 1, 0), pad(masks, 1, 0)
yield imagenet_utils.preprocess_input(batch_x, mode=args.preprocessing_function), masks
示例11: predict
# 需要導入模塊: from keras.applications import imagenet_utils [as 別名]
# 或者: from keras.applications.imagenet_utils import preprocess_input [as 別名]
def predict():
output_dir = args.pred_mask_dir
model = make_model((None, None, 3))
model.load_weights(args.weights)
batch_size = args.pred_batch_size
nbr_test_samples = 100064
filenames = [os.path.join(args.test_data_dir, f) for f in sorted(os.listdir(args.test_data_dir))]
start_time = clock()
for i in range(int(nbr_test_samples / batch_size) + 1):
x = []
for j in range(batch_size):
if i * batch_size + j < len(filenames):
img = load_img(filenames[i * batch_size + j], target_size=(args.img_height, args.img_width))
x.append(img_to_array(img))
x = np.array(x)
x = preprocess_input(x, args.preprocessing_function)
x = do_tta(x, args.pred_tta)
batch_x = np.zeros((x.shape[0], 1280, 1920, 3))
batch_x[:, :, 1:-1, :] = x
preds = model.predict_on_batch(batch_x)
preds = undo_tta(preds, args.pred_tta)
for j in range(batch_size):
filename = filenames[i * batch_size + j]
prediction = preds[j][:, 1:-1, :]
array_to_img(prediction * 255).save(os.path.join(output_dir, filename.split('/')[-1][:-4] + ".png"))
time_spent = clock() - start_time
print("predicted batch ", str(i))
print("Time spent: {:.2f} seconds".format(time_spent))
print("Speed: {:.2f} ms per image".format(time_spent / (batch_size * (i + 1)) * 1000))
print("Elapsed: {:.2f} hours ".format(time_spent / (batch_size * (i + 1)) / 3600 * (nbr_test_samples - (batch_size * (i + 1)))))
示例12: _load_image_from_uri
# 需要導入模塊: from keras.applications import imagenet_utils [as 別名]
# 或者: from keras.applications.imagenet_utils import preprocess_input [as 別名]
def _load_image_from_uri(local_uri):
img = (PIL.Image
.open(local_uri)
.convert('RGB')
.resize((299, 299), PIL.Image.ANTIALIAS))
img_arr = np.array(img).astype(np.float32)
img_tnsr = preprocess_input(img_arr[np.newaxis, :])
return img_tnsr
示例13: load_image
# 需要導入模塊: from keras.applications import imagenet_utils [as 別名]
# 或者: from keras.applications.imagenet_utils import preprocess_input [as 別名]
def load_image(path):
img = image.load_img(path, target_size=(224,224))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
return np.asarray(x)
示例14: preprocess_input
# 需要導入模塊: from keras.applications import imagenet_utils [as 別名]
# 或者: from keras.applications.imagenet_utils import preprocess_input [as 別名]
def preprocess_input(x):
"""Preprocesses a numpy array encoding a batch of images.
# Arguments
x: a 4D numpy array consists of RGB values within [0, 255].
# Returns
Preprocessed array.
"""
return imagenet_utils.preprocess_input(x, mode='tf')
示例15: preprocess_input
# 需要導入模塊: from keras.applications import imagenet_utils [as 別名]
# 或者: from keras.applications.imagenet_utils import preprocess_input [as 別名]
def preprocess_input(x):
"""Preprocesses a numpy array encoding a batch of images.
# Arguments
x: a 4D numpy array consists of RGB values within [0, 255].
# Returns
Input array scaled to [-1.,1.]
"""
return imagenet_utils.preprocess_input(x, mode='tf')