def load_image(path, height=None, width=None):
img = skimage.io.imread(path)
if len(img.shape) == 2:
img = skimage.color.gray2rgb(img)
img = img / 255.0
if height is not None and width is not None:
ny = height
nx = width
elif height is not None:
ny = height
nx = img.shape[1] * ny / img.shape[0]
elif width is not None:
nx = width
ny = img.shape[0] * nx / img.shape[1]
else:
ny = img.shape[0]
nx = img.shape[1]
return skimage.transform.resize(img, (ny, nx))
python类transform()的实例源码
def rescale(input_image, scale_factor):
sz = [s*scale_factor for s in input_image.shape[:2]]
rescaled = skimage.transform.resize(input_image, sz, mode='reflect')
return rescaled
def resize(input_image, size):
dtype = input_image.dtype
ret = skimage.transform.resize(input_image, size)
if dtype == np.uint8:
ret = (255*ret).astype(dtype)
elif dtype == np.uint16:
ret = (65535*ret).astype(dtype)
elif dtype == np.float32 or dtype == np.float64:
ret = ret.astype(dtype)
else:
raise ValueError('resize not implemented for type {}'.format(dtype))
return ret
# ----- I/O -------------------------------------------------------------------
def load_image_array(image_file, image_size,
image_id, data_dir='Data/datasets/mscoco/train2014',
mode='train'):
img = None
if os.path.exists(image_file):
#print('found' + image_file)
img = skimage.io.imread(image_file)
else:
print('notfound' + image_file)
img = skimage.io.imread('http://mscoco.org/images/%d' % (image_id))
img_path = os.path.join(data_dir, 'COCO_%s2014_%.12d.jpg' % ( mode,
image_id))
skimage.io.imsave(img_path, img)
# GRAYSCALE
if len(img.shape) == 2:
img_new = np.ndarray( (img.shape[0], img.shape[1], 3), dtype = 'uint8')
img_new[:,:,0] = img
img_new[:,:,1] = img
img_new[:,:,2] = img
img = img_new
img_resized = skimage.transform.resize(img, (image_size, image_size))
# FLIP HORIZONTAL WIRH A PROBABILITY 0.5
if random.random() > 0.5:
img_resized = np.fliplr(img_resized)
return img_resized.astype('float32')
def load_image_inception(image_file, image_size=128):
img = skimage.io.imread(image_file)
# GRAYSCALE
if len(img.shape) == 2:
img_new = np.ndarray((img.shape[0], img.shape[1], 3), dtype='uint8')
img_new[:, :, 0] = img
img_new[:, :, 1] = img
img_new[:, :, 2] = img
img = img_new
if image_size != 0:
img = skimage.transform.resize(img, (image_size, image_size), mode='reflect')
return img.astype('int32')
def test():
img = skimage.io.imread("./test_data/starry_night.jpg")
ny = 300
nx = img.shape[1] * ny / img.shape[0]
img = skimage.transform.resize(img, (ny, nx))
skimage.io.imsave("./test_data/test/output.jpg", img)
def fast_warp(img, tf, output_shape, mode='constant', order=0):
"""
This wrapper function is faster than skimage.transform.warp
"""
m = tf.params
t_img = np.zeros((img.shape[0],) + output_shape, img.dtype)
for i in range(t_img.shape[0]):
t_img[i] = _warp_fast(img[i], m, output_shape=output_shape,
mode=mode, order=order)
return t_img
def build_centering_transform(image_shape, target_shape):
rows, cols = image_shape
trows, tcols = target_shape
shift_x = (cols - tcols) / 2.0
shift_y = (rows - trows) / 2.0
return skimage.transform.SimilarityTransform(translation=(shift_x, shift_y))
def build_center_uncenter_transforms(image_shape):
"""
These are used to ensure that zooming and rotation happens around the center of the image.
Use these transforms to center and uncenter the image around such a transform.
"""
center_shift = np.array([image_shape[1], image_shape[0]]) / 2.0 - 0.5 # need to swap rows and cols here apparently! confusing!
tform_uncenter = skimage.transform.SimilarityTransform(translation=-center_shift)
tform_center = skimage.transform.SimilarityTransform(translation=center_shift)
return tform_center, tform_uncenter
def build_augmentation_transform(zoom=(1.0, 1.0), rotation=0, shear=0, translation=(0, 0), flip=False):
if flip:
shear += 180
rotation += 180
# shear by 180 degrees is equivalent to rotation by 180 degrees + flip.
# So after that we rotate it another 180 degrees to get just the flip.
tform_augment = skimage.transform.AffineTransform(scale=(1/zoom[0], 1/zoom[1]), rotation=np.deg2rad(rotation), shear=np.deg2rad(shear), translation=translation)
return tform_augment
def transform(self, x):
return prj(self.H.dot(np.append(x, 1)))
def load_augmented_images(fnames, preprocessor, w, h, is_training, aug_params=no_augmentation_params, transform=None,
bbox=None, fill_mode='constant', fill_mode_cval=0, standardizer=None, save_to_dir=None):
return np.array(
[load_augment(f, preprocessor, w, h, is_training, aug_params, transform, bbox, fill_mode, fill_mode_cval,
standardizer, save_to_dir) for f in fnames])
def load_augment(fname, preprocessor, w, h, is_training, aug_params=no_augmentation_params, transform=None, bbox=None,
fill_mode='constant', fill_mode_cval=0, standardizer=None, save_to_dir=None):
"""Load augmented image with output shape (h, w, c)
Default arguments return non augmented image of shape (h, w, c).
To apply a fixed transform (and color augmentation) specify transform (and color_vec in standardizer).
To generate a random augmentation specify aug_params (and sigma in standardizer).
"""
img = _load_image_th(fname, preprocessor)
# img shape - (c, h, w)
if bbox is not None:
img = _definite_crop(img, bbox)
# print(img.shape)
# import cv2
# cv2.imshow("test", np.asarray(img[1,:,:], dtype=np.uint8))
# cv2.waitKey(0)
if bbox[4] == 1:
img = img[:, :, ::-1]
elif transform is not None:
img = _perturb_fixed(img, tform_augment=transform, target_shape=(w, h), mode=fill_mode,
mode_cval=fill_mode_cval)
else:
img = _perturb(img, augmentation_params=aug_params, target_shape=(w, h), mode=fill_mode,
mode_cval=fill_mode_cval)
if save_to_dir is not None:
file_full_name = os.path.basename(fname)
file_name, file_ext = os.path.splitext(file_full_name)
fname2 = "%s/%s_DA_%d%s" % (save_to_dir, file_name, np.random.randint(1e4), file_ext)
_save_image_th(img, fname2)
if standardizer is not None:
img = standardizer(img, is_training)
# convert to shape (h, w, c)
return img.transpose(1, 2, 0)
def build_augmentation_transform(zoom=(1.0, 1.0), rotation=0, shear=0, translation=(0, 0), flip=False):
if flip:
shear += 180
rotation += 180
# shear by 180 degrees is equivalent to rotation by 180 degrees + flip.
# So after that we rotate it another 180 degrees to get just the flip.
tform_augment = skimage.transform.AffineTransform(scale=(1 / zoom[0], 1 / zoom[1]), rotation=np.deg2rad(rotation),
shear=np.deg2rad(shear), translation=translation)
return tform_augment
# internal stuff below
def _fast_warp(img, tf, output_shape, mode='constant', mode_cval=0, order=0):
"""This wrapper function is faster than skimage.transform.warp """
m = tf.params
t_img = np.zeros((img.shape[0],) + output_shape, img.dtype)
for i in range(t_img.shape[0]):
t_img[i] = _warp_fast(img[i], m, output_shape=output_shape,
mode=mode, cval=mode_cval, order=order)
return t_img
def _build_centering_transform(image_shape, target_shape):
cols, rows = image_shape
tcols, trows = target_shape
shift_x = (cols - tcols) / 2.0
shift_y = (rows - trows) / 2.0
return skimage.transform.SimilarityTransform(translation=(shift_x, shift_y))
def fast_warp(img, tf, output_shape=None, mode='constant', order=0):
"""
This wrapper function is faster than skimage.transform.warp
"""
m = tf.params
if output_shape is None:
t_img = np.zeros_like(img);
else:
t_img = np.zeros((img.shape[0],) + output_shape, img.dtype)
for i in range(t_img.shape[0]):
t_img[i] = _warp_fast(img[i], m, output_shape=output_shape,
mode=mode, order=order)
return t_img
def build_centering_transform(image_shape, target_shape):
rows, cols = image_shape
if target_shape is None:
trows,tcols = image_shape
else:
trows, tcols = target_shape
shift_x = (cols - tcols) / 2.0
shift_y = (rows - trows) / 2.0
return skimage.transform.SimilarityTransform(translation=(shift_x, shift_y))
def build_center_uncenter_transforms(image_shape):
"""
These are used to ensure that zooming and rotation happens around the center of the image.
Use these transforms to center and uncenter the image around such a transform.
"""
center_shift = np.array([image_shape[1], image_shape[0]]) / 2.0 - 0.5 # need to swap rows and cols here apparently! confusing!
tform_uncenter = skimage.transform.SimilarityTransform(translation=-center_shift)
tform_center = skimage.transform.SimilarityTransform(translation=center_shift)
return tform_center, tform_uncenter
def build_augmentation_transform(zoom=(1.0, 1.0), rotation=0, shear=0, translation=(0, 0), flip=False):
if flip:
shear += 180
rotation += 180
# shear by 180 degrees is equivalent to rotation by 180 degrees + flip.
# So after that we rotate it another 180 degrees to get just the flip.
tform_augment = skimage.transform.AffineTransform(scale=(1/zoom[0], 1/zoom[1]), rotation=np.deg2rad(rotation), shear=np.deg2rad(shear), translation=translation)
return tform_augment