我们从Python开源项目中,提取了以下12个代码示例,用于说明如何使用scipy.ndimage.interpolation.affine_transform()。
def extract(image,y0,x0,y1,x1,mode='nearest',cval=0): h,w = image.shape ch,cw = y1-y0,x1-x0 y,x = clip(y0,0,max(h-ch,0)),clip(x0,0,max(w-cw, 0)) sub = image[y:y+ch,x:x+cw] # print("extract", image.dtype, image.shape) try: r = interpolation.shift(sub,(y-y0,x-x0),mode=mode,cval=cval,order=0) if cw > w or ch > h: pady0, padx0 = max(-y0, 0), max(-x0, 0) r = interpolation.affine_transform(r, eye(2), offset=(pady0, padx0), cval=1, output_shape=(ch, cw)) return r except RuntimeError: # workaround for platform differences between 32bit and 64bit # scipy.ndimage dtype = sub.dtype sub = array(sub,dtype='float64') sub = interpolation.shift(sub,(y-y0,x-x0),mode=mode,cval=cval,order=0) sub = array(sub,dtype=dtype) return sub
def random_rotation(volume, rotation): theta_x = np.pi / 180 * np.random.uniform(-rotation, rotation) theta_y = np.pi / 180 * np.random.uniform(-rotation, rotation) theta_z = np.pi / 180 * np.random.uniform(-rotation, rotation) rotation_matrix_x = np.array([[1, 0, 0], [0, np.cos(theta_x), -np.sin(theta_x)], [0, np.sin(theta_x), np.cos(theta_x)]]) rotation_matrix_y = np.array([[np.cos(theta_y), 0, np.sin(theta_y)], [0, 1, 0], [-np.sin(theta_y), 0, np.cos(theta_y)]]) rotation_matrix_z = np.array([[np.cos(theta_z), -np.sin(theta_z), 0], [np.sin(theta_z), np.cos(theta_z), 0], [0, 0, 1]]) transform_matrix = np.dot(np.dot(rotation_matrix_x, rotation_matrix_y), rotation_matrix_z) volume_rotated = affine_transform(volume, transform_matrix, mode='nearest') return volume_rotated
def scale_to_h(img,target_height,order=1,dtype=dtype('f'),cval=0): h,w = img.shape scale = target_height*1.0/h target_width = int(scale*w) output = interpolation.affine_transform(1.0*img,eye(2)/scale,order=order, output_shape=(target_height,target_width), mode='constant',cval=cval) output = array(output,dtype=dtype) return output
def apply_transform(x, transform_matrix, channel_index=0, fill_mode='nearest', cval=0.): x = np.rollaxis(x, channel_index, 0) final_affine_matrix = transform_matrix[:2, :2] final_offset = transform_matrix[:2, 2] channel_images = [affine_transform(x_channel, final_affine_matrix, final_offset, order=0, mode=fill_mode, cval=cval) for x_channel in x] x = np.stack(channel_images, axis=0) x = np.rollaxis(x, 0, channel_index+1) return x
def transform(self, translation, theta, method='opencv'): """Create a new image by translating and rotating the current image. Parameters ---------- translation : :obj:`numpy.ndarray` of float The XY translation vector. theta : float Rotation angle in radians, with positive meaning counter-clockwise. method : :obj:`str` Method to use for image transformations (opencv or scipy) Returns ------- :obj:`Image` An image of the same type that has been rotated and translated. """ theta = np.rad2deg(theta) trans_map = np.float32( [[1, 0, translation[1]], [0, 1, translation[0]]]) rot_map = cv2.getRotationMatrix2D( (self.center[1], self.center[0]), theta, 1) trans_map_aff = np.r_[trans_map, [[0, 0, 1]]] rot_map_aff = np.r_[rot_map, [[0, 0, 1]]] full_map = rot_map_aff.dot(trans_map_aff) full_map = full_map[:2, :] if method == 'opencv': im_data_tf = cv2.warpAffine( self.data, full_map, (self.width, self.height), flags=cv2.INTER_NEAREST) else: im_data_tf = sni.affine_transform(self.data, matrix=full_map[:, :2], offset=full_map[:, 2], order=0) return type(self)( im_data_tf.astype( self.data.dtype), frame=self._frame)
def applyLinearTransformToImage(self, image, angle, shear_x, shear_y, scale, size_out): '''Apply the image transformation specified by three parameters. Time it takes warping a 256 x 256 RGB image with various affine warping functions: * 0.25ms cv2.warpImage, nearest interpolation * 0.26ms cv2.warpImage, linear interpolation * 5.11ms ndii.affine_transform, order=0 * 5.93ms skimage.transform._warps_cy._warp_fast, linear interpolation Args: x: 2D numpy array, a single image. angle: Angle by which the image is rotated. shear_x: Shearing factor along the x-axis by which the image is sheared. shear_y: Shearing factor along the x-axis by which the image is sheared. scale: Scaling factor by which the image is scaled. channel_axis: Index of axis for channels in the input tensor. Returns: A tuple of transformed version of the input and the correction scale factor. ''' # Positions of the image center before and after the transformation in # pixel coordinates. s_out = (size_out, size_out) c_in = .5 * np.asarray(image.shape[:2], dtype=np.float64).reshape((2, 1)) c_out = .5 * np.asarray(s_out, dtype=np.float64).reshape((2, 1)) angle = -angle M_rot_inv = np.asarray([[math.cos(angle), -math.sin(angle)], \ [math.sin(angle), math.cos(angle)]]) M_shear_inv = (1. / (shear_x * shear_y - 1.)) \ * np.asarray([[-1., shear_x], [shear_y, -1.]]) M_inv = np.dot(M_shear_inv, M_rot_inv) # First undo rotation, then shear. M_inv /= scale offset = c_in - np.dot(M_inv, c_out) # cv2.warpAffine transform according to dst(p) = src(M_inv * p + offset). # No need to reverse the channels because the channels are interpolated # separately. warped = cv2.warpAffine(image, np.concatenate((M_inv, offset), axis=1), s_out, flags=cv2.INTER_LANCZOS4 | cv2.WARP_INVERSE_MAP) # flags=cv2.INTER_CUBIC | cv2.WARP_INVERSE_MAP) return warped
def augment(images): pixels = images[0].shape[1] center = pixels/2.-0.5 random_flip_x = P.AUGMENTATION_PARAMS['flip'] and np.random.randint(2) == 1 random_flip_y = P.AUGMENTATION_PARAMS['flip'] and np.random.randint(2) == 1 # Translation shift shift_x = np.random.uniform(*P.AUGMENTATION_PARAMS['translation_range']) shift_y = np.random.uniform(*P.AUGMENTATION_PARAMS['translation_range']) rotation_degrees = np.random.uniform(*P.AUGMENTATION_PARAMS['rotation_range']) zoom_factor = np.random.uniform(*P.AUGMENTATION_PARAMS['zoom_range']) #zoom_factor = 1 + (zoom_f/2-zoom_f*np.random.random()) if CV2_AVAILABLE: M = cv2.getRotationMatrix2D((center, center), rotation_degrees, zoom_factor) M[0, 2] += shift_x M[1, 2] += shift_y for i in range(len(images)): image = images[i] if CV2_AVAILABLE: #image = image.transpose(1,2,0) image = cv2.warpAffine(image, M, (pixels, pixels)) if random_flip_x: image = cv2.flip(image, 0) if random_flip_y: image = cv2.flip(image, 1) #image = image.transpose(2,0,1) images[i] = image else: if random_flip_x: #image = image.transpose(1,0) image[:,:] = image[::-1,:] #image = image.transpose(1,0) if random_flip_y: image = image.transpose(1,0) image[:,:] = image[::-1,:] image = image.transpose(1,0) rotate(image, rotation_degrees, reshape=False, output=image) #image2 = zoom(image, [zoom_factor,zoom_factor]) image2 = crop_or_pad(image, pixels, -3000) shift(image2, [shift_x,shift_y], output=image) #affine_transform(image, np.array([[zoom_x,0], [0,zoom_x]]), output=image) #z = AffineTransform(scale=(2,2)) #image = warp(image, z.params) images[i] = image return images