【通义实验室】开源【文本生成图片】大模型

文本生成图片效果

文本为一首古诗:孤帆远影碧空尽,唯见长江天际流。 不同风格生成的图片

模型地址

中文StableDiffusion-通用领域

初始化pipeline

python 复制代码
task = Tasks.text_to_image_synthesis
model_id = 'damo/multi-modal_chinese_stable_diffusion_v1.0'
pipe = pipeline(task=task, model=model_id, torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32)

生成图片

python 复制代码
# 反向提示词
negative_prompt = (
        "blood, gore, violence, murder, kill, dead, corpse, "
        "horrible, frightening, scary, monster, ghost, skeleton, zombie, "
        "sex, nudity, pornography, adult, erotic, mature, "
        "drugs, alcohol, smoking, tobacco, illegal, "
        "dark, night, storm, thunder, lightning, apocalypse, disaster, "
        "gun, knife, sword, bomb, explosion, firearm, "
        "mean, angry, sadistic, hostile, aggressive, bullying, "
        "dangerous, unsafe, hazardous, poison, toxic, pollution"
    )
output = pipe(
        {
            'text': '孤帆远影碧空尽,唯见长江天际流。中国画',
            'num_inference_steps': 120,
            'guidance_scale': 11,
            'negative_prompt': negative_prompt
        }
    )
cv2.imwrite('result1.png', output['output_imgs'][0])
# 输出为opencv numpy格式,转为PIL.Image
img = output['output_imgs'][0]
img = Image.fromarray(img[:,:,::-1])
img.save('result1.png')

封装为http接口的完整代码

python 复制代码
from flask import Flask, request, send_file
import io
import torch
import cv2
from modelscope.pipelines import pipeline
from modelscope.utils.constant import Tasks
from PIL import Image

app = Flask(__name__)

# 初始化pipeline
task = Tasks.text_to_image_synthesis
model_id = 'damo/multi-modal_chinese_stable_diffusion_v1.0'
pipe = pipeline(task=task, model=model_id, torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32)

@app.route('/generate', methods=['POST'])
def generate_image():
    data = request.json
    text = data.get('text', '')
    guidance_scale = data.get('guidance_scale', 9)

    if not text:
        return {'error': 'No text provided'}, 400

    negative_prompt = (
        "blood, gore, violence, murder, kill, dead, corpse, "
        "horrible, frightening, scary, monster, ghost, skeleton, zombie, "
        "sex, nudity, pornography, adult, erotic, mature, "
        "drugs, alcohol, smoking, tobacco, illegal, "
        "dark, night, storm, thunder, lightning, apocalypse, disaster, "
        "gun, knife, sword, bomb, explosion, firearm, "
        "mean, angry, sadistic, hostile, aggressive, bullying, "
        "dangerous, unsafe, hazardous, poison, toxic, pollution"
    )

    output = pipe(
        {
            'text': text,
            'num_inference_steps': 120,
            'guidance_scale': guidance_scale,
            'negative_prompt': negative_prompt
        }
    )

    img = output['output_imgs'][0]
    img = Image.fromarray(img[:, :, ::-1])  # Convert BGR to RGB

    # Save image to bytes
    img_byte_arr = io.BytesIO()
    img.save(img_byte_arr, format='PNG')
    img_byte_arr.seek(0)

    return send_file(img_byte_arr, mimetype='image/png')


if __name__ == '__main__':
    app.run(debug=False, host='0.0.0.0', port=5000)

在python环境下运行代码

第一次运行会下载大模型文件,需要等待一段时间 启动成功会有如下提示

csharp 复制代码
 * Running on all addresses (0.0.0.0)
 * Running on http://127.0.0.1:5000
 * Running on http://10.10.10.132:5000

使用postman测试

源码下载地址

相关推荐
老梁agent4 分钟前
一个工程师的 LLM 理论入门:Transformer、Attention 和 Tokenization(不带公式)
物联网·llm
vanchWanquan4 分钟前
平置革新:RFID 地毯天线重构多行业数字化识别体系
人工智能·安全·重构·制造
m0_380167145 分钟前
加密市场数据API 指南:价格、合约、期权与分析
人工智能·ai·区块链
数据仓库搬砖人6 分钟前
CLI、MCP、Skill:构建 AI Agent 的三层基础设施,你真的分清楚了吗?
人工智能
70asunflower7 分钟前
【Day1-2】部署&运行 Gemma4 大模型 - Datawhale AI学习
人工智能·学习·datawhale·amdev
wuhanzhanhui7 分钟前
智能座舱技术新高地!2026武汉国际智能显示及智能座舱展览会
人工智能·物联网
学Linux的语莫8 分钟前
OpenCV 视频处理入门教程
人工智能·opencv·音视频
砍材农夫10 分钟前
python 如何一次性安装项目所有依赖包(pip和uv)
开发语言·python·pip·uv
yijianace13 分钟前
Python爬虫项目实战:从 BeautifulSoup 到 XPath
爬虫·python·beautifulsoup
王小王-12316 分钟前
基于机器学习的二手汽车交易价格分析与可视化
人工智能·机器学习·二手车价格预测·汽车销量分析·二手车分析·新能源汽车系统·汽车销量分析可视化系统