Python torchvision.transforms.functional.normalize() Examples

The following are 30 code examples of torchvision.transforms.functional.normalize(). 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 torchvision.transforms.functional , or try the search function .
Example #1
Source File: data_loader_stargan.py    From adversarial-object-removal with MIT License 6 votes vote down vote up
def __getitem__(self, index):
        # Apply transforms to the image.
        image = torch.FloatTensor(self.nc,self.out_img_size, self.out_img_size).fill_(-1.)
        # Get the individual images.
        randbox = random.randrange(len(self.metadata['images'][index]))
        imglabel = np.zeros(10, dtype=np.int)
        boxlabel = np.zeros(10, dtype=np.int)
        for i,bb in enumerate(self.metadata['images'][index]):
            imid = random.randrange(self.num_data)
            bbox = [int(bc*self.out_img_size) for bc in bb]
            img, label = self.dataset[imid]
            scImg = FN.resize(img,(bbox[3],bbox[2]))
            image[:, bbox[1]:bbox[1]+bbox[3], bbox[0]:bbox[0]+bbox[2]] = FN.normalize(FN.to_tensor(scImg), mean=(0.5,)*self.nc, std=(0.5,)*self.nc)
            #imglabel[label] = 1
            if i == randbox:
                outBox = FN.normalize(FN.to_tensor(FN.resize(scImg, (self.bbox_out_size, self.bbox_out_size))), mean=(0.5,)*self.nc, std=(0.5,)*self.nc)
                mask = torch.zeros(1,self.out_img_size,self.out_img_size)
                mask[0,bbox[1]:bbox[1]+bbox[3],bbox[0]:bbox[0]+bbox[2]] = 1.
                outbbox = bbox
                #boxlabel[label]=1

        #return image[[0,0,0],::], torch.FloatTensor([1]), outBox[[0,0,0],::], torch.FloatTensor([1]), mask, torch.IntTensor(outbbox)
        return image, torch.FloatTensor([1]), outBox, torch.FloatTensor([1]), mask, torch.IntTensor(outbbox) 
Example #2
Source File: __init__.py    From FPN.pytorch1.0 with MIT License 6 votes vote down vote up
def base_transform_nimgs(images, size, mean, stds, seq_len=1):
    res_imgs = []
    # print(images.shape)
    for i in range(seq_len):
        # img = Image.fromarray(images[i,:, :, :])
        # img = img.resize((size, size), Image.BILINEAR)
        img = cv2.resize(images[i, :, :, :], (size, size)).astype(np.float32)
        #img = images[i, :, :, :].astype(np.float32)
        # img  = np.asarray(img)
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) / 255.0

        res_imgs += [torch.from_numpy(img).permute(2, 0, 1)]
    # pdb.set_trace()
    # res_imgs = np.asarray(res_imgs)
    return [F.normalize(img_tensor, mean, stds) for img_tensor in res_imgs]
    
    # return res_imgs 
Example #3
Source File: PILTransform.py    From ext_portrait_segmentation with MIT License 6 votes vote down vote up
def __call__(self, rgb_img, label_img=None):

        label1 = label_img
        label2 = label_img
        if self.scale1 != 1:
            w, h = label_img.size
            label1 = label1.resize((w//self.scale1, h//self.scale1), Image.NEAREST)

        if self.scale2 != 1:
            w, h = label_img.size
            label2 = label2.resize((w//self.scale2, h//self.scale2), Image.NEAREST)

        rgb_img = F.to_tensor(rgb_img) # convert to tensor (values between 0 and 1)
        rgb_img = F.normalize(rgb_img, self.mean, self.std) # normalize the tensor
        label1 = torch.LongTensor(np.array(label1).astype(np.int64))
        label2 = torch.LongTensor(np.array(label2).astype(np.int64))


        return rgb_img, label1, label2 
Example #4
Source File: cvfunctional.py    From opencv_transforms_torchvision with MIT License 6 votes vote down vote up
def pil_transform(img):
    # img = functional.resize(img, size=(100, 300))
    # img = functional.to_tensor(img)
    # img = functional.normalize(img, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
    # img = functional.pad(img, padding=(10, 10, 20, 20), fill=(255, 255, 255), padding_mode='constant')
    # img = functional.pad(img, padding=(100, 100, 100, 100), padding_mode='symmetric')
    # img = functional.crop(img, -40, -20, 1000, 1000)
    # img = functional.center_crop(img, (310, 300))
    # img = functional.resized_crop(img, -10.3, -20, 330, 220, (500, 500))
    # img = functional.hflip(img)
    # img = functional.vflip(img)
    # tl, tr, bl, br, center = functional.five_crop(img, 100)
    # img = functional.adjust_brightness(img, 2.1)
    # img = functional.adjust_contrast(img, 1.5)
    # img = functional.adjust_saturation(img, 2.3)
    # img = functional.adjust_hue(img, 0.5)
    # img = functional.adjust_gamma(img, gamma=3, gain=0.1)
    # img = functional.rotate(img, 10, resample=PIL.Image.BILINEAR, expand=True, center=None)
    # img = functional.to_grayscale(img, 3)
    # img = functional.affine(img, 10, (0, 0), 1, 0, resample=PIL.Image.BICUBIC, fillcolor=(255,255,0))

    return functional.to_tensor(img) 
Example #5
Source File: cvfunctional.py    From opencv_transforms_torchvision with MIT License 6 votes vote down vote up
def cv_transform(img):
    # img = resize(img, size=(100, 300))
    # img = to_tensor(img)
    # img = normalize(img, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
    # img = pad(img, padding=(10, 10, 20, 20), fill=(255, 255, 255), padding_mode='constant')
    # img = pad(img, padding=(100, 100, 100, 100), fill=5, padding_mode='symmetric')
    # img = crop(img, -40, -20, 1000, 1000)
    # img = center_crop(img, (310, 300))
    # img = resized_crop(img, -10.3, -20, 330, 220, (500, 500))
    # img = hflip(img)
    # img = vflip(img)
    # tl, tr, bl, br, center = five_crop(img, 100)
    # img = adjust_brightness(img, 2.1)
    # img = adjust_contrast(img, 1.5)
    # img = adjust_saturation(img, 2.3)
    # img = adjust_hue(img, 0.5)
    # img = adjust_gamma(img, gamma=3, gain=0.1)
    # img = rotate(img, 10, resample='BILINEAR', expand=True, center=None)
    # img = to_grayscale(img, 3)
    # img = affine(img, 10, (0, 0), 1, 0, resample='BICUBIC', fillcolor=(255,255,0))
    # img = gaussion_noise(img)
    # img = poisson_noise(img)
    img = salt_and_pepper(img)
    return to_tensor(img) 
Example #6
Source File: cvfunctional.py    From opencv_transforms_torchvision with MIT License 6 votes vote down vote up
def normalize(tensor, mean, std):
    """Normalize a tensor image with mean and standard deviation.

    See ``Normalize`` for more details.

    Args:
        tensor (Tensor): Tensor image of size (C, H, W) to be normalized.
        mean (sequence): Sequence of means for each channel.
        std (sequence): Sequence of standard deviations for each channely.

    Returns:
        Tensor: Normalized Tensor image.
    """
    if _is_tensor_image(tensor):
        for t, m, s in zip(tensor, mean, std):
            t.sub_(m).div_(s)
        return tensor
    elif _is_numpy_image(tensor):
        return (tensor.astype(np.float32) - 255.0 * np.array(mean))/np.array(std)
    else:
        raise RuntimeError('Undefined type') 
Example #7
Source File: preprocess.py    From obman_train with GNU General Public License v3.0 6 votes vote down vote up
def prepare_input(frame, flip_left_right=False, debug=False):
    # BGR to RGB and flip frame
    input_image = np.flip(frame, axis=2).copy()
    if flip_left_right:
        input_image = np.flip(input_image, axis=1).copy()

    # Concert to shape batch_size=1, rgb, h, w
    input_image = torch.Tensor(input_image.transpose(2, 0, 1))

    # To debug what is actually fed to network
    if debug:
        plt.imshow(input_image.numpy().transpose(1, 2, 0) / 255)
        plt.show()
    input_image = func_transforms.normalize(
        input_image / 255, [0.5, 0.5, 0.5], [1, 1, 1]
    ).unsqueeze(0)
    # Equivalently
    # input_image_1 = input_image / 255 - 0.5
    input_image = input_image.cuda()
    return input_image 
Example #8
Source File: transforms.py    From U-Net-Fixed-Point-Quantization-for-Medical-Image-Segmentation with MIT License 5 votes vote down vote up
def __call__(self, sample):
        input_data = sample['input']

        mean, std = input_data.mean(), input_data.std()
        input_data = F.normalize(input_data, [mean], [std])

        rdict = {
            'input': input_data,
        }
        sample.update(rdict)
        return sample 
Example #9
Source File: transforms.py    From U-Net-Fixed-Point-Quantization-for-Medical-Image-Segmentation with MIT License 5 votes vote down vote up
def __call__(self, sample):
        input_data = sample['input']

        input_data = F.normalize(input_data, self.mean, self.std)

        rdict = {
            'input': input_data,
        }
        sample.update(rdict)
        return sample 
Example #10
Source File: transforms.py    From U-Net-Fixed-Point-Quantization-for-Medical-Image-Segmentation with MIT License 5 votes vote down vote up
def __call__(self, sample):
        input_data = sample['input']

        mean, std = input_data.mean(), input_data.std()
        input_data = F.normalize(input_data, [mean], [std])

        rdict = {
            'input': input_data,
        }
        sample.update(rdict)
        return sample 
Example #11
Source File: transforms.py    From U-Net-Fixed-Point-Quantization-for-Medical-Image-Segmentation with MIT License 5 votes vote down vote up
def __call__(self, sample):
        input_data = sample['input']

        input_data = F.normalize(input_data, self.mean, self.std)

        rdict = {
            'input': input_data,
        }
        sample.update(rdict)
        return sample 
Example #12
Source File: transforms.py    From U-Net-Fixed-Point-Quantization-for-Medical-Image-Segmentation with MIT License 5 votes vote down vote up
def __call__(self, sample):
        input_data = sample['input']

        input_data = F.normalize(input_data, self.mean, self.std)

        rdict = {
            'input': input_data,
        }
        sample.update(rdict)
        return sample 
Example #13
Source File: transforms.py    From U-Net-Fixed-Point-Quantization-for-Medical-Image-Segmentation with MIT License 5 votes vote down vote up
def __call__(self, sample):
        input_data = sample['input']

        input_data = F.normalize(input_data, self.mean, self.std)

        rdict = {
            'input': input_data,
        }
        sample.update(rdict)
        return sample 
Example #14
Source File: transforms.py    From U-Net-Fixed-Point-Quantization-for-Medical-Image-Segmentation with MIT License 5 votes vote down vote up
def __call__(self, sample):
        input_data = sample['input']

        input_data = F.normalize(input_data, self.mean, self.std)

        rdict = {
            'input': input_data,
        }
        sample.update(rdict)
        return sample 
Example #15
Source File: transforms.py    From U-Net-Fixed-Point-Quantization-for-Medical-Image-Segmentation with MIT License 5 votes vote down vote up
def __call__(self, sample):
        input_data = sample['input']

        mean, std = input_data.mean(), input_data.std()
        input_data = F.normalize(input_data, [mean], [std])

        rdict = {
            'input': input_data,
        }
        sample.update(rdict)
        return sample 
Example #16
Source File: transforms.py    From U-Net-Fixed-Point-Quantization-for-Medical-Image-Segmentation with MIT License 5 votes vote down vote up
def __call__(self, sample):
        input_data = sample['input']

        input_data = F.normalize(input_data, self.mean, self.std)

        rdict = {
            'input': input_data,
        }
        sample.update(rdict)
        return sample 
Example #17
Source File: transforms.py    From U-Net-Fixed-Point-Quantization-for-Medical-Image-Segmentation with MIT License 5 votes vote down vote up
def __call__(self, sample):
        input_data = sample['input']

        mean, std = input_data.mean(), input_data.std()
        input_data = F.normalize(input_data, [mean], [std])

        rdict = {
            'input': input_data,
        }
        sample.update(rdict)
        return sample 
Example #18
Source File: transforms.py    From U-Net-Fixed-Point-Quantization-for-Medical-Image-Segmentation with MIT License 5 votes vote down vote up
def __call__(self, sample):
        input_data = sample['input']

        input_data = F.normalize(input_data, self.mean, self.std)

        rdict = {
            'input': input_data,
        }
        sample.update(rdict)
        return sample 
Example #19
Source File: transforms.py    From U-Net-Fixed-Point-Quantization-for-Medical-Image-Segmentation with MIT License 5 votes vote down vote up
def __call__(self, sample):
        input_data = sample['input']

        mean, std = input_data.mean(), input_data.std()
        input_data = F.normalize(input_data, [mean], [std])

        rdict = {
            'input': input_data,
        }
        sample.update(rdict)
        return sample 
Example #20
Source File: transforms.py    From U-Net-Fixed-Point-Quantization-for-Medical-Image-Segmentation with MIT License 5 votes vote down vote up
def __call__(self, sample):
        input_data = sample['input']

        input_data = F.normalize(input_data, self.mean, self.std)

        rdict = {
            'input': input_data,
        }
        sample.update(rdict)
        return sample 
Example #21
Source File: transforms.py    From U-Net-Fixed-Point-Quantization-for-Medical-Image-Segmentation with MIT License 5 votes vote down vote up
def __call__(self, sample):
        input_data = sample['input']

        mean, std = input_data.mean(), input_data.std()
        input_data = F.normalize(input_data, [mean], [std])

        rdict = {
            'input': input_data,
        }
        sample.update(rdict)
        return sample 
Example #22
Source File: transforms.py    From U-Net-Fixed-Point-Quantization-for-Medical-Image-Segmentation with MIT License 5 votes vote down vote up
def __call__(self, sample):
        input_data = sample['input']

        input_data = F.normalize(input_data, self.mean, self.std)

        rdict = {
            'input': input_data,
        }
        sample.update(rdict)
        return sample 
Example #23
Source File: transforms.py    From training with Apache License 2.0 5 votes vote down vote up
def __call__(self, image, target):
        if self.to_bgr255:
            image = image[[2, 1, 0]] * 255
        image = F.normalize(image, mean=self.mean, std=self.std)
        return image, target 
Example #24
Source File: transforms.py    From pytracking with GNU General Public License v3.0 5 votes vote down vote up
def transform_image(self, image):
        return tvisf.normalize(image, self.mean, self.std, self.inplace) 
Example #25
Source File: transforms.py    From pytracking with GNU General Public License v3.0 5 votes vote down vote up
def transform_image(self, image, brightness_factor):
        # handle numpy array
        image = torch.from_numpy(image.transpose((2, 0, 1)))

        # backward compatibility
        if self.normalize:
            return image.float().mul(brightness_factor/255.0).clamp(0.0, 1.0)
        else:
            return image.float().mul(brightness_factor).clamp(0.0, 255.0) 
Example #26
Source File: transforms.py    From pytracking with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, brightness_jitter=0.0, normalize=True):
        super().__init__()
        self.brightness_jitter = brightness_jitter
        self.normalize = normalize 
Example #27
Source File: video_transforms.py    From pvse with MIT License 5 votes vote down vote up
def __call__(self, tensor):
        """
        Args:
            tensor (Tensor): Tensor image of size (C, H, W) to be normalized.

        Returns:
            Tensor: Normalized Tensor image.
        """
        for i in range(tensor.size(0)):
          F.normalize(tensor[i], self.mean, self.std)
        return tensor 
Example #28
Source File: transforms.py    From retinamask with MIT License 5 votes vote down vote up
def __call__(self, image, target):
        if self.to_bgr255:
            image = image[[2, 1, 0]] * 255
        image = F.normalize(image, mean=self.mean, std=self.std)
        return image, target 
Example #29
Source File: video_transforms.py    From Sound-of-Pixels with MIT License 5 votes vote down vote up
def __call__(self, frames):
        """
        Args:
            frames: a list of Tensor image of size (C, H, W) to be normalized.
        Returns:
            a list of Tensor: a list of normalized Tensor images.
        """
        out_frames = []
        for frame in frames:
            out_frames.append(F.normalize(frame, self.mean, self.std))
        return out_frames 
Example #30
Source File: functional.py    From dsb2018_topcoders with MIT License 5 votes vote down vote up
def img_to_tensor(im, normalize=None):
    tensor = torch.from_numpy(np.moveaxis(im / (255. if im.dtype == np.uint8 else 1), -1, 0).astype(np.float32))
    if normalize is not None:
        return F.normalize(tensor, **normalize)
    return tensor