本文整理汇总了Python中torchvision.transforms.functional.to_tensor方法的典型用法代码示例。如果您正苦于以下问题:Python functional.to_tensor方法的具体用法?Python functional.to_tensor怎么用?Python functional.to_tensor使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类torchvision.transforms.functional
的用法示例。
在下文中一共展示了functional.to_tensor方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __call__
# 需要导入模块: from torchvision.transforms import functional [as 别名]
# 或者: from torchvision.transforms.functional import to_tensor [as 别名]
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
示例2: process_images
# 需要导入模块: from torchvision.transforms import functional [as 别名]
# 或者: from torchvision.transforms.functional import to_tensor [as 别名]
def process_images(self, clean, mask):
i, j, h, w = RandomResizedCrop.get_params(clean, scale=(0.5, 2.0), ratio=(3. / 4., 4. / 3.))
clean_img = resized_crop(clean, i, j, h, w, size=self.img_size, interpolation=Image.BICUBIC)
mask = resized_crop(mask, i, j, h, w, self.img_size, interpolation=Image.BICUBIC)
# get mask before further image augment
# mask = self.get_mask(raw_img, clean_img)
if self.add_random_masks:
mask = random_masks(mask.copy(), size=self.img_size[0], offset=10)
mask = np.where(np.array(mask) > brightness_difference * 255, np.uint8(255), np.uint8(0))
mask = cv2.dilate(mask, np.ones((10, 10), np.uint8), iterations=1)
mask = np.expand_dims(mask, -1)
mask_t = to_tensor(mask)
# mask_t = (mask_t > brightness_difference).float()
# mask_t, _ = torch.max(mask_t, dim=0, keepdim=True)
binary_mask = (1 - mask_t) # valid positions are 1; holes are 0
binary_mask = binary_mask.expand(3, -1, -1)
clean_img = self.transformer(clean_img)
corrupted_img = clean_img * binary_mask
return corrupted_img, binary_mask, clean_img
示例3: resize_pad_tensor
# 需要导入模块: from torchvision.transforms import functional [as 别名]
# 或者: from torchvision.transforms.functional import to_tensor [as 别名]
def resize_pad_tensor(self, pil_img):
origin = to_tensor(pil_img).unsqueeze(0)
fix_len = self.resize
long = max(pil_img.size)
ratio = fix_len / long
new_size = tuple(map(lambda x: int(x * ratio) // 8 * 8, pil_img.size))
img = pil_img.resize(new_size, Image.BICUBIC)
# img = pil_img
img = self.transformer(img).unsqueeze(0)
_, _, h, w = img.size()
if fix_len > w:
boarder_pad = (0, fix_len - w, 0, 0)
else:
boarder_pad = (0, 0, 0, fix_len - h)
img = pad(img, boarder_pad, value=0)
mask_resizer = self.resize_mask(boarder_pad, pil_img.size)
return img, origin, mask_resizer
示例4: __getitem__
# 需要导入模块: from torchvision.transforms import functional [as 别名]
# 或者: from torchvision.transforms.functional import to_tensor [as 别名]
def __getitem__(self, index):
"""Retrieves image from folder and corrupts it."""
# Load PIL image
img_path = os.path.join(self.root_dir, self.imgs[index])
img = Image.open(img_path).convert('RGB')
# Random square crop
if self.crop_size != 0:
img = self._random_crop([img])[0]
# Corrupt source image
tmp = self._corrupt(img)
source = tvF.to_tensor(self._corrupt(img))
# Corrupt target image, but not when clean targets are requested
if self.clean_targets:
target = tvF.to_tensor(img)
else:
target = tvF.to_tensor(self._corrupt(img))
return source, target
示例5: __call__
# 需要导入模块: from torchvision.transforms import functional [as 别名]
# 或者: from torchvision.transforms.functional import to_tensor [as 别名]
def __call__(self, sample):
rdict = {}
input_data = sample['input']
if isinstance(input_data, list):
ret_input = [F.to_tensor(item)
for item in input_data]
else:
ret_input = F.to_tensor(input_data)
rdict['input'] = ret_input
if self.labeled:
gt_data = sample['gt']
if gt_data is not None:
if isinstance(gt_data, list):
ret_gt = [F.to_tensor(item)
for item in gt_data]
else:
ret_gt = F.to_tensor(gt_data)
rdict['gt'] = ret_gt
sample.update(rdict)
return sample
示例6: __getitem__
# 需要导入模块: from torchvision.transforms import functional [as 别名]
# 或者: from torchvision.transforms.functional import to_tensor [as 别名]
def __getitem__(self, index):
# get downscaled, cropped and gt (if available) image
hr_image = Image.open(self.hr_files[index])
w, h = hr_image.size
cs = utils.calculate_valid_crop_size(min(w, h), self.upscale_factor)
if self.crop_size is not None:
cs = min(cs, self.crop_size)
cropped_image = TF.to_tensor(T.CenterCrop(cs // self.upscale_factor)(hr_image))
hr_image = T.CenterCrop(cs)(hr_image)
hr_image = TF.to_tensor(hr_image)
resized_image = utils.imresize(hr_image, 1.0 / self.upscale_factor, True)
if self.lr_files is None:
return resized_image, cropped_image, resized_image
else:
lr_image = Image.open(self.lr_files[index])
lr_image = TF.to_tensor(T.CenterCrop(cs // self.upscale_factor)(lr_image))
return resized_image, cropped_image, lr_image
示例7: cv_transform
# 需要导入模块: from torchvision.transforms import functional [as 别名]
# 或者: from torchvision.transforms.functional import to_tensor [as 别名]
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)
示例8: pil_transform
# 需要导入模块: from torchvision.transforms import functional [as 别名]
# 或者: from torchvision.transforms.functional import to_tensor [as 别名]
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)
示例9: __call__
# 需要导入模块: from torchvision.transforms import functional [as 别名]
# 或者: from torchvision.transforms.functional import to_tensor [as 别名]
def __call__(self, img_z, img_x, bndbox_z, bndbox_x):
crop_z = self._crop(img_z, bndbox_z, self.exemplar_sz)
crop_x = self._crop(img_x, bndbox_x, self.search_sz)
labels, weights = self._create_labels()
crop_z = self._acquire_augment(
crop_z, self.exemplar_sz, self.stats.rgb_variance_z)
crop_x = self._acquire_augment(
crop_x, self.search_sz, self.stats.rgb_variance_x)
crop_z = (255.0 * F.to_tensor(crop_z)).float()
crop_x = (255.0 * F.to_tensor(crop_x)).float()
labels = torch.from_numpy(labels).float()
weights = torch.from_numpy(weights).float()
return crop_z, crop_x, labels, weights
示例10: load_raw_images
# 需要导入模块: from torchvision.transforms import functional [as 别名]
# 或者: from torchvision.transforms.functional import to_tensor [as 别名]
def load_raw_images(ids, images_path):
r"""
Load images from raw files
:param ids: ids of the images in the data order
:param images_path: path of the raw images
:return: the images, as pytorch tensors
"""
images = []
for count, id in enumerate(ids):
# if count % 10000 == 0:
# print(count)
image_path = images_path + "{:0>7d}".format(int(id)) + ".png"
img = Image.open(image_path).convert('L')
img = tvf.to_tensor(img)
assert img.shape[1] == img.shape[2]
assert img.shape[1] in {64, 128}
images.append(img)
return images
示例11: collate
# 需要导入模块: from torchvision.transforms import functional [as 别名]
# 或者: from torchvision.transforms.functional import to_tensor [as 别名]
def collate(batch):
idxs, images, calibs, objects, grids = zip(*batch)
# Crop images to the same dimensions
minw = min(img.size[0] for img in images)
minh = min(img.size[1] for img in images)
images = [img.crop((0, 0, minw, minh)) for img in images]
# Create a vector of indices
idxs = torch.LongTensor(idxs)
# Stack images and calibration matrices along the batch dimension
images = torch.stack([to_tensor(img) for img in images])
calibs = torch.stack(calibs)
grids = torch.stack(grids)
return idxs, images, calibs, objects, grids
示例12: save_image_batch
# 需要导入模块: from torchvision.transforms import functional [as 别名]
# 或者: from torchvision.transforms.functional import to_tensor [as 别名]
def save_image_batch(idx, image_ids):
imsizes = [4, 8, 16, 32, 64, 128]
impaths = [os.path.join(SOURCE_IMG_DIR, get_impath(image_id))
for image_id in image_ids]
images = []
for impath in impaths:
images.append(plt.imread(impath))
for imsize in imsizes:
to_save = torch.zeros((len(impaths), 3, imsize, imsize),
dtype=torch.float32)
for i, im in enumerate(images):
im = im[:, :, :3]
im = cv2.resize(im, (imsize, imsize),
interpolation=cv2.INTER_AREA)
im = to_tensor(im)
assert im.max() <= 1.0
assert len(im.shape) == 3
assert im.dtype == torch.float32
to_save[i] = im
target_dir = os.path.join(TARGET_IMAGE_DIR, str(imsize))
target_path = os.path.join(target_dir, "{}.torch".format(str(idx)))
os.makedirs(target_dir, exist_ok=True)
torch.save(to_save, target_path)
del to_save
示例13: __getitem__
# 需要导入模块: from torchvision.transforms import functional [as 别名]
# 或者: from torchvision.transforms.functional import to_tensor [as 别名]
def __getitem__(self, index):
filename = self.filenames[index]
img_in = Image.open(self.input_dir / filename).convert('RGB')
img_in_lr = img_in.resize(self.input_size, Image.BICUBIC)
img_in_up = img_in_lr.resize(self.output_size, Image.BICUBIC)
img_ref = Image.open(self.ref_dir / filename).convert('RGB')
img_ref = img_ref.resize(self.output_size, Image.BICUBIC)
img_ref_lr = img_ref.resize(self.input_size, Image.BICUBIC)
img_ref_up = img_ref_lr.resize(self.output_size, Image.BICUBIC)
return {'img_in': TF.to_tensor(img_in_up),
'img_ref': TF.to_tensor(img_ref),
'img_ref_blur': TF.to_tensor(img_ref_up),
'filename': Path(filename).stem}
示例14: __call__
# 需要导入模块: from torchvision.transforms import functional [as 别名]
# 或者: from torchvision.transforms.functional import to_tensor [as 别名]
def __call__(self, image, target):
return F.to_tensor(image), target
示例15: __call__
# 需要导入模块: from torchvision.transforms import functional [as 别名]
# 或者: from torchvision.transforms.functional import to_tensor [as 别名]
def __call__(self, image, mask):
# transforming to PIL image
image, mask = F.to_pil_image(image), F.to_pil_image(mask)
# random crop
if self.crop:
i, j, h, w = T.RandomCrop.get_params(image, self.crop)
image, mask = F.crop(image, i, j, h, w), F.crop(mask, i, j, h, w)
if np.random.rand() < self.p_flip:
image, mask = F.hflip(image), F.hflip(mask)
# color transforms || ONLY ON IMAGE
if self.color_jitter_params:
image = self.color_tf(image)
# random affine transform
if np.random.rand() < self.p_random_affine:
affine_params = T.RandomAffine(180).get_params((-90, 90), (1, 1), (2, 2), (-45, 45), self.crop)
image, mask = F.affine(image, *affine_params), F.affine(mask, *affine_params)
# transforming to tensor
image = F.to_tensor(image)
if not self.long_mask:
mask = F.to_tensor(mask)
else:
mask = to_long_tensor(mask)
return image, mask