Python scipy.ndimage 模块,rotate() 实例源码

我们从Python开源项目中,提取了以下35个代码示例,用于说明如何使用scipy.ndimage.rotate()

项目:deeptracking    作者:lvsn    | 项目源码 | 文件源码
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]]
项目:pypher    作者:aboucaud    | 项目源码 | 文件源码
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)
项目:Triplet_Loss_SBIR    作者:TuBui    | 项目源码 | 文件源码
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
项目:visual-search    作者:GYXie    | 项目源码 | 文件源码
def rotate(np_img):
    img = ndimage.rotate(np_img, 10, mode='nearest')
    return img
项目:visual-search    作者:GYXie    | 项目源码 | 文件源码
def main():
    img = imread(args.input_path)
    img = ndimage.rotate(img, args.angle, mode=args.mode)
    misc.imsave(args.output_path, img)
项目:How-to-Learn-from-Little-Data    作者:llSourcell    | 项目源码 | 文件源码
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
项目:NTM-One-Shot-TF    作者:hmishra2250    | 项目源码 | 文件源码
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
项目:haller    作者:bharat    | 项目源码 | 文件源码
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'))
项目:haller    作者:bharat    | 项目源码 | 文件源码
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)
项目:piwall-cvtools    作者:infinnovation    | 项目源码 | 文件源码
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()
项目:fg21sim    作者:liweitianux    | 项目源码 | 文件源码
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
项目:Data-Augmentation    作者:outlace    | 项目源码 | 文件源码
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
项目:Data-Augmentation    作者:outlace    | 项目源码 | 文件源码
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)
项目:MatchingNetworks    作者:AntreasAntoniou    | 项目源码 | 文件源码
def rotate_batch(self, x_batch, axis, k):
        x_batch = rotate(x_batch, k*90, reshape=False, axes=axis, mode="nearest")
        return x_batch
项目:leaf-classification    作者:MWransky    | 项目源码 | 文件源码
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)
项目:leaf-classification    作者:MWransky    | 项目源码 | 文件源码
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)
项目:leaf-classification    作者:MWransky    | 项目源码 | 文件源码
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
项目:leaf-classification    作者:MWransky    | 项目源码 | 文件源码
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)
项目:leaf-classification    作者:MWransky    | 项目源码 | 文件源码
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
项目:tensorflow-mnist-VAE    作者:hwalsuklee    | 项目源码 | 文件源码
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
项目:Triplet_Loss_SBIR    作者:TuBui    | 项目源码 | 文件源码
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
项目:Multi-views-fusion    作者:luogongning    | 项目源码 | 文件源码
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
项目:FingerNet    作者:felixTY    | 项目源码 | 文件源码
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
项目:FingerNet    作者:felixTY    | 项目源码 | 文件源码
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
项目:ntm-one-shot    作者:tristandeleu    | 项目源码 | 文件源码
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
项目:deep-learning-experiments    作者:raghakot    | 项目源码 | 文件源码
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
项目:cnn_workshop    作者:Alfredvc    | 项目源码 | 文件源码
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
项目:one-shot-mann    作者:vineetjain96    | 项目源码 | 文件源码
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
项目:RoadSegmentation    作者:njroussel    | 项目源码 | 文件源码
def rotate_image(image, angle):
    rotated_image = ndimage.rotate(image, angle, mode='reflect', order=0, reshape=False)
    return rotated_image
项目:sparselab    作者:eht-jp    | 项目源码 | 文件源码
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
项目:visual-search    作者:GYXie    | 项目源码 | 文件源码
def main():
    t = time.time()
    img = imread(args.img_file_path)
    imgs = [img, watermark(img), rotate(img), crop(img), mirror(img)]
    imgs_norm = image_normalize(imgs)
    dataset_features = np.load('fc6.npy')

    query_start = time.time()
    query_features = extract_feature(imgs_norm)
    binarizer = preprocessing.Binarizer().fit(query_features)
    query_features = binarizer.transform(query_features)
    print(dataset_features)
    # https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html#scipy.spatial.distance.cdist
    cosine = distance.cdist(dataset_features, query_features, 'cosine')
    print(cosine.shape)
    dis = cosine
    inds_all = argsort(dis, axis=0)  # ???? https://docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html
    print('query cost: %f, dataset: %d, query: %d' % (time.time() - query_start, len(dataset_features), len(imgs)))
    img_names = load_image_names()
    fig, axes = plt.subplots(5, 11, figsize=(22, 10), subplot_kw={'xticks': [], 'yticks': []})
    fig.subplots_adjust(hspace=0.15, wspace=0.01, left=.02, right=.98, top=.92, bottom=.08)
    titles = ['original', 'watermark', 'rotate', 'crop', 'mirror']
    for i in range(len(imgs)):
        topK = []
        inds = inds_all[:, i]
        # print(inds)
        for k in range(10):
            topK.append(img_names[inds[k]])
            print(inds[k], dis[inds[k], i], img_names[inds[k]])

        original = axes[i, 0]
        original.set_title(titles[i])
        img = imgs[i]
        original.imshow(img)
        for j in range(10):
            ax = axes[i, j + 1]
            img = imread(topK[j])
            ax.imshow(img)
            title = '%d : %f' % (j + 1, dis[inds[j], i])
            ax.set_title(title)

    savePath = args.img_file_path + '_search_result.jpg'
    plt.savefig(savePath)
    print(time.time() - t)
    # os.system('open -a Preview.app -F ' + savePath)
项目:miccai17-mmwhs-hybrid    作者:xy0806    | 项目源码 | 文件源码
def get_batch_patches(img_clec, label_clec, patch_dim, batch_size, chn=1, flip_flag=True, rot_flag=True):
    """generate a batch of paired patches for training"""
    batch_img = np.zeros([batch_size, patch_dim, patch_dim, patch_dim, chn]).astype('float32')
    batch_label = np.zeros([batch_size, patch_dim, patch_dim, patch_dim]).astype('int32')

    for k in range(batch_size):
        # randomly select an image pair
        rand_idx = np.arange(len(img_clec))
        np.random.shuffle(rand_idx)
        rand_img = img_clec[rand_idx[0]]
        rand_label = label_clec[rand_idx[0]]
        rand_img = rand_img.astype('float32')
        rand_label = rand_label.astype('int32')

        # randomly select a box anchor
        l, w, h = rand_img.shape
        l_rand = np.arange(l - patch_dim)
        w_rand = np.arange(w - patch_dim)
        h_rand = np.arange(h - patch_dim)
        np.random.shuffle(l_rand)
        np.random.shuffle(w_rand)
        np.random.shuffle(h_rand)
        pos = np.array([l_rand[0], w_rand[0], h_rand[0]])
        # crop
        img_temp = copy.deepcopy(rand_img[pos[0]:pos[0]+patch_dim, pos[1]:pos[1]+patch_dim, pos[2]:pos[2]+patch_dim])
        # normalization
        img_temp = img_temp/255.0
        mean_temp = np.mean(img_temp)
        dev_temp = np.std(img_temp)
        img_norm = (img_temp - mean_temp) / dev_temp

        label_temp = copy.deepcopy(rand_label[pos[0]:pos[0]+patch_dim, pos[1]:pos[1]+patch_dim, pos[2]:pos[2]+patch_dim])

        # possible augmentation
        # rotation
        if rot_flag and np.random.random() > 0.65:
            # print 'rotating patch...'
            rand_angle = [-25, 25]
            np.random.shuffle(rand_angle)
            img_norm = rotate(img_norm, angle=rand_angle[0], axes=(1, 0), reshape=False, order=1)
            label_temp = rotate(label_temp, angle=rand_angle[0], axes=(1, 0), reshape=False, order=0)

        batch_img[k, :, :, :, chn-1] = img_norm
        batch_label[k, :, :, :] = label_temp

    return batch_img, batch_label


# calculate the cube information
项目:cv-utils    作者:gmichaeljaison    | 项目源码 | 文件源码
def add_text_img(img, text, pos, box=None, color=None, thickness=1, scale=1, vertical=False):
    """
    Adds the given text in the image.

    :param img: Input image
    :param text: String text
    :param pos: (x, y) in the image or relative to the given Box object
    :param box: Box object. If not None, the text is placed inside the box.
    :param color: Color of the text.
    :param thickness: Thickness of the font.
    :param scale: Font size scale.
    :param vertical: If true, the text is displayed vertically. (slow)
    :return:
    """
    if color is None:
        color = COL_WHITE

    text = str(text)
    top_left = pos
    if box is not None:
        top_left = box.move(pos).to_int().top_left()
        if top_left[0] > img.shape[1]:
            return

    if vertical:
        if box is not None:
            h, w, d = box.height, box.width, 3
        else:
            h, w, d = img.shape
        txt_img = np.zeros((w, h, d), dtype=np.uint8)
        # 90 deg rotation
        top_left = h - pos[1], pos[0]
        cv.putText(txt_img, text, top_left, cv.FONT_HERSHEY_PLAIN, scale, color, thickness)

        txt_img = ndimage.rotate(txt_img, 90)
        mask = txt_img > 0
        if box is not None:
            im_box = img_box(img, box)
            im_box[mask] = txt_img[mask]
        else:
            img[mask] = txt_img[mask]
    else:
        cv.putText(img, text, top_left, cv.FONT_HERSHEY_PLAIN, scale, color, thickness)
项目:ndmg    作者:neurodata    | 项目源码 | 文件源码
def plot_overlays(atlas, b0, cmaps):
    plt.rcParams.update({'axes.labelsize': 'x-large',
                         'axes.titlesize': 'x-large'})

    if b0.shape == (182, 218, 182):
        x = [78, 90, 100]
        y = [82, 107, 142]
        z = [88, 103, 107]
    else:
        shap = b0.shape
        x = [int(shap[0]*0.35), int(shap[0]*0.51), int(shap[0]*0.65)]
        y = [int(shap[1]*0.35), int(shap[1]*0.51), int(shap[1]*0.65)]
        z = [int(shap[2]*0.35), int(shap[2]*0.51), int(shap[2]*0.65)]
    coords = (x, y, z)

    labs = ['Sagittal Slice (YZ fixed)',
            'Coronal Slice (XZ fixed)',
            'Axial Slice (XY fixed)']
    var = ['X', 'Y', 'Z']
    # create subplot for first slice
    # and customize all labels
    idx = 0
    for i, coord in enumerate(coords):
        for pos in coord:
            idx += 1
            ax = plt.subplot(3, 3, idx)
            ax.set_title(var[i] + " = " + str(pos))
            if i == 0:
                image = ndimage.rotate(b0[pos, :, :], 90)
                atl = ndimage.rotate(atlas[pos, :, :], 90)
            elif i == 1:
                image = ndimage.rotate(b0[:, pos, :], 90)
                atl = ndimage.rotate(atlas[:, pos, :], 90)
            else:
                image = b0[:, :, pos]
                atl = atlas[:, :, pos]

            if idx % 3 == 1:
                ax.set_ylabel(labs[i])
                ax.yaxis.set_ticks([0, image.shape[0]/2, image.shape[0] - 1])
                ax.xaxis.set_ticks([0, image.shape[1]/2, image.shape[1] - 1])

            min_val, max_val = get_min_max(image)
            plt.imshow(atl, interpolation='none', cmap=cmaps[0], alpha=0.5)
            plt.imshow(image, interpolation='none', cmap=cmaps[1], alpha=0.5,
                       vmin=min_val, vmax=max_val)

    fig = plt.gcf()
    fig.set_size_inches(12.5, 10.5, forward=True)
    return fig
项目:ndmg    作者:neurodata    | 项目源码 | 文件源码
def plot_rgb(im):
    plt.rcParams.update({'axes.labelsize': 'x-large',
                         'axes.titlesize': 'x-large'})

    if im.shape == (182, 218, 182):
        x = [78, 90, 100]
        y = [82, 107, 142]
        z = [88, 103, 107]
    else:
        shap = im.shape
        x = [int(shap[0]*0.35), int(shap[0]*0.51), int(shap[0]*0.65)]
        y = [int(shap[1]*0.35), int(shap[1]*0.51), int(shap[1]*0.65)]
        z = [int(shap[2]*0.35), int(shap[2]*0.51), int(shap[2]*0.65)]
    coords = (x, y, z)

    labs = ['Sagittal Slice (YZ fixed)',
            'Coronal Slice (XZ fixed)',
            'Axial Slice (XY fixed)']
    var = ['X', 'Y', 'Z']

    idx = 0
    for i, coord in enumerate(coords):
        for pos in coord:
            idx += 1
            ax = plt.subplot(3, 3, idx)
            ax.set_title(var[i] + " = " + str(pos))
            if i == 0:
                image = ndimage.rotate(im[pos, :, :], 90)
            elif i == 1:
                image = ndimage.rotate(im[:, pos, :], 90)
            else:
                image = im[:, :, pos]

            if idx % 3 == 1:
                ax.set_ylabel(labs[i])
                ax.yaxis.set_ticks([0, image.shape[0]/2, image.shape[0] - 1])
                ax.xaxis.set_ticks([0, image.shape[1]/2, image.shape[1] - 1])

            plt.imshow(image)

    fig = plt.gcf()
    fig.set_size_inches(12.5, 10.5, forward=True)
    return fig