【2025最新图生图】用Python调用SiliconFlow API生成图片:从提示词到自动保存本地![特殊字符]

先看效果!!!!

一、工具功能一览

1. 输入提示词

  • 提示词:描述目标图片的内容(如“一个中国样貌的美少女手拿着红枣,放在嘴边,坐在白色的沙发上,面色红润,笑容甜美”),但是我上面生成的图不是按照这个提示词生成的,想生成什么样的图片可以发挥自己的想象。

2. 生成目标图片

  • 根据输入信息,生成高质量的目标图片。

3. 保存生成图片

  • 生成图片保存为本地文件,方便后续使用。

二. 运行代码

以下是完整的Python代码,直接复制即可使用:代码里面的模型根据我测试之后我觉得是比较好的模型,可以根据自身需求按照API文档进行替换。注意:代码需要补充自己的API KEY和自己本地的图片地址。

import requests
import base64
import os

# 设置API基本信息
API_URL = "https://api.siliconflow.cn/v1/images/generations"  # API端点
API_KEY = "your_api_key_here"  # 替换为您的SiliconFlow API Key

def encode_image_to_base64(image_path):
    """将本地图片编码为Base64字符串"""
    with open(image_path, "rb") as image_file:
        return base64.b64encode(image_file.read()).decode("utf-8")

def generate_image(prompt, image_base64=None, model="stabilityai/stable-diffusion-xl-base-1.0", seed=None, batch_size=1, guidance_scale=7.5, image_size="1024x1024", num_inference_steps=20, negative_prompt=None):
    """调用API生成图片"""
    headers = {
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json"
    }
    data = {
        "model": model,  # 模型名称
        "prompt": prompt,  # 提示词
        "batch_size": batch_size,  # 输出图片个数
        "guidance_scale": guidance_scale,  # 控制生成图像与提示的匹配程度
        "image_size": image_size,  # 图片尺寸
        "num_inference_steps": num_inference_steps,  # 推理步骤数
        "seed": seed,  # 随机种子
        "image": image_base64,  # 上传的图片(Base64编码)
        "negative_prompt": negative_prompt  # 负向提示词
    }
    # 移除空值字段
    data = {k: v for k, v in data.items() if v is not None}

    response = requests.post(API_URL, headers=headers, json=data)
    if response.status_code == 200:
        return response.json()["images"]
    else:
        raise Exception(f"API调用失败,状态码:{response.status_code}, 错误信息:{response.text}")

def save_image_url(image_url, output_folder, output_filename):
    """保存图片URL到本地文件"""
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)
    output_path = os.path.join(output_folder, output_filename)
    with open(output_path, "w") as file:
        file.write(image_url)
    print(f"图片URL已保存至:{output_path}")

def download_image(image_url_dict, output_folder, output_filename):
    """下载并保存图片到本地"""
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    # 提取 URL 字典中的实际 URL
    image_url = image_url_dict['url'] if isinstance(image_url_dict, dict) else image_url_dict

    output_path = os.path.join(output_folder, output_filename)
    response = requests.get(image_url)
    if response.status_code == 200:
        with open(output_path, "wb") as file:
            file.write(response.content)
        print(f"图片已下载并保存至:{output_path}")
    else:
        raise Exception(f"图片下载失败,状态码:{response.status_code}")

def main():
    # 用户输入
    prompt = input("请输入提示词(描述目标图片):")
    image_path = "输入你自己本地的图片"  # 直接指定本地图片路径
    model = input(
        "请输入模型名称(默认stabilityai/stable-diffusion-xl-base-1.0):") or "stabilityai/stable-diffusion-xl-base-1.0"
    seed = input("请输入随机种子(可选,留空随机生成):")
    seed = int(seed) if seed else None
    batch_size = input("请输入输出图片个数(默认1):") or 1
    batch_size = int(batch_size) if batch_size else 1
    guidance_scale = input("请输入提示匹配程度(默认7.5):") or 7.5
    guidance_scale = float(guidance_scale) if guidance_scale else 7.5
    image_size = input("请输入图片尺寸(默认1024x1024):") or "1024x1024"
    num_inference_steps = input("请输入推理步骤数(默认20):") or 20
    num_inference_steps = int(num_inference_steps) if num_inference_steps else 20
    negative_prompt = input("请输入负向提示词(可选,留空不使用):") or None

    # 将用户提供的图片路径进行编码
    image_base64 = encode_image_to_base64(image_path)

    try:
        # 调用生成图片的函数
        images = generate_image(
            prompt=prompt,
            image_base64=image_base64,
            model=model,
            seed=seed,
            batch_size=batch_size,
            guidance_scale=guidance_scale,
            image_size=image_size,
            num_inference_steps=num_inference_steps,
            negative_prompt=negative_prompt
        )

        # 保存生成的图片
        output_folder = "generated_images"
        for index, image_url_dict in enumerate(images):
            output_filename = f"generated_image_{index + 1}.png"
            download_image(image_url_dict, output_folder, output_filename)

    except Exception as e:
        print(f"发生错误:{e}")

if __name__ == "__main__":
    main()

三、为什么选择这个工具?

1. 先进的技术支持

  • 基于SiliconFlow的API,生成效果精准。

2. 完全开源

  • 代码公开透明,支持个性化修改和扩展。

3. 高效便捷

  • 无需设计技能,输入提示词即可生成目标图片。

4. 多场景应用

  • 广告设计、游戏开发、社交媒体内容创作等。

感谢支持!

### 使用大型语言模型生成物信息物信息学领域,利用大型语言模型(LLM)生成物信息是一个新兴的研究方向。通过跨模态融合技术,能够将文本描述转换成对应的可视化形,从而帮助研究人员更好地理解复杂的数据结构和关系。 #### 因组数据的可视化 对于因组数据分析而言,可以通过训练特定的任务导向型LLM来实现自动化绘功能。例如,在处理单核苷酸多态性(SNP)关联研究时,可以输入一段关于某个疾病易感位点的文字说明,让模型自动生成展示该位点分布情况及其与周围区域相互作用模式的地[^1]。 ```python import matplotlib.pyplot as plt from bio_llm import BioLanguageModel # 假设这是一个用于物信息学的LLM库 def generate_snp_map(description): model = BioLanguageModel() fig, ax = plt.subplots() # 将自然语言描述转化为可视化的SNP地 snp_data = model.generate_image_from_text(description) # 绘制热力表示不同位置的重要性程度 heatmap = ax.imshow(snp_data['heatmap'], cmap='coolwarm') plt.colorbar(heatmap) generate_snp_map("位于染色体7q36.1上的rs987654变异可能影响糖尿病风险") ``` 此代码片段展示了如何于给定的遗传特征描述创建一张反映这些特性之间潜在联系的表。这里使用了一个假设性的`BioLanguageModel`类来进行从文本到像的转换操作。 #### 蛋白质三维结构预测 除了二维平面布局外,还可以尝试构建更加立体直观的表现形式——比如蛋白质分子的空间构象。借助类似于AlphaFold的工作原理并结合强大的预训练础架构,现在有可能仅凭氨酸序列就能得到高精度的折叠形态估计结果[^3]。 ```python from alphafold_lite import predict_structure # 这里假设有简化版API可用 sequence = "MKQHK...VGG" # 输入待解析的目标蛋白的一级结构字符串 predicted_model = predict_structure(sequence) # 显示预测后的蛋白质三维模型 display(predicted_model.visualize()) ``` 上述Python脚本模拟了调用轻量级版本的AlphaFold服务接口完成对未知物种内某条肽链最佳猜想的过程,并最终呈现出其外观形象供观察者参考。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值