赞
踩
下面的代码是一个使用 Python 编写的脚本,用于调用阿里云的 Stable Diffusion 模型(通过 Dashscope 库)来生成图像。这个脚本显示了如何使用 Dashscope 的 API,根据用户提供的提示语句生成图像,并将它们保存到指定的路径。
- from http import HTTPStatus
- from urllib.parse import urlparse, unquote
- from pathlib import Path
- from pathlib import PurePosixPath
- import requests
- import dashscope
-
- # 阿里SD,500张,用完需再申请https://help.aliyun.com/zh/dashscope/developer-reference/getting-started-with-stable-diffusion-models?spm=5176.28197632.0.0.97d87e06OPIVDX&disableWebsiteRedirect=true
-
- dashscope.api_key = ''
-
- # model = "dashscope.ImageSynthesis.Models.wanx_v1"
-
- def generate_and_save_images(prompt, n, size, save_path):
- rsp = dashscope.ImageSynthesis.call(model=dashscope.ImageSynthesis.Models.wanx_v1,
- prompt=prompt,
- n=n,
- size=size)
- if rsp.status_code == HTTPStatus.OK:
- print(rsp.output)
- print(rsp.usage)
- for result in rsp.output.results:
- file_name = PurePosixPath(unquote(urlparse(result.url).path)).parts[-1]
- save_file_path = Path(save_path) / file_name
- with open(save_file_path, 'wb+') as f:
- f.write(requests.get(result.url).content)
- else:
- print('Failed, status_code: %s, code: %s, message: %s' %
- (rsp.status_code, rsp.code, rsp.message))
-
- if __name__ == '__main__':
- prompt = "a dog and a cat"
- n = 4
- size = '1024*1024'
- save_path = 'D:\\wenjian\\临时'
- generate_and_save_images(prompt, n, size, save_path)
这个脚本可以广泛应用于需要自动生成图像的场景,如:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。