mmgeneration cyclegan translation_demo.py 批量转图片

该代码示例展示了如何利用预训练的cycleGAN模型将一组图片转换为梵高艺术风格,并保存转换后的图像。通过指定配置文件和预训练权重,模型读取输入图片并生成梵高风格的图像,然后可以遍历目录批量处理所有.jpg和.png文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

## cycleGAN 常规图片批量转换为梵高domain(或者其他domain)并保存于该文件夹中.


# 导入mmcv和mmgeneration
# import mmcv
from mmgen.apis import init_model, sample_img2img_model
import os
# 导入 opencv
import cv2

# 导入numpy和matplotlib
import numpy as np
import matplotlib.pyplot as plt
# 照片转梵高

# 指定config文件路径
config_file = 'configs/cyclegan/cyclegan_lsgan_resnet_in_facades_b1x1_80k_vangogh2photo.py'

# 指定预训练模型权重文件路径
checkpoint_file = 'work_dirs/experiments/cyclegan_vangogh2photo/ckpt/cyclegan_vangogh2photo/iter_best.pth'
model = init_model(config_file, checkpoint_file)


# 输出图像宽高像素尺寸
img_size = 1024


def gen_vis_fake_img(input_path, model, target_domain='vangogh', figsize=60, save_path=None):
    # 读入输入图像,获取高宽尺寸  folder = 'Picture/'
    # ch_filepath =  '1_'+filepath
    input_img = cv2.imread(input_path)
    # 生成梵高油画图像,注意 target_domain 要设置正确
    fake_imgs = sample_img2img_model(model, input_path, target_domain=target_domain)
    # 获取生成图像尺寸
    img_size = fake_imgs.shape[2]

    # 分别抽取RGB三通道图像,归一化为0-255的uint8自然图像
    RGB = np.zeros((img_size, img_size, 3))
    RGB[:, :, 0] = fake_imgs[0][2]
    RGB[:, :, 1] = fake_imgs[0][1]
    RGB[:, :, 2] = fake_imgs[0][0]
    # 将生成图转为输入图像大小
    RGB = cv2.resize(RGB, dsize=(input_img.shape[1], input_img.shape[0]))
    # 像素值归一化
    RGB = 255 * (RGB - RGB.min()) / (RGB.max() - RGB.min())
    # 像素值转为整数
    RGB = RGB.astype('uint8')

    if save_path:
        # 导出生成的图像文件
        cv2.imwrite(save_path, cv2.cvtColor(RGB, cv2.COLOR_BGR2RGB))

#以上代码 部分借鉴同济子豪兄.



def traverse_dir(path):
    for file in os.listdir(path):
        file_path = os.path.join(path,file)
        if os.path.isfile(file_path):
            if os.path.splitext(file_path)[1] in ['.jpg','.png']:
                out_file_name = os.path.splitext(file_path)\[0]+'_gan'+os.path.splitext(file_path)[1]
                gen_vis_fake_img(file_path, model, target_domain='vangogh', figsize=60, save_path=out_file_name)
        elif os.path.isdir(file_path):
            traverse_dir(file_path)

if __name__ == '__main__':
    path = './data_pic'
    traverse_dir(path)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

duanboboke

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值