【PyTorch】生成一张随机噪声图片

【PyTorch】生成一张随机噪声图片_第1张图片

环境

PyTorch安装教程:Windows | Linux | Mac

代码

from torchvision.transforms import ToPILImage
import torch


def random_noise(nc, width, height):
    '''Generator a random noise image from tensor.

    If nc is 1, the Grayscale image will be created.
    If nc is 3, the RGB image will be generated.

    Args:
        nc (int): (1 or 3) number of channels.
        width (int): width of output image.
        height (int): height of output image.
    Returns:
        PIL Image.
    '''
    img = torch.rand(nc, width, height)
    img = ToPILImage()(img)
    return img


if __name__ == '__main__':
    random_noise(3, 256, 256).save('random-noise.jpg')

结果

彩色图 灰度图
【PyTorch】生成一张随机噪声图片_第2张图片 【PyTorch】生成一张随机噪声图片_第3张图片

参考

https://pytorch.org/docs/stable/generated/torch.rand.html#torch-rand
https://pytorch.org/vision/stable/transforms.html#torchvision.transforms.ToPILImage

你可能感兴趣的:(pytorch,pytorch)