Python skimage.transform.SimilarityTransform() Examples
The following are 30
code examples of skimage.transform.SimilarityTransform().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
skimage.transform
, or try the search function
.
Example #1
Source File: scalable_reference_pattern.py From pyxem with GNU General Public License v3.0 | 8 votes |
def function(self, x, y): signal2D = self.signal.data order = self.order d11 = self.d11.value d12 = self.d12.value d21 = self.d21.value d22 = self.d22.value t1 = self.t1.value t2 = self.t2.value D = np.array([[d11, d12, t1], [d21, d22, t2], [0.0, 0.0, 1.0]]) shifty, shiftx = np.array(signal2D.shape[:2]) / 2 shift = tf.SimilarityTransform(translation=[-shiftx, -shifty]) tform = tf.AffineTransform(matrix=D) shift_inv = tf.SimilarityTransform(translation=[shiftx, shifty]) transformed = tf.warp( signal2D, (shift + (tform + shift_inv)).inverse, order=order ) return transformed
Example #2
Source File: image_processing_common.py From tensorflow-litterbox with Apache License 2.0 | 7 votes |
def distort_affine_skimage(image, rotation=10.0, shear=5.0, random_state=None): if random_state is None: random_state = np.random.RandomState(None) rot = np.deg2rad(np.random.uniform(-rotation, rotation)) sheer = np.deg2rad(np.random.uniform(-shear, shear)) shape = image.shape shape_size = shape[:2] center = np.float32(shape_size) / 2. - 0.5 pre = transform.SimilarityTransform(translation=-center) affine = transform.AffineTransform(rotation=rot, shear=sheer, translation=center) tform = pre + affine distorted_image = transform.warp(image, tform.params, mode='reflect') return distorted_image.astype(np.float32)
Example #3
Source File: face_align.py From insightface with MIT License | 6 votes |
def estimate_norm(lmk, image_size = 112, mode='arcface'): assert lmk.shape==(5,2) tform = trans.SimilarityTransform() lmk_tran = np.insert(lmk, 2, values=np.ones(5), axis=1) min_M = [] min_index = [] min_error = float('inf') if mode=='arcface': assert image_size==112 src = arcface_src else: src = src_map[image_size] for i in np.arange(src.shape[0]): tform.estimate(lmk, src[i]) M = tform.params[0:2,:] results = np.dot(M, lmk_tran.T) results = results.T error = np.sum(np.sqrt(np.sum((results - src[i]) ** 2,axis=1))) # print(error) if error< min_error: min_error = error min_M = M min_index = i return min_M, min_index
Example #4
Source File: face_align.py From 1.FaceRecognition with MIT License | 6 votes |
def estimate_norm(lmk, image_size = 112, mode='arcface'): assert lmk.shape==(5,2) tform = trans.SimilarityTransform() lmk_tran = np.insert(lmk, 2, values=np.ones(5), axis=1) min_M = [] min_index = [] min_error = float('inf') if mode=='arcface': assert image_size==112 src = arcface_src else: src = src_map[image_size] for i in np.arange(src.shape[0]): tform.estimate(lmk, src[i]) M = tform.params[0:2,:] results = np.dot(M, lmk_tran.T) results = results.T error = np.sum(np.sqrt(np.sum((results - src[i]) ** 2,axis=1))) # print(error) if error< min_error: min_error = error min_M = M min_index = i return min_M, min_index
Example #5
Source File: MaskDamager.py From PReMVOS with MIT License | 6 votes |
def scale_mask(mask, factor=1.05): nzy, nzx, _ = mask.nonzero() if nzy.size == 0: return mask #center_y, center_x = nzy.mean(), nzx.mean() #print center_y, center_x center_y, center_x = (nzy.max() + nzy.min()) / 2, (nzx.max() + nzx.min()) / 2 #print center_y, center_x shift_ = SimilarityTransform(translation=[-center_x, -center_y]) shift_inv = SimilarityTransform(translation=[center_x, center_y]) A = SimilarityTransform(scale=(factor, factor)) mask_out = warp(mask, (shift_ + (A + shift_inv)).inverse) mask_out = (mask_out > 0.5).astype("float32") #import matplotlib.pyplot as plt #im = numpy.concatenate([mask, mask, mask_out],axis=2) #plt.imshow(im) #plt.show() return mask_out
Example #6
Source File: face_align_util.py From MaskInsightface with Apache License 2.0 | 6 votes |
def estimate_norm(self, lmk): assert lmk.shape == (5, 2) tform = trans.SimilarityTransform() lmk_tran = np.insert(lmk, 2, values=np.ones(5), axis=1) min_M = [] min_index = [] min_error = float('inf') src = self.arcface_src for i in np.arange(src.shape[0]): tform.estimate(lmk, src[i]) M = tform.params[0:2, :] results = np.dot(M, lmk_tran.T) results = results.T error = np.sum(np.sqrt(np.sum((results - src[i]) ** 2, axis=1))) # print(error) if error < min_error: min_error = error min_M = M min_index = i return min_M, min_index
Example #7
Source File: mask_damaging.py From models with Apache License 2.0 | 6 votes |
def _scale_mask(mask, scale_amount=0.025): """Damages a mask for a single object by randomly scaling it in numpy. Args: mask: Boolean numpy array of shape(height, width, 1). scale_amount: Float scalar, the maximum factor for random scaling. Returns: The scaled version of mask. """ nzy, nzx, _ = mask.nonzero() cy = 0.5 * (nzy.max() - nzy.min()) cx = 0.5 * (nzx.max() - nzx.min()) scale_factor = np.random.uniform(1.0 - scale_amount, 1.0 + scale_amount) shift = transform.SimilarityTransform(translation=[-cx, -cy]) inv_shift = transform.SimilarityTransform(translation=[cx, cy]) s = transform.SimilarityTransform(scale=[scale_factor, scale_factor]) m = (shift + (s + inv_shift)).inverse scaled_mask = transform.warp(mask, m) > 0.5 return scaled_mask
Example #8
Source File: mask_damaging.py From models with Apache License 2.0 | 6 votes |
def _rotate_mask(mask, max_rot_degrees=3.0): """Damages a mask for a single object by randomly rotating it in numpy. Args: mask: Boolean numpy array of shape(height, width, 1). max_rot_degrees: Float scalar, the maximum number of degrees to rotate. Returns: The scaled version of mask. """ cy = 0.5 * mask.shape[0] cx = 0.5 * mask.shape[1] rot_degrees = np.random.uniform(-max_rot_degrees, max_rot_degrees) shift = transform.SimilarityTransform(translation=[-cx, -cy]) inv_shift = transform.SimilarityTransform(translation=[cx, cy]) r = transform.SimilarityTransform(rotation=np.deg2rad(rot_degrees)) m = (shift + (r + inv_shift)).inverse scaled_mask = transform.warp(mask, m) > 0.5 return scaled_mask
Example #9
Source File: face_align.py From insightface with MIT License | 6 votes |
def estimate_norm(lmk, image_size = 112, mode='arcface'): assert lmk.shape==(5,2) tform = trans.SimilarityTransform() lmk_tran = np.insert(lmk, 2, values=np.ones(5), axis=1) min_M = [] min_index = [] min_error = float('inf') if mode=='arcface': assert image_size==112 src = arcface_src else: src = src_map[image_size] for i in np.arange(src.shape[0]): tform.estimate(lmk, src[i]) M = tform.params[0:2,:] results = np.dot(M, lmk_tran.T) results = results.T error = np.sum(np.sqrt(np.sum((results - src[i]) ** 2,axis=1))) # print(error) if error< min_error: min_error = error min_M = M min_index = i return min_M, min_index
Example #10
Source File: alignment.py From advhat with MIT License | 5 votes |
def preprocess(img, landmark): image_size = [112,112] src = np.array([ [38.2946, 51.6963], [73.5318, 51.5014], [56.0252, 71.7366], [41.5493, 92.3655], [70.7299, 92.2041] ], dtype=np.float32) dst = landmark.astype(np.float32) tform = trans.SimilarityTransform() tform.estimate(dst, src) M = tform.params[0:2,:] warped = cv2.warpAffine(img,M,(image_size[1],image_size[0]), borderValue = 0.0) return warped
Example #11
Source File: demo.py From advhat with MIT License | 5 votes |
def preprocess(img, landmark): image_size = [112,112] src = np.array([ [38.2946, 51.6963], [73.5318, 51.5014], [56.0252, 71.7366], [41.5493, 92.3655], [70.7299, 92.2041] ], dtype=np.float32) dst = landmark.astype(np.float32) tform = trans.SimilarityTransform() tform.estimate(dst, src) M = tform.params[0:2,:] warped = cv2.warpAffine(img,M,(image_size[1],image_size[0]), borderValue = 0.0) return warped
Example #12
Source File: face_preparation.py From advhat with MIT License | 5 votes |
def preprocess(img, landmark): image_size = [600,600] src = 600./112.*np.array([ [38.2946, 51.6963], [73.5318, 51.5014], [56.0252, 71.7366], [41.5493, 92.3655], [70.7299, 92.2041] ], dtype=np.float32) dst = landmark.astype(np.float32) tform = trans.SimilarityTransform() tform.estimate(dst, src) M = tform.params[0:2,:] warped = cv2.warpAffine(img,M,(image_size[1],image_size[0]), borderValue = 0.0) return warped
Example #13
Source File: input_sixteen.py From kaggle-satellite-imagery-feature-detection with MIT License | 5 votes |
def _align_two_rasters(img1, img2): p1 = normalize(img1[10:-10, 10:-10, 0].astype(np.float32)) p2 = normalize(img2[10:-10, 10:-10, 7].astype(np.float32)) x, y = poc(p2, p1) print('x: {0:.5f} y: {1:.5f}'.format(x, y)) t_form = tf.SimilarityTransform(translation=(x, y)) img3 = tf.warp(img2, t_form) return img3
Example #14
Source File: geometric.py From ViolenceDetection with Apache License 2.0 | 5 votes |
def _warp_cv2(self, image, scale_x, scale_y, translate_x_px, translate_y_px, rotate, shear, cval, mode, order): height, width = image.shape[0], image.shape[1] shift_x = width / 2.0 - 0.5 shift_y = height / 2.0 - 0.5 matrix_to_topleft = tf.SimilarityTransform(translation=[-shift_x, -shift_y]) matrix_transforms = tf.AffineTransform( scale=(scale_x, scale_y), translation=(translate_x_px, translate_y_px), rotation=math.radians(rotate), shear=math.radians(shear) ) matrix_to_center = tf.SimilarityTransform(translation=[shift_x, shift_y]) matrix = (matrix_to_topleft + matrix_transforms + matrix_to_center) image_warped = cv2.warpAffine( image, matrix.params[:2], #np.zeros((2, 3)), dsize=(width, height), flags=order, borderMode=mode, borderValue=cval ) # cv2 warp drops last axis if shape is (H, W, 1) if image_warped.ndim == 2: image_warped = image_warped[..., np.newaxis] return image_warped
Example #15
Source File: geometric.py From ViolenceDetection with Apache License 2.0 | 5 votes |
def _warp_skimage(self, image, scale_x, scale_y, translate_x_px, translate_y_px, rotate, shear, cval, mode, order): height, width = image.shape[0], image.shape[1] shift_x = width / 2.0 - 0.5 shift_y = height / 2.0 - 0.5 matrix_to_topleft = tf.SimilarityTransform(translation=[-shift_x, -shift_y]) matrix_transforms = tf.AffineTransform( scale=(scale_x, scale_y), translation=(translate_x_px, translate_y_px), rotation=math.radians(rotate), shear=math.radians(shear) ) matrix_to_center = tf.SimilarityTransform(translation=[shift_x, shift_y]) matrix = (matrix_to_topleft + matrix_transforms + matrix_to_center) image_warped = tf.warp( image, matrix.inverse, order=order, mode=mode, cval=cval, preserve_range=True ) # warp changes uint8 to float64, making this necessary if image_warped.dtype != image.dtype: image_warped = image_warped.astype(image.dtype, copy=False) return image_warped
Example #16
Source File: crop.py From whale-2015 with Apache License 2.0 | 5 votes |
def crop(path, bonnet, blowhole): im = io.imread(path).astype(np.uint8) if doscale == 1: bonnet['y'] *= float(im.shape[0]) / imwidth bonnet['x'] *= float(im.shape[1]) / imwidth blowhole['y'] *= float(im.shape[0]) / imwidth blowhole['x'] *= float(im.shape[1]) / imwidth y = bonnet['y'] - blowhole['y'] x = bonnet['x'] - blowhole['x'] dist = math.hypot(x, y) minh = 10 minw = 20 croph = int((im.shape[0] - 1.0 * dist) // 2) cropw = int((im.shape[1] - 2.0 * dist) // 2) newh = im.shape[0] - 2 * croph neww = im.shape[1] - 2 * cropw if croph <= 0 or cropw <= 0 or newh < minh or neww < minw: print(' %s unchanged' % os.path.basename(path)) else: angle = math.atan2(y, x) * 180 / math.pi centery = 0.4 * bonnet['y'] + 0.6 * blowhole['y'] centerx = 0.4 * bonnet['x'] + 0.6 * blowhole['x'] center = (centerx, centery) im = tf.rotate(im, angle, resize=False, center=center, preserve_range=True) imcenter = (im.shape[1] / 2, im.shape[0] / 2) trans = (center[0] - imcenter[0], center[1] - imcenter[1]) tform = tf.SimilarityTransform(translation=trans) im = tf.warp(im, tform) im = im[croph:-croph, cropw:-cropw] path = os.path.join(dstdir, os.path.basename(path)) io.imsave(path, im.astype(np.uint8)) return im.shape[0], im.shape[1]
Example #17
Source File: img_helper.py From insightface with MIT License | 5 votes |
def transform(data, center, output_size, scale, rotation): scale_ratio = float(output_size)/scale rot = float(rotation)*np.pi/180.0 #translation = (output_size/2-center[0]*scale_ratio, output_size/2-center[1]*scale_ratio) t1 = stf.SimilarityTransform(scale=scale_ratio) cx = center[0]*scale_ratio cy = center[1]*scale_ratio t2 = stf.SimilarityTransform(translation=(-1*cx, -1*cy)) t3 = stf.SimilarityTransform(rotation=rot) t4 = stf.SimilarityTransform(translation=(output_size/2, output_size/2)) t = t1+t2+t3+t4 trans = t.params[0:2] #print('M', scale, rotation, trans) cropped = cv2.warpAffine(data,trans,(output_size, output_size), borderValue = 0.0) return cropped, trans
Example #18
Source File: expt_utils.py From pyxem with GNU General Public License v3.0 | 5 votes |
def convert_affine_to_transform(D, shape): """ Converts an affine transform on a diffraction pattern to a suitable form for skimage.transform.warp() Parameters ---------- D : np.array Affine transform to be applied shape : tuple Shape tuple in form (y,x) for the diffraction pattern Returns ------- transformation : np.array 3x3 numpy array of the transformation to be applied. """ shift_x = (shape[1] - 1) / 2 shift_y = (shape[0] - 1) / 2 tf_shift = tf.SimilarityTransform(translation=[-shift_x, -shift_y]) tf_shift_inv = tf.SimilarityTransform(translation=[shift_x, shift_y]) # This defines the transform you want to perform distortion = tf.AffineTransform(matrix=D) # skimage transforms can be added like this, does matrix multiplication, # hence the need for the brackets. (Note tf.warp takes the inverse) transformation = (tf_shift + (distortion + tf_shift_inv)).inverse return transformation
Example #19
Source File: jhamski.py From facial_expressions with Apache License 2.0 | 5 votes |
def warp12(img, name): tform = tf.SimilarityTransform(scale=1, rotation=math.pi / 4, translation=(img.shape[0] / 2, -100)) af_img = tf.warp(img, tform) save_image(af_img, name, 'warp1') af_img2 = tf.warp(img, tform.inverse) save_image(af_img2, name, 'warp2')
Example #20
Source File: test_align.py From astroalign with MIT License | 5 votes |
def test_register_nddata(self): from astropy.nddata import NDData from skimage.transform import SimilarityTransform transf = SimilarityTransform(rotation=np.pi / 2.0, translation=(1, 0)) nd = NDData( [[0.0, 1.0], [2.0, 3.0]], mask=[[True, False], [False, False]] ) registered_img, footp = aa.apply_transform( transf, nd, nd, propagate_mask=True ) err = np.linalg.norm( registered_img - np.array([[2.0, 0.0], [3.0, 1.0]]) ) self.assertLess(err, 1e-6) err_mask = footp == np.array([[False, True], [False, False]]) self.assertTrue(all(err_mask.flatten())) # Test now if there is no assigned mask during creation nd = NDData([[0.0, 1.0], [2.0, 3.0]]) registered_img, footp = aa.apply_transform( transf, nd, nd, propagate_mask=True ) err = np.linalg.norm( registered_img - np.array([[2.0, 0.0], [3.0, 1.0]]) ) self.assertLess(err, 1e-6) err_mask = footp == np.array([[False, False], [False, False]]) self.assertTrue(all(err_mask.flatten()))
Example #21
Source File: test_align.py From astroalign with MIT License | 5 votes |
def test_register_ccddata(self): from ccdproc import CCDData from skimage.transform import SimilarityTransform transf = SimilarityTransform(rotation=np.pi / 2.0, translation=(1, 0)) cd = CCDData( [[0.0, 1.0], [2.0, 3.0]], mask=[[True, False], [False, False]], unit="adu", ) registered_img, footp = aa.apply_transform( transf, cd, cd, propagate_mask=True ) err = np.linalg.norm( registered_img - np.array([[2.0, 0.0], [3.0, 1.0]]) ) self.assertLess(err, 1e-6) err_mask = footp == np.array([[False, True], [False, False]]) self.assertTrue(all(err_mask.flatten())) cd = CCDData([[0.0, 1.0], [2.0, 3.0]], unit="adu") registered_img, footp = aa.apply_transform( transf, cd, cd, propagate_mask=True ) err = np.linalg.norm( registered_img - np.array([[2.0, 0.0], [3.0, 1.0]]) ) self.assertLess(err, 1e-6) err_mask = footp == np.array([[False, False], [False, False]]) self.assertTrue(all(err_mask.flatten()))
Example #22
Source File: segmentation.py From kraken with Apache License 2.0 | 5 votes |
def _rotate(image, angle, center, scale, cval=0): """ Rotate function taken mostly from scikit image. Main difference is that this one allows dimensional scaling and records the final translation to ensure no image content is lost. This is needed to rotate the seam back into the original image. """ rows, cols = image.shape[0], image.shape[1] tform1 = SimilarityTransform(translation=center) tform2 = SimilarityTransform(rotation=angle) tform3 = SimilarityTransform(translation=-center) tform4 = AffineTransform(scale=(1/scale, 1)) tform = tform4 + tform3 + tform2 + tform1 corners = np.array([ [0, 0], [0, rows - 1], [cols - 1, rows - 1], [cols - 1, 0] ]) corners = tform.inverse(corners) minc = corners[:, 0].min() minr = corners[:, 1].min() maxc = corners[:, 0].max() maxr = corners[:, 1].max() out_rows = maxr - minr + 1 out_cols = maxc - minc + 1 output_shape = np.around((out_rows, out_cols)) # fit output image in new shape translation = (minc, minr) tform5 = SimilarityTransform(translation=translation) tform = tform5 + tform tform.params[2] = (0, 0, 1) return tform, warp(image, tform, output_shape=output_shape, order=0, cval=cval, clip=False, preserve_range=True)
Example #23
Source File: test_align.py From astroalign with MIT License | 5 votes |
def test_register_npma(self): from skimage.transform import SimilarityTransform transf = SimilarityTransform(rotation=np.pi / 2.0, translation=(1, 0)) nparr = np.array([[0.0, 1.0], [2.0, 3.0]]) mask = [[True, False], [False, False]] ma = np.ma.array(nparr, mask=mask) registered_img, footp = aa.apply_transform( transf, ma, ma, propagate_mask=True ) err = np.linalg.norm( registered_img - np.array([[2.0, 0.0], [3.0, 1.0]]) ) self.assertLess(err, 1e-6) err_mask = footp == np.array([[False, True], [False, False]]) self.assertTrue(all(err_mask.flatten())) ma = np.ma.array(nparr) registered_img, footp = aa.apply_transform( transf, ma, ma, propagate_mask=True ) err = np.linalg.norm( registered_img - np.array([[2.0, 0.0], [3.0, 1.0]]) ) self.assertLess(err, 1e-6) err_mask = footp == np.array([[False, False], [False, False]]) self.assertTrue(all(err_mask.flatten()))
Example #24
Source File: img_helper.py From 1.FaceRecognition with MIT License | 5 votes |
def transform(data, center, output_size, scale, rotation): scale_ratio = float(output_size)/scale rot = float(rotation)*np.pi/180.0 #translation = (output_size/2-center[0]*scale_ratio, output_size/2-center[1]*scale_ratio) t1 = stf.SimilarityTransform(scale=scale_ratio) cx = center[0]*scale_ratio cy = center[1]*scale_ratio t2 = stf.SimilarityTransform(translation=(-1*cx, -1*cy)) t3 = stf.SimilarityTransform(rotation=rot) t4 = stf.SimilarityTransform(translation=(output_size/2, output_size/2)) t = t1+t2+t3+t4 trans = t.params[0:2] #print('M', scale, rotation, trans) cropped = cv2.warpAffine(data,trans,(output_size, output_size), borderValue = 0.0) return cropped, trans
Example #25
Source File: augment.py From autoencoding_beyond_pixels with MIT License | 5 votes |
def img_augment(img, translation=0.0, scale=1.0, rotation=0.0, gamma=1.0, contrast=1.0, hue=0.0, border_mode='constant'): if not (np.all(np.isclose(translation, [0.0, 0.0])) and np.isclose(scale, 1.0) and np.isclose(rotation, 0.0)): img_center = np.array(img.shape[:2]) / 2.0 scale = (scale, scale) transf = transform.SimilarityTransform(translation=-img_center) transf += transform.SimilarityTransform(scale=scale, rotation=rotation) translation = img_center + translation transf += transform.SimilarityTransform(translation=translation) img = transform.warp(img, transf, order=3, mode=border_mode) if not np.isclose(gamma, 1.0): img **= gamma colorspace = 'rgb' if not np.isclose(contrast, 1.0): img = color.convert_colorspace(img, colorspace, 'hsv') colorspace = 'hsv' img[..., 1:] **= contrast if not np.isclose(hue, 0.0): img = color.convert_colorspace(img, colorspace, 'hsv') colorspace = 'hsv' img[..., 0] += hue img[img[..., 0] > 1.0, 0] -= 1.0 img[img[..., 0] < 0.0, 0] += 1.0 img = color.convert_colorspace(img, colorspace, 'rgb') if np.min(img) < 0.0 or np.max(img) > 1.0: raise ValueError('Invalid values in output image.') return img
Example #26
Source File: applyGeometricTransformation.py From multi-object-tracking with GNU General Public License v3.0 | 5 votes |
def applyGeometricTransformation(startXs, startYs, newXs, newYs, bbox): n_object = bbox.shape[0] newbbox = np.zeros_like(bbox) Xs = newXs.copy() Ys = newYs.copy() for obj_idx in range(n_object): startXs_obj = startXs[:,[obj_idx]] startYs_obj = startYs[:,[obj_idx]] newXs_obj = newXs[:,[obj_idx]] newYs_obj = newYs[:,[obj_idx]] desired_points = np.hstack((startXs_obj,startYs_obj)) actual_points = np.hstack((newXs_obj,newYs_obj)) t = tf.SimilarityTransform() t.estimate(dst=actual_points, src=desired_points) mat = t.params # estimate the new bounding box with all the feature points # coords = np.vstack((bbox[obj_idx,:,:].T,np.array([1,1,1,1]))) # new_coords = mat.dot(coords) # newbbox[obj_idx,:,:] = new_coords[0:2,:].T # estimate the new bounding box with only the inliners (Added by Yongyi Wang) THRES = 1 projected = mat.dot(np.vstack((desired_points.T.astype(float),np.ones([1,np.shape(desired_points)[0]])))) distance = np.square(projected[0:2,:].T - actual_points).sum(axis = 1) actual_inliers = actual_points[distance < THRES] desired_inliers = desired_points[distance < THRES] if np.shape(desired_inliers)[0]<4: print('too few points') actual_inliers = actual_points desired_inliers = desired_points t.estimate(dst=actual_inliers, src=desired_inliers) mat = t.params coords = np.vstack((bbox[obj_idx,:,:].T,np.array([1,1,1,1]))) new_coords = mat.dot(coords) newbbox[obj_idx,:,:] = new_coords[0:2,:].T Xs[distance >= THRES, obj_idx] = -1 Ys[distance >= THRES, obj_idx] = -1 return Xs, Ys, newbbox
Example #27
Source File: points_crop.py From kaggle-right-whale with MIT License | 5 votes |
def get_head_crop(img, pt1, pt2): im = img.copy() minh = 10 minw = 20 x = pt1[0] - pt2[0] y = pt1[1] - pt2[1] dist = math.hypot(x, y) croph = int((im.shape[0] - 1.0 * dist) // 2) cropw = int((im.shape[1] - 2.0 * dist) // 2) newh = im.shape[0] - 2 * croph neww = im.shape[1] - 2 * cropw if croph <= 0 or cropw <= 0 or newh < minh or neww < minw: return im else: angle = math.atan2(y, x) * 180 / math.pi centery = 0.4 * pt1[1] + 0.6 * pt2[1] centerx = 0.4 * pt1[0] + 0.6 * pt2[0] center = (centerx, centery) im = rotate(im, angle, resize=False, center=center) imcenter = (im.shape[1] / 2, im.shape[0] / 2) trans = (center[0] - imcenter[0], center[1] - imcenter[1]) tform = SimilarityTransform(translation=trans) im = warp(im, tform) im = im[croph:-croph, cropw:-cropw] return im
Example #28
Source File: geometry.py From PassportEye with MIT License | 5 votes |
def _compensate_rotation_shift(self, img, scale): """This is an auxiliary method used by extract_from_image. It is needed due to particular specifics of the skimage.transform.rotate implementation. Namely, when you use rotate(... , resize=True), the rotated image is rotated and shifted by certain amount. Thus when we need to cut out the box from the image, we need to account for this shift. We do this by repeating the computation from skimage.transform.rotate here. TODO: This makes the code uncomfortably coupled to SKImage (e.g. this logic is appropriate for skimage 0.12.1, but not for 0.11, and no one knows what happens in later versions). A solution would be to use skimage.transform.warp with custom settings, but we can think of it later. """ ctr = np.asarray([self.center[1]*scale, self.center[0]*scale]) tform1 = transform.SimilarityTransform(translation=ctr) tform2 = transform.SimilarityTransform(rotation=np.pi/2 - self.angle) tform3 = transform.SimilarityTransform(translation=-ctr) tform = tform3 + tform2 + tform1 rows, cols = img.shape[0], img.shape[1] corners = np.array([ [0, 0], [0, rows - 1], [cols - 1, rows - 1], [cols - 1, 0] ]) corners = tform.inverse(corners) minc = corners[:, 0].min() minr = corners[:, 1].min() maxc = corners[:, 0].max() maxr = corners[:, 1].max() # SKImage 0.11 version out_rows = maxr - minr + 1 out_cols = maxc - minc + 1 # fit output image in new shape return ((cols - out_cols) / 2., (rows - out_rows) / 2.)
Example #29
Source File: poc.py From kaggle-satellite-imagery-feature-detection with MIT License | 4 votes |
def test(test_func): lena = imread('lena512.png') n = 100 error_all = np.zeros([n]) pbar = progressbar.ProgressBar(max_value=n) for i in range(n): pbar.update(i+1) x_true = np.random.random()*6-5 y_true = np.random.random()*6-5 # ex) left:5, up:30 => translation=(5, 30) t_form = tf.SimilarityTransform(translation=(x_true, y_true)) lena_shift = tf.warp(lena, t_form) a1 = np.random.randint(10, 50) a2 = np.random.randint(10, 50) a3 = np.random.randint(10, 50) a4 = np.random.randint(10, 50) img1 = lena[a1:-a2, a3:-a4] img2 = lena_shift[a1:-a2, a3:-a4] x_est, y_est = test_func(img1, img2) # print("x: {0:.3f}, x: {0:.3f}".format(x_true, y_true)) # print("x: {0:.3f}, y: {0:.3f}".format(x_est, y_est)) value = math.sqrt((x_true - x_est)**2 + (y_true - y_est)**2) error_all[i] = value ave = np.average(error_all) std = np.std(error_all) print("\terror: {0:.3f} +- {1:.3f}".format(ave, std)) #------------------------------ # main #------------------------------
Example #30
Source File: models.py From rainymotion with MIT License | 4 votes |
def run(self): """ Run nowcasting calculations. Returns ------- nowcasts : 3D numpy array of shape (lead_steps, dim_x, dim_y). """ # define available transformations dictionary transformations = {'euclidean': sktf.EuclideanTransform(), 'similarity': sktf.SimilarityTransform(), 'affine': sktf.AffineTransform(), 'projective': sktf.ProjectiveTransform()} # scale input data to uint8 [0-255] with self.scaler data_scaled, c1, c2 = self.scaler(self.input_data) # set up transformer object trf = transformations[self.warper] # obtain source and target points if self.extrapolation == "linear": pts_source, pts_target_container = _sparse_linear(data_instance=data_scaled, of_params=self.of_params, lead_steps=self.lead_steps) elif self.extrapolation == "simple_delta": pts_source, pts_target_container = _sparse_sd(data_instance=data_scaled, of_params=self.of_params, lead_steps=self.lead_steps) # now we can start to find nowcasted image # for every candidate of projected sets of points # container for our nowcasts last_frame = data_scaled[-1] nowcst_frames = [] for lead_step, pts_target in enumerate(pts_target_container): # estimate transformation matrix # based on source and traget points trf.estimate(pts_source, pts_target) # make a nowcast nowcst_frame = sktf.warp(last_frame/255, trf.inverse) # transformations dealing with strange behaviour nowcst_frame = (nowcst_frame*255).astype('uint8') # add to the container nowcst_frames.append(nowcst_frame) nowcst_frames = np.stack(nowcst_frames, axis=0) nowcst_frames = self.inverse_scaler(nowcst_frames, c1, c2) return nowcst_frames