pytorch如何对image和label同时进行随机翻转
更新时间:2023年09月09日 11:38:29 作者:叫我小二吧
这篇文章主要介绍了pytorch如何对image和label同时进行随机翻转问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
pytorch对image和label同时进行随机翻转
在使用pytorch进行数据增广时碰到一个坑,对image和label分别进行增广,网络训练结果一直很差,查了很久才找到,原来分别image和label进行随机翻转操作时,是不同步的,记录之,防止以后再犯。
所以在对数据进行随机增广操作时,需要指定的参数,
代码如下:
image_path = '/home/org/19.bmp'
label_path = '/home/mask/19.png'
image = Image.open(image_path)
print(image.size)
label = Image.open(label_path)
plt.figure()
plt.subplot(2, 2, 1)
plt.imshow(image)
plt.subplot(2, 2, 2)
plt.imshow(label)
p = np.random.choice([0, 1])#在0,1二者中随机取一个,
print(p)
transform = transforms.Compose([
transforms.RandomHorizontalFlip(p),#指定是否翻转
transforms.ToTensor()
])
img = transform(image)
lab = transform(label)
unloader = transforms.ToPILImage()
img = unloader(img)
lab = unloader(lab)
# print(img.shape)
plt.subplot(2, 2, 3)
plt.imshow(img)
plt.subplot(2, 2, 4)
plt.imshow(lab)
plt.show()结果如下:

pytorch image to tensor
from PIL import Image
import os.path as osp
import os
from torchvision.transforms import ToTensor
test_path = '../dataset/BSD500/images/test'
images_ls = os.listdir(test_path)
images_all_path = []
for image in images_ls:
s_images_path = osp.join(test_path, image)
images_all_path.append(s_images_path)
# print(images_all_path)
image = Image.open(images_all_path[0]).convert('YCbCr')
# image.show()
# print(image)
y, cb, cr = image.split()
print(y)
print(cb)
print(cr)
# y.show()
# cb.show()
image_to_tensor = ToTensor()
y = image_to_tensor(y)
print(y.shape)总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
python列表排序用 sort()和sorted()的区别
这篇文章主要介绍了python列表排序用 sort()和sorted()的区别,主要比较 Python 中用于列表排序的两种函数 sort() 和 sorted(),选择合适的排序函数,下文详细内容需要的小伙伴可以参考一下2022-03-03
Pandas中DataFrame.replace()函数的实现
DataFrame.replace()用于替换DataFrame中的指定值,本文主要介绍了Pandas中DataFrame.replace()函数的实现,具有一定的参考价值,感兴趣的可以了解一下2024-07-07
Pytorch实现List Tensor转Tensor,reshape拼接等操作
这篇文章主要介绍了Pytorch实现List Tensor转Tensor,reshape拼接等操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2022-11-11
Django项目使用ckeditor详解(不使用admin)
今天小编就为大家分享一篇Django项目使用ckeditor详解(不使用admin),具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2019-12-12
Python SQLAlchemy基本操作和常用技巧(包含大量实例,非常好)
这篇文章主要介绍了Python的ORM框架SQLAlchemy基本操作和常用技巧,包含大量实例,非常好的一个学习SQLAlchemy的教程,需要的朋友可以参考下2014-05-05


最新评论