def rotate_image(img, angle, pivot):
pivot = pivot.astype(np.int32)
# double size of image while centering object
pads = [[img.shape[0] - pivot[0], pivot[0]], [img.shape[1] - pivot[1], pivot[1]]]
if len(img.shape) > 2:
pads.append([0, 0])
imgP = np.pad(img, pads, 'constant')
# reduce size of matrix to rotate around the object
if len(img.shape) > 2:
total_y = np.sum(imgP.any(axis=(0, 2))) * 2.4
total_x = np.sum(imgP.any(axis=(1, 2))) * 2.4
else:
total_y = np.sum(imgP.any(axis=0)) * 2.4
total_x = np.sum(imgP.any(axis=1)) * 2.4
cropy = int((imgP.shape[0] - total_y)/2)
cropx = int((imgP.shape[1] - total_x)/2)
imgP[cropy:-cropy, cropx:-cropx] = ndimage.rotate(imgP[cropy:-cropy, cropx:-cropx], angle,
reshape=False, prefilter=False)
return imgP[pads[0][0]: -pads[0][1], pads[1][0]: -pads[1][1]]
python类rotate()的实例源码
def imrotate(image, angle, interp_order=1):
"""
Rotate an image from North to East given an angle in degrees
Parameters
----------
image : `numpy.ndarray`
Input data array
angle : float
Angle in degrees
interp_order : int, optional
Spline interpolation order [0, 5] (default 1: linear)
Returns
-------
output : `numpy.ndarray`
Rotated data array
"""
return rotate(image, -1.0 * angle,
order=interp_order, reshape=False, prefilter=False)
def augment(self,im):
"""
augmentation includes: mean subtract, random crop, random mirror, random rotation
"""
#random rotation
if self.rot != 0:
rot_ang = np.random.randint(self.rot[0], high = self.rot[1]+1)
im = ndimage.rotate(im.astype(np.uint8), rot_ang, \
cval=255,reshape = False)
#mean subtract and scaling
im = np.float32(im)
im -= self.mean
im *= self.scale
#random flip
flip = np.random.choice(2)*2-1
im = im[:, ::flip]
#random crop
y_offset = np.random.randint(im.shape[0] - self.outshape[0] - 8)
x_offset = np.random.randint(im.shape[1] - self.outshape[1] - 8)
return im[4+y_offset:4+self.outshape[0]+y_offset,
4+x_offset:4+self.outshape[1]+x_offset]
#return im
def rotate(np_img):
img = ndimage.rotate(np_img, 10, mode='nearest')
return img
def main():
img = imread(args.input_path)
img = ndimage.rotate(img, args.angle, mode=args.mode)
misc.imsave(args.output_path, img)
def load_transform(image_path, angle=0., s=(0,0), size=(20,20)):
#Load the image
original = imread(image_path, flatten=True)
#Rotate the image
rotated = np.maximum(np.minimum(rotate(original, angle=angle, cval=1.), 1.), 0.)
#Shift the image
shifted = shift(rotated, shift=s)
#Resize the image
resized = np.asarray(imresize(rotated, size=size), dtype=np.float32) / 255 #Note here we coded manually as np.float32, it should be tf.float32
#Invert the image
inverted = 1. - resized
max_value = np.max(inverted)
if max_value > 0:
inverted /= max_value
return inverted
def load_transform(image_path, angle=0., s=(0,0), size=(20,20)):
#Load the image
original = imread(image_path, flatten=True)
#Rotate the image
rotated = np.maximum(np.minimum(rotate(original, angle=angle, cval=1.), 1.), 0.)
#Shift the image
shifted = shift(rotated, shift=s)
#Resize the image
resized = np.asarray(imresize(rotated, size=size), dtype=np.float32) / 255 #Note here we coded manually as np.float32, it should be tf.float32
#Invert the image
inverted = 1. - resized
max_value = np.max(inverted)
if max_value > 0:
inverted /= max_value
return inverted
def rotate(a, args):
"""
Rotate panel layout by an arbitrary degree around the origin.
"""
# Create a matrix that fits all panels and puts the origin at the center.
# Downscale the matrix by 10x to reduce computation. Also scipy.ndimage.rotate
# seems to have issues with large matrices where some elements get duplicated
panels = {p['panelId']: p for p in a.panel_positions}
for pid in panels:
panels[pid]['x'] //= 10
panels[pid]['y'] //= 10
# calculate the max dimension of our bounding box, and make sure that our
# resulting image can handle 2x the image size, in case we rotate 45 degrees
dim = 2 * max([max(abs(p['x']), abs(p['y'])) for p in panels.values()])
image = numpy.zeros(shape=(2 * dim, 2 * dim))
# Put all panels in the matrix and rotate
for (k, v) in panels.items():
image[v['y'] + dim][v['x'] + dim] = k
# Rotate
r = args.rotate % 360
rotated = ndimage.rotate(image, r, order=0, reshape=False)
for (y, x) in numpy.transpose(numpy.nonzero(rotated)):
p = panels[rotated[y][x]]
p['x'] = (int(x) - dim) * 10
p['y'] = (int(y) - dim) * 10
p['o'] = (p['o'] + r) % 360
# Cache the result for the future, along with the rotation we used
config = configparser.ConfigParser()
config.read('aurora.ini')
config['device']['rotation'] = str(args.rotate % 360)
config['device']['panel_positions'] = json.dumps(list(panels.values()))
config.write(open('aurora.ini', 'w'))
def main(argv):
parser = argparse.ArgumentParser()
parser.add_argument('--plot', dest='plot', action='store_true')
parser.add_argument('--on', dest='on_off', action='store_true')
parser.add_argument('--off', dest='on_off', action='store_false')
parser.add_argument('--brightness', dest='brightness', type=int, choices=range(0,100))
parser.add_argument('--rotate', dest='rotate', type=int, choices=range(-360,360))
args = parser.parse_args()
a = aurora()
if args.on_off != a.on:
a.on = args.on_off
if args.brightness is not None:
a.brightness = args.brightness
if args.rotate is not None:
rotate(a, args)
if args.plot:
plot(a)
def canny_demo():
# Generate noisy image of a square
im = np.zeros((128, 128))
im[32:-32, 32:-32] = 1
im = ndi.rotate(im, 15, mode='constant')
im = ndi.gaussian_filter(im, 4)
im += 0.2 * np.random.random(im.shape)
# Compute the Canny filter for two values of sigma
edges1 = feature.canny(im)
edges2 = feature.canny(im, sigma=3)
# display results
fig, (ax1, ax2, ax3) = plt.subplots(nrows=1, ncols=3, figsize=(8, 3),
sharex=True, sharey=True)
ax1.imshow(im, cmap=plt.cm.gray)
ax1.axis('off')
ax1.set_title('noisy image', fontsize=20)
ax2.imshow(edges1, cmap=plt.cm.gray)
ax2.axis('off')
ax2.set_title('Canny filter, $\sigma=1$', fontsize=20)
ax3.imshow(edges2, cmap=plt.cm.gray)
ax3.axis('off')
ax3.set_title('Canny filter, $\sigma=3$', fontsize=20)
fig.tight_layout()
plt.show()
def circle2ellipse(imgcirc, bfraction, rotation=None):
"""
Shrink the input circle image with respect to the center along the
column (axis) to transform the circle to an ellipse, and then rotate
around the image center.
Parameters
----------
imgcirc : 2D `~numpy.ndarray`
Input image grid containing a circle at the center
bfraction : float
The fraction of the semi-minor axis w.r.t. the semi-major axis
(i.e., the half width of the input image), to determine the
shrunk size (height) of the output image.
Should be a fraction within [0, 1]
rotation : float, optional
Rotation angle (unit: [deg])
Default: ``None`` (i.e., no rotation)
Returns
-------
imgout : 2D `~numpy.ndarray`
Image of the same size as the input circle image.
"""
nrow, ncol = imgcirc.shape
# Shrink the circle to be elliptical
nrow2 = nrow * bfraction
nrow2 = int(nrow2 / 2) * 2 + 1 # be odd
# NOTE: zoom() calculate the output shape with round() instead of int();
# fix the warning about they may be different.
zoom = ((nrow2+0.1)/nrow, 1)
img2 = ndimage.zoom(imgcirc, zoom=zoom, order=1)
# Pad the shrunk image to have the same size as input
imgout = np.zeros(shape=(nrow, ncol))
r1 = int((nrow - nrow2) / 2)
imgout[r1:(r1+nrow2), :] = img2
if rotation:
imgout = ndimage.rotate(imgout, angle=rotation, reshape=False, order=1)
return imgout
def rotate(image):
randnum = np.random.randint(1,360)
new_image = np.copy(image)
return ndimage.rotate(new_image, angle=randnum, reshape=False)
#randomly manipulates image
#rotate, flip along axis, add blotch, shift
def augment(images, labels=None, amplify=2):
# INPUT:
#images shape: (batch_size, height, width, channels=3)
#labels shape: (batch_size, 3)
ops = {
0: addBlotch,
1: shift,
2: addNoise,
3: rotate
}
shape = images.shape
new_images = np.zeros(((amplify*shape[0]), shape[1], shape[2], shape[3]))
if labels is not None:
new_labels = np.zeros(((amplify*shape[0]), 3))
for i in range(images.shape[0]):
cur_img = np.copy(images[i])
new_images[i] = cur_img
if labels is not None:
new_labels[i] = np.copy(labels[i])
for j in range(1, amplify):
add_r = ( j * shape[0] )
which_op = np.random.randint(low=0, high=4)
dup_img = np.zeros((1,shape[1], shape[2], shape[3]))
new_images[i+add_r] = ops[which_op](cur_img)
if labels is not None:
new_labels[i+add_r] = np.copy(labels[i])
if labels is not None:
return new_images.astype(np.uint8), new_labels.astype(np.uint8)
else:
return new_images.astype(np.uint8)
def rotate_batch(self, x_batch, axis, k):
x_batch = rotate(x_batch, k*90, reshape=False, axes=axis, mode="nearest")
return x_batch
def augment_data(images, labels):
more_images = np.zeros((4*images.shape[0], images.shape[1], images.shape[2],))
more_labels = np.zeros((4*labels.shape[0]))
for i in range(labels.shape[0]):
for j in range(4):
rotation = j*90
more_images[4*i+j] = ndimage.rotate(images[i], rotation)
more_labels[4*i+j] = labels[i]
return shuffle(more_images, more_labels)
def augment_data(images, labels):
more_images = np.zeros((8*images.shape[0], images.shape[1], images.shape[2],))
more_labels = np.zeros((8*labels.shape[0]))
for i in range(labels.shape[0]):
for j in range(8):
rotation = j*90
more_images[8*i+j] = ndimage.rotate(images[i], rotation)
more_labels[8*i+j] = labels[i]
return shuffle(more_images, more_labels)
def augment_test_data(images):
more_images = np.zeros((4*images.shape[0], images.shape[1], images.shape[2],))
for i in range(images.shape[0]):
for j in range(4):
rotation = j*90
more_images[4*i+j] = ndimage.rotate(images[i], rotation)
return more_images
def augment_data(images, labels):
more_images = np.zeros((8*images.shape[0], images.shape[1], images.shape[2],))
more_labels = np.zeros((8*labels.shape[0]))
for i in range(labels.shape[0]):
for j in range(8):
rotation = j*90
more_images[8*i+j] = ndimage.rotate(images[i], rotation)
more_labels[8*i+j] = labels[i]
return shuffle(more_images, more_labels)
def augment_test_data(images):
more_images = np.zeros((4*images.shape[0], images.shape[1], images.shape[2],))
for i in range(images.shape[0]):
for j in range(4):
rotation = j*90
more_images[4*i+j] = ndimage.rotate(images[i], rotation)
return more_images
def expend_training_data(images, labels):
expanded_images = []
expanded_labels = []
j = 0 # counter
for x, y in zip(images, labels):
j = j+1
if j%100==0:
print ('expanding data : %03d / %03d' % (j,numpy.size(images,0)))
# register original data
expanded_images.append(x)
expanded_labels.append(y)
# get a value for the background
# zero is the expected value, but median() is used to estimate background's value
bg_value = numpy.median(x) # this is regarded as background's value
image = numpy.reshape(x, (-1, 28))
for i in range(4):
# rotate the image with random degree
angle = numpy.random.randint(-15,15,1)
new_img = ndimage.rotate(image,angle,reshape=False, cval=bg_value)
# shift the image with random distance
shift = numpy.random.randint(-2, 2, 2)
new_img_ = ndimage.shift(new_img,shift, cval=bg_value)
# register new training data
expanded_images.append(numpy.reshape(new_img_, 784))
expanded_labels.append(y)
# images and labels are concatenated for random-shuffle at each epoch
# notice that pair of image and label should not be broken
expanded_train_total_data = numpy.concatenate((expanded_images, expanded_labels), axis=1)
numpy.random.shuffle(expanded_train_total_data)
return expanded_train_total_data
# Prepare MNISt data
def edge_rotate(im,ang):
"""
rotate edge map using nearest neighbour preserving edge and dimension
Assumption: background 255, foreground 0
currently does not work as good as ndimage.rotate
"""
ang_rad = np.pi / 180.0 * ang
H,W = np.float32(im.shape)
R = mat([[np.cos(ang_rad),-np.sin(ang_rad) ,0],
[np.sin(ang_rad), np.cos(ang_rad),0],
[0 ,0 ,1.0]])
T0 = mat([[1.0,0,-W/2],[0,1.0,-H/2],[0,0,1.0]])
M0 = T0.I * R * T0
tl_x,tl_y = np.floor(warping([0,0],M0))
tr_x,tr_y = np.floor(warping([W-1,0],M0))
bl_x,bl_y = np.floor(warping([0,H-1],M0))
br_x,br_y = np.floor(warping([W-1,H-1],M0))
minx = np.min([tl_x,tr_x,bl_x,br_x])
maxx = np.max([tl_x,tr_x,bl_x,br_x])
miny = np.min([tl_y,tr_y,bl_y,br_y])
maxy = np.max([tl_y,tr_y,bl_y,br_y])
T1 = mat([[1.0,0.0,minx],
[0.0,1.0,miny],
[0.0,0.0,1.0]])
M1 = M0.I * T1
nW = int(maxx - minx+1)
nH = int(maxy - miny+1)
out = np.ones((nH,nW),dtype=np.float32)*255
for y in xrange(nH):
for x in xrange(nW):
u,v = np.int64(warping([x,y],M1))
if u>=0 and u<W and v>=0 and v<H and im[v,u]!=255:
out[y,x]=0
return out
def rotation_augmentation(X, angle_range):
progbar = Progbar(X.shape[0]) # progress bar for augmentation status tracking
X_rot = np.copy(X)
for i in range(len(X)):
angle = np.random.randint(-angle_range, angle_range)
for j in range(X.shape[1]):
X_rot[i, j] = ndimage.rotate(X[i, j], angle, reshape=False, order=1)
progbar.add(1)
return X_rot
def sub_load_data(data, img_size, aug):
img_name, dataset = data
img = misc.imread(dataset+'images/'+img_name+'.bmp', mode='L')
seg = misc.imread(dataset+'seg_labels/'+img_name+'.png', mode='L')
try:
ali = misc.imread(dataset+'ori_labels/'+img_name+'.bmp', mode='L')
except:
ali = np.zeros_like(img)
mnt = np.array(mnt_reader(dataset+'mnt_labels/'+img_name+'.mnt'), dtype=float)
if any(img.shape != img_size):
# random pad mean values to reach required shape
if np.random.rand()<aug:
tra = np.int32(np.random.rand(2)*(np.array(img_size)-np.array(img.shape)))
else:
tra = np.int32(0.5*(np.array(img_size)-np.array(img.shape)))
img_t = np.ones(img_size)*np.mean(img)
seg_t = np.zeros(img_size)
ali_t = np.ones(img_size)*np.mean(ali)
img_t[tra[0]:tra[0]+img.shape[0],tra[1]:tra[1]+img.shape[1]] = img
seg_t[tra[0]:tra[0]+img.shape[0],tra[1]:tra[1]+img.shape[1]] = seg
ali_t[tra[0]:tra[0]+img.shape[0],tra[1]:tra[1]+img.shape[1]] = ali
img = img_t
seg = seg_t
ali = ali_t
mnt = mnt+np.array([tra[1],tra[0],0])
if np.random.rand()<aug:
# random rotation [0 - 360] & translation img_size / 4
rot = np.random.rand() * 360
tra = (np.random.rand(2)-0.5) / 2 * img_size
img = ndimage.rotate(img, rot, reshape=False, mode='reflect')
img = ndimage.shift(img, tra, mode='reflect')
seg = ndimage.rotate(seg, rot, reshape=False, mode='constant')
seg = ndimage.shift(seg, tra, mode='constant')
ali = ndimage.rotate(ali, rot, reshape=False, mode='reflect')
ali = ndimage.shift(ali, tra, mode='reflect')
mnt_r = point_rot(mnt[:, :2], rot/180*np.pi, img.shape, img.shape)
mnt = np.column_stack((mnt_r+tra[[1, 0]], mnt[:, 2]-rot/180*np.pi))
# only keep mnt that stay in pic & not on border
mnt = mnt[(8<=mnt[:,0])*(mnt[:,0]<img_size[1]-8)*(8<=mnt[:, 1])*(mnt[:,1]<img_size[0]-8), :]
return img, seg, ali, mnt
def sub_load_data(data, img_size, aug):
img_name, dataset = data
img = misc.imread(dataset+'images/'+img_name+'.bmp', mode='L')
seg = misc.imread(dataset+'seg_labels/'+img_name+'.png', mode='L')
try:
ali = misc.imread(dataset+'ori_labels/'+img_name+'.bmp', mode='L')
except:
ali = np.zeros_like(img)
mnt = np.array(mnt_reader(dataset+'mnt_labels/'+img_name+'.mnt'), dtype=float)
if any(img.shape != img_size):
# random pad mean values to reach required shape
if np.random.rand()<aug:
tra = np.int32(np.random.rand(2)*(np.array(img_size)-np.array(img.shape)))
else:
tra = np.int32(0.5*(np.array(img_size)-np.array(img.shape)))
img_t = np.ones(img_size)*np.mean(img)
seg_t = np.zeros(img_size)
ali_t = np.ones(img_size)*np.mean(ali)
img_t[tra[0]:tra[0]+img.shape[0],tra[1]:tra[1]+img.shape[1]] = img
seg_t[tra[0]:tra[0]+img.shape[0],tra[1]:tra[1]+img.shape[1]] = seg
ali_t[tra[0]:tra[0]+img.shape[0],tra[1]:tra[1]+img.shape[1]] = ali
img = img_t
seg = seg_t
ali = ali_t
mnt = mnt+np.array([tra[1],tra[0],0])
if np.random.rand()<aug:
# random rotation [0 - 360] & translation img_size / 4
rot = np.random.rand() * 360
tra = (np.random.rand(2)-0.5) / 2 * img_size
img = ndimage.rotate(img, rot, reshape=False, mode='reflect')
img = ndimage.shift(img, tra, mode='reflect')
seg = ndimage.rotate(seg, rot, reshape=False, mode='constant')
seg = ndimage.shift(seg, tra, mode='constant')
ali = ndimage.rotate(ali, rot, reshape=False, mode='reflect')
ali = ndimage.shift(ali, tra, mode='reflect')
mnt_r = point_rot(mnt[:, :2], rot/180*np.pi, img.shape, img.shape)
mnt = np.column_stack((mnt_r+tra[[1, 0]], mnt[:, 2]-rot/180*np.pi))
# only keep mnt that stay in pic & not on border
mnt = mnt[(8<=mnt[:,0])*(mnt[:,0]<img_size[1]-8)*(8<=mnt[:, 1])*(mnt[:,1]<img_size[0]-8), :]
return img, seg, ali, mnt
def load_transform(image_path, angle=0., s=(0, 0), size=(20, 20)):
# Load the image
original = imread(image_path, flatten=True)
# Rotate the image
rotated = np.maximum(np.minimum(rotate(original, angle=angle, cval=1.), 1.), 0.)
# Shift the image
shifted = shift(rotated, shift=s)
# Resize the image
resized = np.asarray(scipy.misc.imresize(rotated, size=size), dtype=theano.config.floatX) / 255.
# Invert the image
inverted = 1. - resized
max_value = np.max(inverted)
if max_value > 0.:
inverted /= max_value
return inverted
def compare(test_id, angles, models):
img = X_test[test_id]
imgs = np.array([ndimage.rotate(img, rot, reshape=False) for rot in angles])
all_probs = []
all_matched = []
for model in models:
probs, matched = get_probs_matched(imgs, model, test_id)
all_probs.append(probs)
all_matched.append(matched)
return all_probs, all_matched
def transform(self, Xb, yb):
Xb, yb = super(RotateBatchIterator, self).transform(Xb, yb)
angle = np.random.randint(-10,11)
Xb_rotated = rotate(Xb, angle, axes=(2, 3), reshape=False)
return Xb_rotated, yb
def transform_image(image_path, angle=0., s=(0,0), size=(20,20)):
original = imread(image_path, flatten=True)
rotated = np.maximum(np.minimum(rotate(original, angle=angle, cval=1.), 1.), 0.)
shifted = shift(rotated, shift=s)
resized = np.asarray(imresize(rotated, size=size), dtype=np.float32)/255
inverted = 1. - resized
max_value = np.max(inverted)
if max_value > 0:
inverted /= max_value
return inverted
def rotate_image(image, angle):
rotated_image = ndimage.rotate(image, angle, mode='reflect', order=0, reshape=False)
return rotated_image
def rotate(self, angle=0, deg=True, save_totalflux=False):
'''
Rotate the input image
Arguments:
self: input imagefite.imagefits object
angle (float): Rotational Angle. Anti-clockwise direction will be positive (same to the Position Angle).
deg (boolean): It true, then the unit of angle will be degree. Otherwise, it will be radian.
save_totalflux (boolean): If true, the total flux of the image will be conserved.
'''
# create output fits
outfits = copy.deepcopy(self)
if deg:
degangle = -angle
radangle = -np.deg2rad(angle)
else:
degangle = -np.rad2deg(angle)
radangle = -angle
#cosa = np.cos(radangle)
#sina = np.sin(radangle)
Nx = outfits.header["nx"]
Ny = outfits.header["ny"]
for istokes in np.arange(self.header["ns"]):
for ifreq in np.arange(self.header["nf"]):
image = outfits.data[istokes, ifreq]
# rotate data
newimage = sn.rotate(image, degangle)
# get the size of new data
My = newimage.shape[0]
Mx = newimage.shape[1]
# take the center of the rotated image
outfits.data[istokes, ifreq] = newimage[np.around(My / 2 - Ny / 2):np.around(My / 2 - Ny / 2) + Ny,
np.around(Mx / 2 - Nx / 2):np.around(Mx / 2 - Nx / 2) + Nx]
# Flux Scaling
if save_totalflux:
totalflux = self.totalflux(istokes=istokes, ifreq=ifreq)
outfits.data[istokes, ifreq] *= totalflux / \
outfits.totalflux(istokes=istokes, ifreq=ifreq)
outfits.update_fits()
return outfits