当前位置: 首页>>代码示例>>Python>>正文


Python transform.resize方法代码示例

本文整理汇总了Python中skimage.transform.resize方法的典型用法代码示例。如果您正苦于以下问题:Python transform.resize方法的具体用法?Python transform.resize怎么用?Python transform.resize使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在skimage.transform的用法示例。


在下文中一共展示了transform.resize方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: PreprocessContentImage

# 需要导入模块: from skimage import transform [as 别名]
# 或者: from skimage.transform import resize [as 别名]
def PreprocessContentImage(path, long_edge):
    img = io.imread(path)
    logging.info("load the content image, size = %s", img.shape[:2])
    factor = float(long_edge) / max(img.shape[:2])
    new_size = (int(img.shape[0] * factor), int(img.shape[1] * factor))
    resized_img = transform.resize(img, new_size)
    sample = np.asarray(resized_img) * 256
    # swap axes to make image from (224, 224, 3) to (3, 224, 224)
    sample = np.swapaxes(sample, 0, 2)
    sample = np.swapaxes(sample, 1, 2)
    # sub mean
    sample[0, :] -= 123.68
    sample[1, :] -= 116.779
    sample[2, :] -= 103.939
    logging.info("resize the content image to %s", new_size)
    return np.resize(sample, (1, 3, sample.shape[1], sample.shape[2])) 
开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:18,代码来源:nstyle.py

示例2: PreprocessImage

# 需要导入模块: from skimage import transform [as 别名]
# 或者: from skimage.transform import resize [as 别名]
def PreprocessImage(path, show_img=False):
    # load image
    img = io.imread(path)
    print("Original Image Shape: ", img.shape)
    # we crop image from center
    short_egde = min(img.shape[:2])
    yy = int((img.shape[0] - short_egde) / 2)
    xx = int((img.shape[1] - short_egde) / 2)
    crop_img = img[yy : yy + short_egde, xx : xx + short_egde]
    # resize to 224, 224
    resized_img = transform.resize(crop_img, (224, 224))
    # convert to numpy.ndarray
    sample = np.asarray(resized_img) * 255
    # swap axes to make image from (224, 224, 3) to (3, 224, 224)
    sample = np.swapaxes(sample, 0, 2)
    sample = np.swapaxes(sample, 1, 2)

    # sub mean
    return sample

# Get preprocessed batch (single image batch) 
开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:23,代码来源:mxnet_predict_example.py

示例3: evaluate_sliding_window

# 需要导入模块: from skimage import transform [as 别名]
# 或者: from skimage.transform import resize [as 别名]
def evaluate_sliding_window(img_filename, crops):
    img = io.imread(img_filename).astype(np.float32)/255
    if img.ndim == 2: # Handle B/W images
        img = np.expand_dims(img, axis=-1)
        img = np.repeat(img, 3, 2)

    img_crops = np.zeros((batch_size, 227, 227, 3))
    for i in xrange(len(crops)):
        crop = crops[i]
        img_crop = transform.resize(img[crop[1]:crop[1]+crop[3],crop[0]:crop[0]+crop[2]], (227, 227))-0.5
        img_crop = np.expand_dims(img_crop, axis=0)
        img_crops[i,:,:,:] = img_crop

    # compute ranking scores
    scores = sess.run([score_func], feed_dict={image_placeholder: img_crops})

    # find the optimal crop
    idx = np.argmax(scores[:len(crops)])
    best_window = crops[idx]

    # return the best crop
    return (best_window[0], best_window[1], best_window[2], best_window[3]) 
开发者ID:yiling-chen,项目名称:view-finding-network,代码行数:24,代码来源:vfn_eval.py

示例4: show_landmarks

# 需要导入模块: from skimage import transform [as 别名]
# 或者: from skimage.transform import resize [as 别名]
def show_landmarks(image, heatmap, gt_landmarks, gt_heatmap):
    """Show image with pred_landmarks"""
    pred_landmarks = []
    pred_landmarks, _ = get_preds_fromhm(torch.from_numpy(heatmap).unsqueeze(0))
    pred_landmarks = pred_landmarks.squeeze()*4

    # pred_landmarks2 = get_preds_fromhm2(heatmap)
    heatmap = np.max(gt_heatmap, axis=0)
    heatmap = heatmap / np.max(heatmap)
    # image = ski_transform.resize(image, (64, 64))*255
    image = image.astype(np.uint8)
    heatmap = np.max(gt_heatmap, axis=0)
    heatmap = ski_transform.resize(heatmap, (image.shape[0], image.shape[1]))
    heatmap *= 255
    heatmap = heatmap.astype(np.uint8)
    heatmap = cv2.applyColorMap(heatmap, cv2.COLORMAP_JET)
    plt.imshow(image)
    plt.scatter(gt_landmarks[:, 0], gt_landmarks[:, 1], s=0.5, marker='.', c='g')
    plt.scatter(pred_landmarks[:, 0], pred_landmarks[:, 1], s=0.5, marker='.', c='r')
    plt.pause(0.001)  # pause a bit so that plots are updated 
开发者ID:protossw512,项目名称:AdaptiveWingLoss,代码行数:22,代码来源:utils.py

示例5: setup_mnist

# 需要导入模块: from skimage import transform [as 别名]
# 或者: from skimage.transform import resize [as 别名]
def setup_mnist(self, img_res):

        print ("Setting up MNIST...")

        if not os.path.exists('datasets/mnist_x.npy'):
            # Load the dataset
            (mnist_X, mnist_y), (_, _) = mnist.load_data()

            # Normalize and rescale images
            mnist_X = self.normalize(mnist_X)
            mnist_X = np.array([imresize(x, img_res) for x in mnist_X])
            mnist_X = np.expand_dims(mnist_X, axis=-1)
            mnist_X = np.repeat(mnist_X, 3, axis=-1)

            self.mnist_X, self.mnist_y = mnist_X, mnist_y

            # Save formatted images
            np.save('datasets/mnist_x.npy', self.mnist_X)
            np.save('datasets/mnist_y.npy', self.mnist_y)
        else:
            self.mnist_X = np.load('datasets/mnist_x.npy')
            self.mnist_y = np.load('datasets/mnist_y.npy')

        print ("+ Done.") 
开发者ID:eriklindernoren,项目名称:Keras-GAN,代码行数:26,代码来源:data_loader.py

示例6: resize_image

# 需要导入模块: from skimage import transform [as 别名]
# 或者: from skimage.transform import resize [as 别名]
def resize_image(image, max_dim):
    """
    缩放图像为正方形,指定长边大小,短边padding;
    :param image: numpy 数组(H,W,3)
    :param max_dim: 长边大小
    :return: 缩放后的图像,元素图像的宽口位置,缩放尺寸,padding
    """
    image_dtype = image.dtype
    h, w = image.shape[:2]
    scale = max_dim / max(h, w)  # 缩放尺寸
    image = transform.resize(image, (round(h * scale), round(w * scale)),
                             order=1, mode='constant', cval=0, clip=True, preserve_range=True)
    h, w = image.shape[:2]
    # 计算padding
    top_pad = (max_dim - h) // 2
    bottom_pad = max_dim - h - top_pad
    left_pad = (max_dim - w) // 2
    right_pad = max_dim - w - left_pad
    padding = [(top_pad, bottom_pad), (left_pad, right_pad), (0, 0)]
    image = np.pad(image, padding, mode='constant', constant_values=0)
    # 原始图像在缩放图像上的窗口位置
    window = (top_pad, left_pad, h + top_pad, w + left_pad)  #
    return image.astype(image_dtype), window, scale, padding 
开发者ID:yizt,项目名称:keras-ctpn,代码行数:25,代码来源:image_utils.py

示例7: get_data_from_id

# 需要导入模块: from skimage import transform [as 别名]
# 或者: from skimage.transform import resize [as 别名]
def get_data_from_id(root, mode, id_):
    """
    Returns:
     - img_downsized: this is the image in 128px res.
     - y_keypts: the keypts in range [0, 1]. To plot
       these, multiply by 128., and overlay these on 
       img_downsized.
     - z_keypts: the z keypoints normalised.
    """
    img = imread("%s/%s_img/%s.jpg" % (root,mode,id_))
    keypts = read_kpt_file("%s/%s_lm/%s_lm.csv" % (root,mode,id_))
    # We want the img + keypts in 128x128px img so preproc them
    # accordingly.
    img_downsized = resize(img, (128,128))
    y_keypts = np.copy(keypts)[:,0:2]
    y_keypts[:,0] = y_keypts[:,0] / float(img.shape[1]) # x's
    y_keypts[:,1] = y_keypts[:,1] / float(img.shape[0]) # y's
    avg_sz = (img.shape[0]+img.shape[1]) / 2.
    z_keypts = keypts[:,2] / avg_sz # what range??
    return img_downsized, y_keypts, z_keypts 
开发者ID:joelmoniz,项目名称:DepthNets,代码行数:22,代码来源:util.py

示例8: resize_image

# 需要导入模块: from skimage import transform [as 别名]
# 或者: from skimage.transform import resize [as 别名]
def resize_image(img, new_size_typle, resize_method):
    try:
        from skimage import img_as_ubyte
        from skimage.transform import resize
    except ImportError:
        logger.error(
            ' scikit-image is not installed. '
            'In order to install all image feature dependencies run '
            'pip install ludwig[image]'
        )
        sys.exit(-1)

    if tuple(img.shape[:2]) != new_size_typle:
        if resize_method == CROP_OR_PAD:
            return crop_or_pad(img, new_size_typle)
        elif resize_method == INTERPOLATE:
            return img_as_ubyte(resize(img, new_size_typle))
        raise ValueError(
            'Invalid image resize method: {}'.format(resize_method))
    return img 
开发者ID:uber,项目名称:ludwig,代码行数:22,代码来源:image_utils.py

示例9: add_heat

# 需要导入模块: from skimage import transform [as 别名]
# 或者: from skimage.transform import resize [as 别名]
def add_heat(image, heat_map, max_v, min_v, alpha=0.4, save=None, cmap='jet', axis='off'):
    height = image.shape[0]
    width = image.shape[1]

    # resize heat map
    heat_map_resized = transform.resize(heat_map, (height, width))

    # normalize heat map
    max_value = max_v
    min_value = min_v
    normalized_heat_map = (heat_map_resized - min_value) / (max_value - min_value)

    # display
    plt.imshow(image)
    plt.imshow(255 * normalized_heat_map, alpha=alpha, cmap=cmap)
    plt.axis(axis)

    if save is not None:
        plt.savefig(save, bbox_inches='tight', pad_inches=0) 
开发者ID:ruinmessi,项目名称:ASFF,代码行数:21,代码来源:vis_utils.py

示例10: add

# 需要导入模块: from skimage import transform [as 别名]
# 或者: from skimage.transform import resize [as 别名]
def add(image, heat_map, alpha=0.6, display=False, save=None, cmap='viridis', axis='on', verbose=False):

    height = image.shape[0]
    width = image.shape[1]

    # resize heat map
    heat_map_resized = transform.resize(heat_map, (height, width))

    # normalize heat map
    max_value = np.max(heat_map_resized)
    min_value = np.min(heat_map_resized)
    normalized_heat_map = (heat_map_resized - min_value) / (max_value - min_value)

    # display
    plt.imshow(image)
    plt.imshow(255 * normalized_heat_map, alpha=alpha, cmap=cmap)
    plt.axis(axis)

    if display:
        plt.show()

    if save is not None:
        if verbose:
            print('save image: ' + save)
        plt.savefig(save, bbox_inches='tight', pad_inches=0) 
开发者ID:durandtibo,项目名称:heatmap,代码行数:27,代码来源:heat_map.py

示例11: work

# 需要导入模块: from skimage import transform [as 别名]
# 或者: from skimage.transform import resize [as 别名]
def work(self, tensor):
        """
            Resize the tensor
            If the tensor is not in the range of [-1, 1], we will do the normalization automatically

            Arg:    tensor  - The np.ndarray object. The tensor you want to deal with
            Ret:    The resized tensor
        """
        # Normalize the tensor if needed
        mean, std = -1, -1
        min_v = np.min(tensor)
        max_v = np.max(tensor)
        if not (max_v <= 1 and min_v >= -1):
            mean = 0.5 * max_v + 0.5 * min_v
            std  = 0.5 * max_v - 0.5 * min_v
            # print(max_v, min_v, mean, std)
            tensor = (tensor - mean) / std

        # Work
        tensor = transform.resize(tensor, self.output_size, mode = 'constant', order = 0)

        # De-normalize the tensor
        if mean != -1 and std != -1:
            tensor = tensor * std + mean
        return tensor 
开发者ID:tomguluson92,项目名称:StyleGAN2_PyTorch,代码行数:27,代码来源:complex.py

示例12: create_dataset

# 需要导入模块: from skimage import transform [as 别名]
# 或者: from skimage.transform import resize [as 别名]
def create_dataset(paths, width_in, height_in, width_out, height_out, data_indexes, mat):
    x = []
    y = []
    for path in tqdm(paths):
        mat = scipy.io.loadmat(path)
        img_tensor = mat['images']
        fluid_tensor = mat['manualFluid1']
        img_array = np.transpose(img_tensor, (2, 0 ,1)) / 255
        img_array = resize(img_array, (img_array.shape[0], width_in, height_in))
        fluid_array = np.transpose(fluid_tensor, (2, 0 ,1))
        fluid_array = thresh(fluid_array)
        fluid_array  = resize(fluid_array, (fluid_array .shape[0], width_out, height_out))

        for idx in data_indexes:
            x += [np.expand_dims(img_array[idx], 0)]
            y += [np.expand_dims(fluid_array[idx], 0)]
    return np.array(x), np.array(y) 
开发者ID:Hsankesara,项目名称:DeepResearch,代码行数:19,代码来源:run_unet.py

示例13: __getitem__

# 需要导入模块: from skimage import transform [as 别名]
# 或者: from skimage.transform import resize [as 别名]
def __getitem__(self, idx):
        image_pos = self.lines.ix[idx, 0]
        image = io.imread(image_pos)
        image = image.astype(np.float)
        h,w = image.shape[:2]
        if(h<w):
            factor = h/350.0
            w = w/factor
            h = 350
        else:
            factor = w/350.0
            h = h/factor
            w = 350
        image = transform.resize(image, (int(h), int(w), 3))
        image_id = self.lines.ix[idx, 1]
        sample = {'image': image, 'id': image_id}
        if self.trans is not None:
            sample = self.trans(sample)
        return sample 
开发者ID:crashmoon,项目名称:Progressive-Generative-Networks,代码行数:21,代码来源:gan_lstm_two.py

示例14: handle_alphabet

# 需要导入模块: from skimage import transform [as 别名]
# 或者: from skimage.transform import resize [as 别名]
def handle_alphabet(folder):
    print('{}...'.format(folder.split('/')[-1]))
    for rotate in [0, 90, 180, 270]:
        # Create new folders for each augmented alphabet
        mkdir(f'{folder}.{rotate}')
        for root, character_folders, _ in os.walk(folder):
            for character_folder in character_folders:
                # For each character folder in an alphabet rotate and resize all of the images and save
                # to the new folder
                handle_characters(folder, root + '/' + character_folder, rotate)
                # return

    # Delete original alphabet
    rmdir(folder)


# Clean up previous extraction 
开发者ID:oscarknagg,项目名称:few-shot,代码行数:19,代码来源:prepare_omniglot.py

示例15: draw_seg

# 需要导入模块: from skimage import transform [as 别名]
# 或者: from skimage.transform import resize [as 别名]
def draw_seg(self, img, seg_gt, segmentation, name):
        """Applies generated segmentation mask to an image"""
        palette = np.load('Extra/palette.npy').tolist()
        img_size = (img.shape[0], img.shape[1])

        segmentation = imresize(segmentation, img_size, order=0, preserve_range=True).astype(int)

        image = Image.fromarray((img * 255).astype('uint8'))
        segmentation_draw = Image.fromarray((segmentation).astype('uint8'), 'P')
        segmentation_draw.putpalette(palette)
        segmentation_draw.save(self.directory + '/%s_segmentation.png' % name, 'PNG')
        image.save(self.directory + '/%s.jpg' % name, 'JPEG')

        if seg_gt:
            seg_gt_draw = Image.fromarray((seg_gt).astype('uint8'), 'P')
            seg_gt_draw.putpalette(palette)
            seg_gt_draw.save(self.directory + '/%s_seg_gt.png' % name, 'PNG') 
开发者ID:dvornikita,项目名称:blitznet,代码行数:19,代码来源:detector.py


注:本文中的skimage.transform.resize方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。