File size: 1,286 Bytes
9fb5dd0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import gradio as gr
import torch
import torchvision.transforms as transforms
from PIL import Image
import matplotlib.pyplot as plt

# Load the trained generator model
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
generator_A2B = Generator().to(device)
generator_A2B.load_state_dict(torch.load("generator_A2B.pth", map_location=device))
generator_A2B.eval()

def transform_image(image):
    transform = transforms.Compose([
        transforms.Resize((256, 256)),
        transforms.ToTensor(),
        transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
    ])
    return transform(image).unsqueeze(0).to(device)

def generate(image):
    image = Image.open(image).convert("RGB")
    input_tensor = transform_image(image)
    with torch.no_grad():
        output_tensor = generator_A2B(input_tensor)
    
    output_image = (output_tensor.squeeze(0).permute(1, 2, 0).cpu().numpy() + 1) / 2
    plt.imshow(output_image)
    plt.axis("off")
    plt.show()
    return output_image

# Create Gradio Interface
demo = gr.Interface(
    fn=generate,
    inputs=gr.Image(type="filepath"),
    outputs=gr.Image(),
    title="CycleGAN Image Translation",
    description="Upload an image and get the translated output from the CycleGAN model."
)

demo.launch()