Python skimage.img_as_float() Examples

The following are 30 code examples of skimage.img_as_float(). 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 , or try the search function .
Example #1
Source File: preprocessing.py    From video_to_sequence with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def preprocess_frame(image, target_height=224, target_width=224):

    if len(image.shape) == 2:
        image = np.tile(image[:,:,None], 3)
    elif len(image.shape) == 4:
        image = image[:,:,:,0]

    image = skimage.img_as_float(image).astype(np.float32)
    height, width, rgb = image.shape
    if width == height:
        resized_image = cv2.resize(image, (target_height,target_width))

    elif height < width:
        resized_image = cv2.resize(image, (int(width * float(target_height)/height), target_width))
        cropping_length = int((resized_image.shape[1] - target_height) / 2)
        resized_image = resized_image[:,cropping_length:resized_image.shape[1] - cropping_length]

    else:
        resized_image = cv2.resize(image, (target_height, int(height * float(target_width) / width)))
        cropping_length = int((resized_image.shape[0] - target_width) / 2)
        resized_image = resized_image[cropping_length:resized_image.shape[0] - cropping_length,:]

    return cv2.resize(resized_image, (target_height, target_width)) 
Example #2
Source File: visualClef.py    From Deep-Plant with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def crop_image(self, x, target_height=224, target_width=224):
        image = skimage.img_as_float(skimage.io.imread(x)).astype(np.float32)

        if len(image.shape) == 2:
            image = np.tile(image[:,:,None], 3)
        elif len(image.shape) == 4:
            image = image[:,:,:,0]
    
        height, width, rgb = image.shape
        if width == height:
            resized_image = cv2.resize(image, (target_height,target_width))
      
        elif height < width:
            resized_image = cv2.resize(image, (int(width * float(target_height)/height), target_width))
            cropping_length = int((resized_image.shape[1] - target_height) / 2)
            resized_image = resized_image[:,cropping_length:resized_image.shape[1] - cropping_length]

        else:
            resized_image = cv2.resize(image, (target_height, int(height * float(target_width) / width)))
            cropping_length = int((resized_image.shape[0] - target_width) / 2)
            resized_image = resized_image[cropping_length:resized_image.shape[0] - cropping_length,:]

        return cv2.resize(resized_image, (target_height, target_width))    
    
####### Network Parameters ######## 
Example #3
Source File: load_ops.py    From taskonomy with MIT License 6 votes vote down vote up
def resize_rescale_imagenet(img, new_dims, interp_order=1, current_scale=None, no_clip=False):
    """
    Resize an image array with interpolation, and rescale to be 
      between 
    Parameters
    ----------
    im : (H x W x K) ndarray
    new_dims : (height, width) tuple of new dimensions.
    new_scale : (min, max) tuple of new scale.
    interp_order : interpolation order, default is linear.
    Returns
    -------
    im : resized ndarray with shape (new_dims[0], new_dims[1], K)
    """
    img = skimage.img_as_float( img )
    img = resize_image( img, new_dims, interp_order )
    img = img[:,:,[2,1,0]] * 255.
    mean_bgr = [103.062623801, 115.902882574, 123.151630838]
    img = img - mean_bgr
    return img 
Example #4
Source File: transform.py    From deep_demosaick with MIT License 6 votes vote down vote up
def __call__(self, sample):
        image_gt, image_input, image_mosaic, filename = sample['image_gt'], sample['image_input'], \
                                              sample['image_mosaic'], sample['filename']

        h, w = image_gt.shape[:2]
        if isinstance(self.output_size, int):
            if h > w:
                new_h, new_w = self.output_size * h / w, self.output_size
            else:
                new_h, new_w = self.output_size, self.output_size * w / h
        else:
            new_h, new_w = self.output_size

        new_h, new_w = int(new_h), int(new_w)

        image_gt = transform.resize(skimage.img_as_float(image_gt), (new_h, new_w))
        image_input = transform.resize(skimage.img_as_float(image_input), (new_h, new_w))
        image_mosaic = transform.resize(skimage.img_as_float(image_mosaic), (new_h, new_w))
        return {'image_gt': image_gt, 'image_input': image_input,
                'image_mosaic': image_mosaic, 'filename': filename} 
Example #5
Source File: StructuredForests.py    From StructuredForests with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def bsds500_test(model, input_root, output_root):
    from skimage import img_as_float, img_as_ubyte
    from skimage.io import imread, imsave

    if not os.path.exists(output_root):
        os.makedirs(output_root)

    image_dir = os.path.join(input_root, "BSDS500", "data", "images", "test")
    file_names = filter(lambda name: name[-3:] == "jpg", os.listdir(image_dir))
    n_image = len(file_names)

    for i, file_name in enumerate(file_names):
        img = img_as_float(imread(os.path.join(image_dir, file_name)))

        edge = img_as_ubyte(model.predict(img))

        imsave(os.path.join(output_root, file_name[:-3] + "png"), edge)

        sys.stdout.write("Processing Image %d/%d\r" % (i + 1, n_image))
        sys.stdout.flush()
    print 
Example #6
Source File: StructuredForests.py    From StructuredForests with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def bsds500_train(input_root):
    import scipy.io as SIO
    from skimage import img_as_float
    from skimage.io import imread

    dataset_dir = os.path.join(input_root, "BSDS500", "data")
    image_dir = os.path.join(dataset_dir, "images", "train")
    label_dir = os.path.join(dataset_dir, "groundTruth", "train")
    data = []

    for file_name in os.listdir(label_dir):
        gts = SIO.loadmat(os.path.join(label_dir, file_name))
        gts = gts["groundTruth"].flatten()
        bnds = [gt["Boundaries"][0, 0] for gt in gts]
        segs = [gt["Segmentation"][0, 0] for gt in gts]

        img = imread(os.path.join(image_dir, file_name[:-3] + "jpg"))
        img = img_as_float(img)

        data.append((img, bnds, segs))

    return data 
Example #7
Source File: caffe_image_features.py    From neuralmonkey with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def crop_image(x, target_height=227, target_width=227):
    image = skimage.img_as_float(skimage.io.imread(x)).astype(np.float32)

    if len(image.shape) == 2:
        image = np.tile(image[:,:,None], 3)
    elif len(image.shape) == 4:
        image = image[:,:,:,0]

    height, width, rgb = image.shape
    if width == height:
        resized_image = skimage.transform.resize(image, (target_height,target_width))

    elif height < width:
        resized_image = skimage.transform.resize(image, (int(width * float(target_height)/height), target_width))
        cropping_length = int((resized_image.shape[1] - target_height) / 2)
        resized_image = resized_image[:,cropping_length:resized_image.shape[1] - cropping_length]

    else:
        resized_image = skimage.transform.resize(image, (target_height, int(height * float(target_width) / width)))
        cropping_length = int((resized_image.shape[0] - target_width) / 2)
        resized_image = resized_image[cropping_length:resized_image.shape[0] - cropping_length,:]

    return skimage.transform.resize(resized_image, (target_height, target_width)) 
Example #8
Source File: demo.py    From lung-segmentation-2d with MIT License 6 votes vote down vote up
def loadDataGeneral(df, path, im_shape):
    X, y = [], []
    for i, item in df.iterrows():
        img = img_as_float(io.imread(path + item[0]))
        mask = io.imread(path + item[1])
        img = transform.resize(img, im_shape)
        img = exposure.equalize_hist(img)
        img = np.expand_dims(img, -1)
        mask = transform.resize(mask, im_shape)
        mask = np.expand_dims(mask, -1)
        X.append(img)
        y.append(mask)
    X = np.array(X)
    y = np.array(y)
    X -= X.mean()
    X /= X.std()

    print '### Dataset loaded'
    print '\t{}'.format(path)
    print '\t{}\t{}'.format(X.shape, y.shape)
    print '\tX:{:.1f}-{:.1f}\ty:{:.1f}-{:.1f}\n'.format(X.min(), X.max(), y.min(), y.max())
    print '\tX.mean = {}, X.std = {}'.format(X.mean(), X.std())
    return X, y 
Example #9
Source File: load_data.py    From lung-segmentation-2d with MIT License 6 votes vote down vote up
def loadDataGeneral(df, path, im_shape):
    """Function for loading arbitrary data in standard formats"""
    X, y = [], []
    for i, item in df.iterrows():
        img = img_as_float(io.imread(path + item[0]))
        mask = io.imread(path + item[1])
        img = transform.resize(img, im_shape)
        img = exposure.equalize_hist(img)
        img = np.expand_dims(img, -1)
        mask = transform.resize(mask, im_shape)
        mask = np.expand_dims(mask, -1)
        X.append(img)
        y.append(mask)
    X = np.array(X)
    y = np.array(y)
    X -= X.mean()
    X /= X.std()

    print '### Dataset loaded'
    print '\t{}'.format(path)
    print '\t{}\t{}'.format(X.shape, y.shape)
    print '\tX:{:.1f}-{:.1f}\ty:{:.1f}-{:.1f}\n'.format(X.min(), X.max(), y.min(), y.max())
    print '\tX.mean = {}, X.std = {}'.format(X.mean(), X.std())
    return X, y 
Example #10
Source File: load_ops.py    From taskonomy with MIT License 6 votes vote down vote up
def load_scaled_image( filename, color=True ):
    """
    Load an image converting from grayscale or alpha as needed.
    From KChen

    Args:
        filename : string
        color : boolean
            flag for color format. True (default) loads as RGB while False
            loads as intensity (if image is already grayscale).
    Returns
        image : an image with type np.float32 in range [0, 1]
            of size (H x W x 3) in RGB or
            of size (H x W x 1) in grayscale.
    By kchen 
    """
    img = skimage.img_as_float(skimage.io.imread(filename, as_grey=not color)).astype(np.float32)
    if img.ndim == 2:
        img = img[:, :, np.newaxis]
        if color:
            img = np.tile(img, (1, 1, 3))
    elif img.shape[2] == 4:
        img = img[:, :, :3]
    return img 
Example #11
Source File: load_ops.py    From taskonomy with MIT License 6 votes vote down vote up
def resize_rescale_image_low_sat(img, new_dims, new_scale, interp_order=1, current_scale=None, no_clip=False):
    """
    Resize an image array with interpolation, and rescale to be 
      between 
    Parameters
    ----------
    im : (H x W x K) ndarray
    new_dims : (height, width) tuple of new dimensions.
    new_scale : (min, max) tuple of new scale.
    interp_order : interpolation order, default is linear.
    Returns
    -------
    im : resized ndarray with shape (new_dims[0], new_dims[1], K)
    """
    img = skimage.img_as_float( img )
    img = resize_image( img, new_dims, interp_order )
    img = np.clip(img, 0.1, 0.9)
    img = rescale_image( img, new_scale, current_scale=current_scale, no_clip=no_clip )
    return img 
Example #12
Source File: load_ops.py    From taskonomy with MIT License 6 votes vote down vote up
def resize_rescale_image_low_sat_2(img, new_dims, new_scale, interp_order=1, current_scale=None, no_clip=False):
    """
    Resize an image array with interpolation, and rescale to be 
      between 
    Parameters
    ----------
    im : (H x W x K) ndarray
    new_dims : (height, width) tuple of new dimensions.
    new_scale : (min, max) tuple of new scale.
    interp_order : interpolation order, default is linear.
    Returns
    -------
    im : resized ndarray with shape (new_dims[0], new_dims[1], K)
    """
    img = skimage.img_as_float( img )
    img = resize_image( img, new_dims, interp_order )
    img = np.clip(img, 0.2, 0.8)
    img = rescale_image( img, new_scale, current_scale=current_scale, no_clip=no_clip )
    return img 
Example #13
Source File: load_ops.py    From taskonomy with MIT License 6 votes vote down vote up
def random_noise_image(img, new_dims, new_scale, interp_order=1 ):
    """
        Add noise to an image

        Args:
        im : (H x W x K) ndarray
        new_dims : (height, width) tuple of new dimensions.
        new_scale : (min, max) tuple of new scale.
        interp_order : interpolation order, default is linear.
    Returns:
            a noisy version of the original clean image
    """
    img = skimage.util.img_as_float( img )
    img = resize_image( img, new_dims, interp_order )
    img = skimage.util.random_noise(img, var=0.01)
    img = rescale_image( img, new_scale )
    return img

#################
# Colorization  #
################# 
Example #14
Source File: load_ops.py    From taskonomy with MIT License 6 votes vote down vote up
def to_light(img, new_dims, new_scale, interp_order=1 ):
    """
    Turn an image into lightness 
        
        Args:
        im : (H x W x K) ndarray
        new_dims : (height, width) tuple of new dimensions.
        new_scale : (min, max) tuple of new scale.
        interp_order : interpolation order, default is linear.
    Returns:
        a lightness version of the original image
    """
    img = skimage.img_as_float( img )
    img = resize_image( img, new_dims, interp_order )
    img = skimage.color.rgb2lab(img)[:,:,0]
    img = rescale_image( img, new_scale, current_scale=[0,100])
    return np.expand_dims(img,2) 
Example #15
Source File: load_ops.py    From taskonomy with MIT License 6 votes vote down vote up
def resize_rescale_image(img, new_dims, new_scale, interp_order=1, current_scale=None, no_clip=False):
    """
    Resize an image array with interpolation, and rescale to be 
      between 
    Parameters
    ----------
    im : (H x W x K) ndarray
    new_dims : (height, width) tuple of new dimensions.
    new_scale : (min, max) tuple of new scale.
    interp_order : interpolation order, default is linear.
    Returns
    -------
    im : resized ndarray with shape (new_dims[0], new_dims[1], K)
    """
    img = skimage.img_as_float( img )
    img = resize_image( img, new_dims, interp_order )
    img = rescale_image( img, new_scale, current_scale=current_scale, no_clip=no_clip )

    return img 
Example #16
Source File: load_ops.py    From taskonomy with MIT License 6 votes vote down vote up
def to_ab(img, new_dims, new_scale, interp_order=1 ):
    """
    Turn an image into ab 
        
        Args:
        im : (H x W x K) ndarray
        new_dims : (height, width) tuple of new dimensions.
        new_scale : (min, max) tuple of new scale.
        interp_order : interpolation order, default is linear.
    Returns:
        a ab version of the original image
    """
    img = skimage.img_as_float( img )
    img = resize_image( img, new_dims, interp_order )
    img = skimage.color.rgb2lab(img)[:,:,1:]
    img = rescale_image( img, new_scale, current_scale=[-100,100])
    return img 
Example #17
Source File: load_ops.py    From taskonomy with MIT License 6 votes vote down vote up
def to_light(img, new_dims, new_scale, interp_order=1 ):
    """
    Turn an image into lightness 
        
        Args:
        im : (H x W x K) ndarray
        new_dims : (height, width) tuple of new dimensions.
        new_scale : (min, max) tuple of new scale.
        interp_order : interpolation order, default is linear.
    Returns:
        a lightness version of the original image
    """
    img = skimage.img_as_float( img )
    img = resize_image( img, new_dims, interp_order )
    img = skimage.color.rgb2lab(img)[:,:,0]
    img = rescale_image( img, new_scale, current_scale=[0,100])
    return np.expand_dims(img,2) 
Example #18
Source File: load_ops.py    From taskonomy with MIT License 6 votes vote down vote up
def to_light_low_sat(img, new_dims, new_scale, interp_order=1 ):
    """
    Turn an image into lightness 
        
        Args:
        im : (H x W x K) ndarray
        new_dims : (height, width) tuple of new dimensions.
        new_scale : (min, max) tuple of new scale.
        interp_order : interpolation order, default is linear.
    Returns:
        a lightness version of the original image
    """
    img = skimage.img_as_float( img )
    img = np.clip(img, 0.2, 0.8)
    img = resize_image( img, new_dims, interp_order )
    img = skimage.color.rgb2lab(img)[:,:,0]
    img = rescale_image( img, new_scale, current_scale=[0,100])
    return np.expand_dims(img,2) 
Example #19
Source File: load_ops.py    From taskonomy with MIT License 6 votes vote down vote up
def resize_rescale_image_gaussian_blur(img, new_dims, new_scale, interp_order=1, blur_strength=4, current_scale=None, no_clip=False):
    """
    Resize an image array with interpolation, and rescale to be 
      between 
    Parameters
    ----------
    im : (H x W x K) ndarray
    new_dims : (height, width) tuple of new dimensions.
    new_scale : (min, max) tuple of new scale.
    interp_order : interpolation order, default is linear.
    Returns
    -------
    im : resized ndarray with shape (new_dims[0], new_dims[1], K)
    """
    img = skimage.img_as_float( img )
    img = resize_image( img, new_dims, interp_order )
    img = rescale_image( img, new_scale, current_scale=current_scale, no_clip=True )
    blurred = gaussian_filter(img, sigma=blur_strength)
    if not no_clip:
        min_val, max_val = new_scale
        np.clip(blurred, min_val, max_val, out=blurred)
    return blurred 
Example #20
Source File: load_ops.py    From taskonomy with MIT License 6 votes vote down vote up
def resize_rescale_image(img, new_dims, new_scale, interp_order=1, current_scale=None, no_clip=False):
    """
    Resize an image array with interpolation, and rescale to be 
      between 
    Parameters
    ----------
    im : (H x W x K) ndarray
    new_dims : (height, width) tuple of new dimensions.
    new_scale : (min, max) tuple of new scale.
    interp_order : interpolation order, default is linear.
    Returns
    -------
    im : resized ndarray with shape (new_dims[0], new_dims[1], K)
    """
    img = skimage.img_as_float( img )
    img = resize_image( img, new_dims, interp_order )
    img = rescale_image( img, new_scale, current_scale=current_scale, no_clip=no_clip )

    return img 
Example #21
Source File: load_ops.py    From taskonomy with MIT License 6 votes vote down vote up
def resize_rescale_image_low_sat_2(img, new_dims, new_scale, interp_order=1, current_scale=None, no_clip=False):
    """
    Resize an image array with interpolation, and rescale to be 
      between 
    Parameters
    ----------
    im : (H x W x K) ndarray
    new_dims : (height, width) tuple of new dimensions.
    new_scale : (min, max) tuple of new scale.
    interp_order : interpolation order, default is linear.
    Returns
    -------
    im : resized ndarray with shape (new_dims[0], new_dims[1], K)
    """
    img = skimage.img_as_float( img )
    img = resize_image( img, new_dims, interp_order )
    img = np.clip(img, 0.2, 0.8)
    # low_sat_scale = [0.05, 0.95]
    # img = rescale_image( img, low_sat_scale, current_scale=current_scale, no_clip=no_clip )
    img = rescale_image( img, new_scale, current_scale=current_scale, no_clip=no_clip )
    return img 
Example #22
Source File: load_ops.py    From taskonomy with MIT License 6 votes vote down vote up
def resize_rescale_imagenet(img, new_dims, interp_order=1, current_scale=None, no_clip=False):
    """
    Resize an image array with interpolation, and rescale to be 
      between 
    Parameters
    ----------
    im : (H x W x K) ndarray
    new_dims : (height, width) tuple of new dimensions.
    new_scale : (min, max) tuple of new scale.
    interp_order : interpolation order, default is linear.
    Returns
    -------
    im : resized ndarray with shape (new_dims[0], new_dims[1], K)
    """
    img = skimage.img_as_float( img )
    img = resize_image( img, new_dims, interp_order )
    #img = rescale_image( img, new_scale, current_scale=current_scale, no_clip=no_clip )
    img = img[:,:,[2,1,0]] * 255.
    root = '/home/ubuntu/task-taxonomy-331b/lib/data'
    #img = img - np.load('{}/mean_image.npy'.format(root))
    mean_bgr = [103.062623801, 115.902882574, 123.151630838]
    img = img - mean_bgr
    return img 
Example #23
Source File: load_ops.py    From taskonomy with MIT License 6 votes vote down vote up
def load_scaled_image( filename, color=True ):
    """
    Load an image converting from grayscale or alpha as needed.
    From KChen

    Args:
        filename : string
        color : boolean
            flag for color format. True (default) loads as RGB while False
            loads as intensity (if image is already grayscale).
    Returns
        image : an image with type np.float32 in range [0, 1]
            of size (H x W x 3) in RGB or
            of size (H x W x 1) in grayscale.
    By kchen 
    """
    img = skimage.img_as_float(skimage.io.imread(filename, as_grey=not color)).astype(np.float32)
    if img.ndim == 2:
        img = img[:, :, np.newaxis]
        if color:
            img = np.tile(img, (1, 1, 3))
    elif img.shape[2] == 4:
        img = img[:, :, :3]
    return img 
Example #24
Source File: core.py    From midlevel-reps with MIT License 6 votes vote down vote up
def resize_rescale_image(img, new_dims, new_scale, interp_order=1, current_scale=None, no_clip=False):
    """
    Resize an image array with interpolation, and rescale to be 
      between 
    Parameters
    ----------
    im : (H x W x K) ndarray
    new_dims : (height, width) tuple of new dimensions.
    new_scale : (min, max) tuple of new scale.
    interp_order : interpolation order, default is linear.
    Returns
    -------
    im : resized ndarray with shape (new_dims[0], new_dims[1], K)
    """
    img = skimage.img_as_float( img )
    img = resize_image( img, new_dims, interp_order )
    img = rescale_image( img, new_scale, current_scale=current_scale, no_clip=no_clip )

    return img 
Example #25
Source File: dataset.py    From tanda with MIT License 6 votes vote down vote up
def load_cifar10_batch(fpath, one_hot=True, as_float=True):
    with open(fpath, 'rb') as f:
        # https://stackoverflow.com/questions/11305790
        if six.PY3:
            data = cPickle.load(f, encoding='latin-1')
        else:
            data = cPickle.load(f)
        X = np.copy(data['data']).reshape(-1, 32*32, 3, order='F')
        X = X.reshape(-1, 32, 32, 3)
        Y = np.array(data['labels'])

        # Convert labels to one hot
        if one_hot:
            Y = to_one_hot(Y)

        # CONVERT TO FLOAT [0,1] TYPE HERE to be consistent with skimage TFs!!!
        # See: http://scikit-image.org/docs/dev/user_guide/data_types.html
        if as_float:
            X = img_as_float(X)
    return X, Y 
Example #26
Source File: load_ops.py    From taskonomy with MIT License 6 votes vote down vote up
def to_light_low_sat(img, new_dims, new_scale, interp_order=1 ):
    """
    Turn an image into lightness 
        
        Args:
        im : (H x W x K) ndarray
        new_dims : (height, width) tuple of new dimensions.
        new_scale : (min, max) tuple of new scale.
        interp_order : interpolation order, default is linear.
    Returns:
        a lightness version of the original image
    """
    img = skimage.img_as_float( img )
    img = np.clip(img, 0.2, 0.8)
    img = resize_image( img, new_dims, interp_order )
    img = skimage.color.rgb2lab(img)[:,:,0]
    img = rescale_image( img, new_scale, current_scale=[0,100])
    return np.expand_dims(img,2) 
Example #27
Source File: tf_eval.py    From 3d-dl with MIT License 5 votes vote down vote up
def adaptive_equalize(img):
    # Adaptive Equalization
    img = img_as_float(img)
    img_adapteq = exposure.equalize_adapthist(img, clip_limit=0.05)
    return img_as_ubyte(img_adapteq) 
Example #28
Source File: core.py    From midlevel-reps with MIT License 5 votes vote down vote up
def resize_image(im, new_dims, interp_order=1):
    """
    Resize an image array with interpolation.
    Parameters
    ----------
    im : (H x W x K) ndarray
    new_dims : (height, width) tuple of new dimensions.
    interp_order : interpolation order, default is linear.
    Returns
    -------
    im : resized ndarray with shape (new_dims[0], new_dims[1], K)
    By kchen @ https://github.com/kchen92/joint-representation/blob/24b30ca6963d2ec99618af379c1e05e1f7026710/lib/data/input_pipeline_feed_dict.py
    """
    if type(im) == PIL.PngImagePlugin.PngImageFile:
        interps = [PIL.Image.NEAREST, PIL.Image.BILINEAR]
        return skimage.util.img_as_float(im.resize(new_dims, interps[interp_order]))
        
    if all( new_dims[i] == im.shape[i] for i in range( len( new_dims ) ) ):
        resized_im = im #return im.astype(np.float32)
    elif im.shape[-1] == 1 or im.shape[-1] == 3:
        #     # skimage is fast but only understands {1,3} channel images
        resized_im = resize(im, new_dims, order=interp_order, preserve_range=True)
    else:
        # ndimage interpolates anything but more slowly.
        scale = tuple(np.array(new_dims, dtype=float) / np.array(im.shape[:2]))
        resized_im = zoom(im, scale + (1,), order=interp_order)
    # resized_im = resized_im.astype(np.float32)
    return resized_im 
Example #29
Source File: core.py    From midlevel-reps with MIT License 5 votes vote down vote up
def rescale_image(im, new_scale=[-1.,1.], current_scale=None, no_clip=False):
    """
    Rescales an image pixel values to target_scale
    
    Args:
        img: A np.float_32 array, assumed between [0,1]
        new_scale: [min,max] 
        current_scale: If not supplied, it is assumed to be in:
            [0, 1]: if dtype=float
            [0, 2^16]: if dtype=uint
            [0, 255]: if dtype=ubyte
    Returns:
        rescaled_image
    """
    # im = im.astype(np.float32)
    if current_scale is not None:
        min_val, max_val = current_scale
        if not no_clip:
            im = np.clip(im, min_val, max_val)
        im = im - min_val
        im /= (max_val - min_val) 
    min_val, max_val = new_scale
    im *= (max_val - min_val)
    im += min_val
    im = skimage.img_as_float(im)

    return im 
Example #30
Source File: ImageEqualization.py    From 3d-dl with MIT License 5 votes vote down vote up
def plot_img_and_hist(image, axes, bins=256):
    """Plot an image along with its histogram and cumulative histogram.

    """
    image = img_as_float(image)
    ax_img, ax_hist = axes
    ax_cdf = ax_hist.twinx()

    # Display image
    ax_img.imshow(image, cmap=plt.cm.gray)
    ax_img.set_axis_off()
    ax_img.set_adjustable('box-forced')

    # Display histogram
    ax_hist.hist(image.ravel(), bins=bins, histtype='step', color='black')
    ax_hist.ticklabel_format(axis='y', style='scientific', scilimits=(0, 0))
    ax_hist.set_xlabel('Pixel intensity')
    ax_hist.set_xlim(0, 1)
    ax_hist.set_yticks([])

    # Display cumulative distribution
    img_cdf, bins = exposure.cumulative_distribution(image, bins)
    ax_cdf.plot(bins, img_cdf, 'r')
    ax_cdf.set_yticks([])

    return ax_img, ax_hist, ax_cdf


# Load an example image