我们从Python开源项目中,提取了以下23个代码示例,用于说明如何使用scipy.ndimage.interpolation.shift()。
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 apply(self, im): """ Apply axis-localized displacements. Parameters ---------- im : ndarray The image or volume to shift """ from scipy.ndimage.interpolation import shift im = rollaxis(im, self.axis) im.setflags(write=True) for ind in range(0, im.shape[0]): im[ind] = shift(im[ind], map(lambda x: -x, self.delta[ind]), mode='nearest') im = rollaxis(im, 0, self.axis+1) return im
def drop_shadow(self, alpha, theta, shift, size, op=0.80): """ alpha : alpha layer whose shadow need to be cast theta : [0,2pi] -- the shadow direction shift : shift in pixels of the shadow size : size of the GaussianBlur filter op : opacity of the shadow (multiplying factor) @return : alpha of the shadow layer (it is assumed that the color is black/white) """ if size%2==0: size -= 1 size = max(1,size) shadow = cv.GaussianBlur(alpha,(size,size),0) [dx,dy] = shift * np.array([-np.sin(theta), np.cos(theta)]) shadow = op*sii.shift(shadow, shift=[dx,dy],mode='constant',cval=0) return shadow.astype('uint8')
def random_track_shift(track, out=None, shift_delta='auto'): if out is None: out = np.ndarray(shape=track.shape, dtype=track.dtype) if shift_delta == 'auto': track_x, track_y = np.where(track > 0) x_from, x_to = np.min(track_x), np.max(track_x) y_from, y_to = np.min(track_y), np.max(track_y) x_delta = np.random.randint(-x_from, out.shape[0] - x_to) y_delta = np.random.randint(-y_from, out.shape[1] - y_to) out = np.roll(track, x_delta, axis=0) out = np.roll(out, y_delta, axis=1) return out else: delta = np.random.uniform(-1.0, 1.0, size=2) * shift_delta return shift(track, delta, output=out, order=0, prefilter=False)
def draw_ellipse(shape, radius, center, FWHM, noise=0): sigma = FWHM / 2.35482 cutoff = 2 * FWHM # draw a circle R = max(radius) zoom_factor = np.array(radius) / R size = int((R + cutoff)*2) c = size // 2 y, x = np.meshgrid(*([np.arange(size)] * 2), indexing='ij') h = np.sqrt((y - c)**2+(x - c)**2) - R mask = np.abs(h) < cutoff im = np.zeros((size,)*2, dtype=np.float) im[mask] += np.exp((h[mask] / sigma)**2/-2)/(sigma*np.sqrt(2*np.pi)) # zoom so that radii are ok with warnings.catch_warnings(): warnings.simplefilter("ignore") im = zoom(im, zoom_factor) # shift and make correct shape center_diff = center - np.array(center_of_mass(im)) left_padding = np.round(center_diff).astype(np.int) subpx_shift = center_diff - left_padding im = shift(im, subpx_shift) im = crop_pad(im, -left_padding, shape) im[im < 0] = 0 assert_almost_equal(center_of_mass(im), center, decimal=2) if noise > 0: im += np.random.random(shape) * noise * im.max() return (im / im.max() * 255).astype(np.uint8)
def draw_ellipsoid(shape, radius, center, FWHM, noise=0): sigma = FWHM / 2.35482 cutoff = 2 * FWHM # draw a sphere R = max(radius) zoom_factor = np.array(radius) / R size = int((R + cutoff)*2) c = size // 2 z, y, x = np.meshgrid(*([np.arange(size)] * 3), indexing='ij') h = np.sqrt((z - c)**2+(y - c)**2+(x - c)**2) - R mask = np.abs(h) < cutoff im = np.zeros((size,)*3, dtype=np.float) im[mask] += np.exp((h[mask] / sigma)**2/-2)/(sigma*np.sqrt(2*np.pi)) # zoom so that radii are ok with warnings.catch_warnings(): warnings.simplefilter("ignore") im = zoom(im, zoom_factor) # shift and make correct shape center_diff = center - np.array(center_of_mass(im)) left_padding = np.round(center_diff).astype(np.int) subpx_shift = center_diff - left_padding im = shift(im, subpx_shift) im = crop_pad(im, -left_padding, shape) im[im < 0] = 0 assert_almost_equal(center_of_mass(im), center, decimal=2) if noise > 0: im += np.random.random(shape) * noise * im.max() return (im / im.max() * 255).astype(np.uint8)
def test_fit(eng): reference = arange(25).reshape(5, 5) algorithm = CrossCorr() deltas = [[1, 2], [-2, 1]] shifted = [shift(reference, delta, mode='wrap', order=0) for delta in deltas] model = algorithm.fit(shifted, reference=reference) assert allclose(model.toarray(), deltas)
def test_fit_3d(eng): reference = arange(125).reshape(5, 5, 5) algorithm = CrossCorr() deltas = [[1, 0, 2], [0, 1, 2]] shifted = [shift(reference, delta, mode='wrap', order=0) for delta in deltas] model = algorithm.fit(shifted, reference=reference) assert allclose(model.toarray(), deltas)
def test_fit_axis(eng): reference = arange(60).reshape(2, 5, 6) algorithm = CrossCorr(axis=0) a = shift(reference[0], [1, 2], mode='wrap', order=0) b = shift(reference[1], [-2, 1], mode='wrap', order=0) c = shift(reference[0], [2, 1], mode='wrap', order=0) d = shift(reference[1], [1, -2], mode='wrap', order=0) shifted = [asarray([a, b]), asarray([c, d]),] model = algorithm.fit(shifted, reference=reference) assert allclose(model.toarray(), [[[1, 2], [-2, 1]], [[2, 1], [1, -2]]])
def apply(self, im): """ Apply an n-dimensional displacement by shifting an image or volume. Parameters ---------- im : ndarray The image or volume to shift """ from scipy.ndimage.interpolation import shift return shift(im, map(lambda x: -x, self.delta), mode='nearest')
def testtime_augmentation(image, label): labels = [] images = [] rotations = [0] flips = [[0,0],[1,0],[0,1],[1,1]] shifts = [[0,0]] zooms = [1] for r in rotations: for f in flips: for s in shifts: for z in zooms: image2 = np.array(image) if f[0]: image2[:,:] = image2[::-1,:] if f[1]: image2 = image2.transpose(1,0) image2[:,:] = image2[::-1,:] image2 = image2.transpose(1,0) #rotate(image2, r, reshape=False, output=image2) #image3 = zoom(image2, [z,z]) #image3 = crop_or_pad(image3, P.INPUT_SIZE, 0) #image2 = image3 # #shift(image2, [s[0],s[1]], output=image2) images.append([image2]) #Adds color channel dimension! labels.append(label) return images, labels
def augment_multi(images,random_flip_x,shift_x,shift_y,rotation_degrees,zoom_factor): pixels = images[0].shape[2] center = pixels/2.-0.5 for i in range(len(images)): image = images[i] if random_flip_x: print "flipping image" #image[:,:] = image[:,::-1] image[:,:,:] = image[:,:,::-1] #original print image.shape if rotation_degrees != 0: print "rotating images" if i == 0: #lung image = rotate(image, rotation_degrees, axes=(1,2), reshape=False,cval=-3000,order=0) else: image = rotate(image, rotation_degrees, axes=(1,2), reshape=False,order=0) print "post rotate ",image.shape image = crop_or_pad_multi(image, pixels, -3000) print image.shape if shift_x != 0 or shift_y != 0: print "shifting images by ",shift_x,shift_y, image.shape if i == 0: image = shift(image, [0,shift_x,shift_y],order=0,cval=-3000) else: image = shift(image, [0,shift_x,shift_y],order=0) images[i] = image return images
def center_tracks(tracks, out=None): c = np.array(tracks.shape[1:], dtype='int') / 2 if out is None: out = np.ndarray(shape=tracks.shape, dtype=tracks.dtype) for i in xrange(tracks.shape[0]): cm = np.array(center_of_mass(tracks[i, :, :]), dtype='int32') out[i, :, :] = shift(tracks[i, :, :], c - cm) return out
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
def recenter(self, centroid_method="2dg"): """ This function ... :return: """ center_x = 0.5 * (self.xsize - 1) center_y = 0.5 * (self.ysize - 1) if centroid_method == "com": x_centroid, y_centroid = self.centroid_com() elif centroid_method == "fit": x_centroid, y_centroid = self.centroid_fit() elif centroid_method == "2dg": x_centroid, y_centroid = self.centroid_2dg() elif centroid_method == "aniano": x_centroid, y_centroid = self.get_maximum_aniano() else: raise ValueError("Invalid centroid method") # Debugging log.debug("The centroid coordinate of the kernel was found to be " + str(x_centroid) + ", " + str(y_centroid)) log.debug("The center of the kernel image is " + str(center_x) + ", " + str(center_y)) # Calculate shift shift_x = center_x - x_centroid shift_y = center_y - y_centroid # If the shift is less than 0.2 pixel, don't shift if shift_x < 0.2 and shift_y <= 0.2: log.debug("Kernel is already perfectly aligned with the center: skipping recentering ...") return # Debugging log.debug("Shifting the kernel center by (" + str(shift_x) + ", " + str(shift_y) + " pixels ...") # Shift self._data = shift(self._data, [shift_x, shift_y]) # CHECK AGAIN if centroid_method == "com": x_centroid, y_centroid = self.centroid_com() elif centroid_method == "fit": x_centroid, y_centroid = self.centroid_fit() elif centroid_method == "2dg": x_centroid, y_centroid = self.centroid_2dg() elif centroid_method == "aniano": x_centroid, y_centroid = self.get_maximum_aniano() else: raise ValueError("Invalid centroid method") new_shift_x = center_x - x_centroid new_shift_y = center_y - y_centroid new_shift_x_relative = abs(new_shift_x) / abs(shift_x) new_shift_y_relative = abs(new_shift_y) / abs(shift_y) #print("new shift x relative " + str(new_shift_x_relative)) #print("new shift y relative " + str(new_shift_y_relative)) if new_shift_x_relative >= 0.1: raise RuntimeError("The recentering of the kernel failed: new x shift = " + str(new_shift_x) + ", previous x shift = " + str(shift_x)) if new_shift_y_relative >= 0.1: raise RuntimeError("The recentering of the kernel failed: new y shift = " + str(new_shift_y) + ", previous y shift = " + str(shift_y)) # -----------------------------------------------------------------
def center_aniano(self): """ This function ... :return: """ # Debugging log.debug("Centering the kernel ...") # FROM CONVOLVE_IMAGE.PRO (G. Aniano) center_x = int(0.5 * (self.xsize - 1)) center_y = int(0.5 * (self.ysize - 1)) # get_maximun,image,x_max,y_max x_max, y_max = self.get_maximum() # ; determine the needed shifts shift_x = center_x - x_max shift_y = center_y - y_max # ; make the shift if nonzero if (shift_x != 0) or (shift_y != 0): # Debugging log.debug("Shifting the kernel center by (" + str(shift_x) + ", " + str(shift_y) + " pixels ...") self._data = shift(self._data, [shift_x,shift_y]) # Y self._data[:abs(shift_y),:] = 0.0 self._data[self.ysize-1-abs(shift_y):self.ysize,:] = 0.0 # X self._data[:,:abs(shift_x)] = 0.0 self._data[:,self.xsize-1-abs(shift_x):] = 0.0 # CHECK # Calculate shift again x_max, y_max = self.get_maximum() new_shift_x = center_x - x_max new_shift_y = center_y - y_max # Raise exception if there is still a shift if (new_shift_x != 0) or (new_shift_y != 0): raise RuntimeError("Something went wrong during the kernel centering: " "new shift x = " + str(new_shift_x) + ", new shift y = " + str(new_shift_y) + " (previous shift x = " + str(shift_x) + ", previous shift y = " + str(shift_y)) # -----------------------------------------------------------------
def get_maximum_aniano(self): """ This function ... :return: """ rad_to_mean = 5 data_copy = self._data.copy() # mean_im = data_copy * 0.0 i_range = range(-int(rad_to_mean), int(rad_to_mean)+1) #print("irange", i_range) for i in i_range: j_range = range(-int(math.sqrt(rad_to_mean ** 2 - i ** 2)), int(math.sqrt(rad_to_mean ** 2 - i ** 2))+1) #print("jrange", j_range) for j in j_range: mean_im += shift(data_copy, [i, j]) mean_im_sum = np.sum(mean_im) #mx = max(mean_im, location) #index = ARRAY_INDICES(mean_im, location) #x_max = index[0] #y_max = index[1] # Get x and y max max_index = np.argmax(mean_im) c = (max_index // len(mean_im[0]), max_index % len(mean_im[0])) x_max = c[1] y_max = c[0] max_value = mean_im[y_max, x_max] where = np.abs(mean_im - max_value) < (5e-4 * mean_im_sum) count = np.sum(where) if count > 1: log.debug("WARNING: The PSF has " + str(count) + "pixels with values similar to its maximum... we will take their centroid...") xsize = data_copy.shape[1] ysize = data_copy.shape[0] xv, yv = np.meshgrid(np.arange(xsize), np.arange(ysize)) # Average x max x_max = np.sum(xv[where]) / float(count) # Average y max y_max = np.sum(xv[where]) / float(count) # Return xmax and ymax position return x_max, y_max # -----------------------------------------------------------------