如何在Python中访问或保存gradio_client生成的图像

1 投票
2 回答
43 浏览
提问于 2025-04-14 16:06
from gradio_client import Client
    
client = Client("ByteDance/SDXL-Lightning")
result = client.predict(
        "astronaut riding a horse realistic",   
        "8-Step",   
        api_name="/generate_image"
)
print(result)

这是我的代码,它返回一个字符串形式的路径,所以我对它无能为力:

/tmp/gradio/ecfea853d51fb542f45865d58816480210e58ea3/image.png

我该如何显示这个路径或者保存它呢?

我尝试在客户端参数中设置 download_files = True,但没有看到任何变化。

2 个回答

0

请使用matplotlib和PIL:

image = Image.open(result)
plt.imshow(image)
plt.axis('off')  
plt.show()
image.save("output_image.png")

示例代码:

from gradio_client import Client
from PIL import Image
import matplotlib.pyplot as plt

client = Client("ByteDance/SDXL-Lightning")
result = client.predict(
        "astronaut riding a horse realistic",   
        "8-Step",   
        api_name="/generate_image"
)

image = Image.open(result)
plt.imshow(image)
plt.axis('off')  
plt.show()
image.save("output_image.png")

输出结果:

在这里输入图片描述

0

我觉得如果你使用这个skimage会更简单。

from gradio_client import Client

#Package for image display
from skimage import io

#Package for save the image
import os

client = Client("ByteDance/SDXL-Lightning")
result = client.predict(
        "astronaut riding a horse realistic",   
        "8-Step",   
        api_name="/generate_image"
)

#Move image from temporal place to desired destination
new_path = "./image.png"
os.replace(result, new_path)

#Show the image
img = io.imread(new_path)
io.imshow(img)
io.show()

撰写回答