modelslab-image-generation

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

ModelsLab Image Generation

ModelsLab 图像生成

Generate stunning AI images using ModelsLab's extensive library of models and powerful generation endpoints.
借助ModelsLab丰富的模型库和强大的生成端点,生成令人惊叹的AI图像。

When to Use This Skill

何时使用该技能

  • Generate images from text descriptions
  • Transform or modify existing images
  • Fill in masked parts of images (inpainting)
  • Use ControlNet for precise control
  • Need fast generation (Realtime API)
  • Need highest quality (Community/FLUX models)
  • Create product images, marketing graphics, or artwork
  • 根据文本描述生成图像
  • 转换或修改现有图像
  • 填充图像的遮罩区域(inpainting)
  • 使用ControlNet实现精准控制
  • 需要快速生成图像(Realtime API)
  • 需要最高质量的图像(Community/FLUX模型)
  • 创建产品图片、营销素材或艺术作品

Available APIs

可用API

1. Realtime API (Fastest)

1. Realtime API(最快)

Best for: Speed-critical applications, prototypes, real-time demos
  • Text2Img:
    POST https://modelslab.com/api/v6/realtime/text2img
  • Img2Img:
    POST https://modelslab.com/api/v6/realtime/img2img
  • Response time: < 5 seconds
最佳适用场景:对速度要求高的应用、原型、实时演示
  • Text2Img:
    POST https://modelslab.com/api/v6/realtime/text2img
  • Img2Img:
    POST https://modelslab.com/api/v6/realtime/img2img
  • 响应时间:< 5秒

2. Community Models (Highest Quality)

2. Community Models(最高质量)

Best for: Production outputs, custom models, advanced features
  • Text2Img:
    POST https://modelslab.com/api/v6/images/text2img
  • Img2Img:
    POST https://modelslab.com/api/v6/images/img2img
  • Inpainting:
    POST https://modelslab.com/api/v6/images/inpaint
  • ControlNet:
    POST https://modelslab.com/api/v6/images/controlnet
  • 10,000+ models available
最佳适用场景:生产环境输出、自定义模型、高级功能
  • Text2Img:
    POST https://modelslab.com/api/v6/images/text2img
  • Img2Img:
    POST https://modelslab.com/api/v6/images/img2img
  • 图像修复(Inpainting):
    POST https://modelslab.com/api/v6/images/inpaint
  • ControlNet:
    POST https://modelslab.com/api/v6/images/controlnet
  • 可用模型数量:10000+

3. FLUX API (Premium Quality)

3. FLUX API(顶级质量)

Best for: State-of-the-art results
  • Text2Img:
    POST https://modelslab.com/api/v6/images/flux
  • Best-in-class image quality
最佳适用场景:追求最先进的生成效果
  • Text2Img:
    POST https://modelslab.com/api/v6/images/flux
  • 业内领先的图像质量

Quick Start: Text to Image

快速入门:文本转图像

python
import requests
import time

def generate_image(prompt, api_key, api_type="community"):
    """Generate an image from text.

    Args:
        prompt: Text description of the image
        api_key: Your ModelsLab API key
        api_type: "realtime" (fast) or "community" (quality)
    """
    if api_type == "realtime":
        url = "https://modelslab.com/api/v6/realtime/text2img"
        payload = {
            "key": api_key,
            "prompt": prompt,
            "negative_prompt": "blurry, low quality",
            "width": 512,
            "height": 512,
            "num_inference_steps": 20,
            "guidance_scale": 7.5
        }
    else:  # community
        url = "https://modelslab.com/api/v6/images/text2img"
        payload = {
            "key": api_key,
            "model_id": "midjourney",  # or any model
            "prompt": prompt,
            "negative_prompt": "blurry, low quality, distorted",
            "width": 768,
            "height": 768,
            "samples": 1,
            "num_inference_steps": 30,
            "guidance_scale": 7.5,
            "safety_checker": "yes"
        }

    response = requests.post(url, json=payload)
    data = response.json()

    if data["status"] == "success":
        return data["output"][0]
    elif data["status"] == "processing":
        # Poll for results (community API may be async)
        return poll_result(data["id"], api_key)
    else:
        raise Exception(f"Error: {data.get('message')}")

def poll_result(request_id, api_key, timeout=300):
    """Poll for async generation results."""
    start = time.time()
    while time.time() - start < timeout:
        resp = requests.post(
            f"https://modelslab.com/api/v6/images/fetch/{request_id}",
            json={"key": api_key}
        )
        data = resp.json()

        if data["status"] == "success":
            return data["output"][0]
        elif data["status"] == "failed":
            raise Exception(data.get("message", "Failed"))

        time.sleep(5)
    raise Exception("Timeout")
python
import requests
import time

def generate_image(prompt, api_key, api_type="community"):
    """根据文本生成图像。

    参数:
        prompt: 图像的文本描述
        api_key: 你的ModelsLab API密钥
        api_type: "realtime"(快速)或 "community"(高质量)
    """
    if api_type == "realtime":
        url = "https://modelslab.com/api/v6/realtime/text2img"
        payload = {
            "key": api_key,
            "prompt": prompt,
            "negative_prompt": "blurry, low quality",
            "width": 512,
            "height": 512,
            "num_inference_steps": 20,
            "guidance_scale": 7.5
        }
    else:  # community
        url = "https://modelslab.com/api/v6/images/text2img"
        payload = {
            "key": api_key,
            "model_id": "midjourney",  # 或其他任意模型
            "prompt": prompt,
            "negative_prompt": "blurry, low quality, distorted",
            "width": 768,
            "height": 768,
            "samples": 1,
            "num_inference_steps": 30,
            "guidance_scale": 7.5,
            "safety_checker": "yes"
        }

    response = requests.post(url, json=payload)
    data = response.json()

    if data["status"] == "success":
        return data["output"][0]
    elif data["status"] == "processing":
        # 轮询获取结果(Community API可能为异步)
        return poll_result(data["id"], api_key)
    else:
        raise Exception(f"Error: {data.get('message')}")

def poll_result(request_id, api_key, timeout=300):
    """轮询异步生成的结果。"""
    start = time.time()
    while time.time() - start < timeout:
        resp = requests.post(
            f"https://modelslab.com/api/v6/images/fetch/{request_id}",
            json={"key": api_key}
        )
        data = resp.json()

        if data["status"] == "success":
            return data["output"][0]
        elif data["status"] == "failed":
            raise Exception(data.get("message", "Failed"))

        time.sleep(5)
    raise Exception("Timeout")

Usage

使用示例

image_url = generate_image( "A futuristic cityscape at sunset, cyberpunk style, 8k, highly detailed", "your_api_key", api_type="community" ) print(f"Image: {image_url}")
undefined
image_url = generate_image( "A futuristic cityscape at sunset, cyberpunk style, 8k, highly detailed", "your_api_key", api_type="community" ) print(f"Image: {image_url}")
undefined

Image to Image Transformation

图像转图像转换

python
def transform_image(init_image, prompt, api_key, strength=0.7):
    """Transform an existing image based on a prompt.

    Args:
        init_image: URL of the input image
        prompt: How to transform the image
        strength: 0.0-1.0, higher = more change
    """
    response = requests.post(
        "https://modelslab.com/api/v6/images/img2img",
        json={
            "key": api_key,
            "model_id": "midjourney",
            "prompt": prompt,
            "init_image": init_image,
            "strength": strength,
            "width": 512,
            "height": 512,
            "num_inference_steps": 30,
            "guidance_scale": 7.5
        }
    )

    data = response.json()
    if data["status"] == "success":
        return data["output"][0]
    elif data["status"] == "processing":
        return poll_result(data["id"], api_key)
python
def transform_image(init_image, prompt, api_key, strength=0.7):
    """根据提示转换现有图像。

    参数:
        init_image: 输入图像的URL
        prompt: 图像转换的描述
        strength: 0.0-1.0,值越大变化越明显
    """
    response = requests.post(
        "https://modelslab.com/api/v6/images/img2img",
        json={
            "key": api_key,
            "model_id": "midjourney",
            "prompt": prompt,
            "init_image": init_image,
            "strength": strength,
            "width": 512,
            "height": 512,
            "num_inference_steps": 30,
            "guidance_scale": 7.5
        }
    )

    data = response.json()
    if data["status"] == "success":
        return data["output"][0]
    elif data["status"] == "processing":
        return poll_result(data["id"], api_key)

Transform a photo into a painting

将照片转换为油画风格

result = transform_image( "https://example.com/photo.jpg", "An oil painting in Van Gogh style", "your_api_key", strength=0.8 )
undefined
result = transform_image( "https://example.com/photo.jpg", "An oil painting in Van Gogh style", "your_api_key", strength=0.8 )
undefined

Inpainting (Fill Masked Regions)

图像修复(填充遮罩区域)

python
def inpaint_image(image_url, mask_url, prompt, api_key):
    """Fill in masked parts of an image.

    Args:
        image_url: Original image URL
        mask_url: Mask image URL (white = inpaint, black = keep)
        prompt: What to generate in masked area
    """
    response = requests.post(
        "https://modelslab.com/api/v6/images/inpaint",
        json={
            "key": api_key,
            "model_id": "midjourney",
            "init_image": image_url,
            "mask_image": mask_url,
            "prompt": prompt,
            "negative_prompt": "blurry, low quality",
            "width": 512,
            "height": 512,
            "num_inference_steps": 30
        }
    )

    data = response.json()
    if data["status"] == "success":
        return data["output"][0]
    elif data["status"] == "processing":
        return poll_result(data["id"], api_key)
python
def inpaint_image(image_url, mask_url, prompt, api_key):
    """填充图像的遮罩区域。

    参数:
        image_url: 原始图像的URL
        mask_url: 遮罩图像的URL(白色区域为修复部分,黑色区域保留)
        prompt: 遮罩区域要生成的内容描述
    """
    response = requests.post(
        "https://modelslab.com/api/v6/images/inpaint",
        json={
            "key": api_key,
            "model_id": "midjourney",
            "init_image": image_url,
            "mask_image": mask_url,
            "prompt": prompt,
            "negative_prompt": "blurry, low quality",
            "width": 512,
            "height": 512,
            "num_inference_steps": 30
        }
    )

    data = response.json()
    if data["status"] == "success":
        return data["output"][0]
    elif data["status"] == "processing":
        return poll_result(data["id"], api_key)

Replace object in image

替换图像中的物体

result = inpaint_image( "https://example.com/room.jpg", "https://example.com/mask.jpg", "A modern red sofa", "your_api_key" )
undefined
result = inpaint_image( "https://example.com/room.jpg", "https://example.com/mask.jpg", "A modern red sofa", "your_api_key" )
undefined

ControlNet (Precise Control)

ControlNet(精准控制)

python
def generate_with_controlnet(image_url, prompt, controlnet_type, api_key):
    """Use ControlNet for precise composition control.

    ControlNet Types:
        - canny: Edge detection
        - depth: Depth map
        - pose: Human pose
        - scribble: Sketch-based
        - normal: Surface normals
        - seg: Semantic segmentation
    """
    response = requests.post(
        "https://modelslab.com/api/v6/images/controlnet",
        json={
            "key": api_key,
            "model_id": "midjourney",
            "controlnet_model": controlnet_type,
            "controlnet_type": controlnet_type,
            "init_image": image_url,
            "prompt": prompt,
            "width": 512,
            "height": 512,
            "num_inference_steps": 30
        }
    )

    data = response.json()
    if data["status"] == "success":
        return data["output"][0]
    elif data["status"] == "processing":
        return poll_result(data["id"], api_key)
python
def generate_with_controlnet(image_url, prompt, controlnet_type, api_key):
    """使用ControlNet实现精准构图控制。

    ControlNet类型:
        - canny: 边缘检测
        - depth: 深度图
        - pose: 人体姿态
        - scribble: 基于草图
        - normal: 表面法线
        - seg: 语义分割
    """
    response = requests.post(
        "https://modelslab.com/api/v6/images/controlnet",
        json={
            "key": api_key,
            "model_id": "midjourney",
            "controlnet_model": controlnet_type,
            "controlnet_type": controlnet_type,
            "init_image": image_url,
            "prompt": prompt,
            "width": 512,
            "height": 512,
            "num_inference_steps": 30
        }
    )

    data = response.json()
    if data["status"] == "success":
        return data["output"][0]
    elif data["status"] == "processing":
        return poll_result(data["id"], api_key)

Preserve pose, change style

保留姿态,更改风格

result = generate_with_controlnet( "https://example.com/person.jpg", "A superhero in dynamic pose, comic book style", "pose", "your_api_key" )
undefined
result = generate_with_controlnet( "https://example.com/person.jpg", "A superhero in dynamic pose, comic book style", "pose", "your_api_key" )
undefined

Popular Model IDs

热门模型ID

Photorealistic

写实风格

  • realistic-vision-v13
    - High-quality realistic images
  • deliberate-v2
    - Versatile realistic style
  • absolute-reality-v1.6
    - Ultra-realistic outputs
  • realistic-vision-v13
    - 高质量写实图像
  • deliberate-v2
    - 多用途写实风格
  • absolute-reality-v1.6
    - 超写实输出

Artistic/Stylized

艺术/风格化

  • midjourney
    - MidJourney-style images (most popular)
  • dreamshaper-8
    - Artistic and versatile
  • openjourney
    - Open-source MidJourney alternative
  • midjourney
    - MidJourney风格图像(最受欢迎)
  • dreamshaper-8
    - 艺术感强且用途广泛
  • openjourney
    - 开源MidJourney替代方案

Anime/Illustration

动漫/插画

  • anything-v5
    - Anime style
  • counterfeit-v2.5
    - Anime portraits
  • meinamix
    - High-quality anime art
Browse all models: https://modelslab.com/models
  • anything-v5
    - 动漫风格
  • counterfeit-v2.5
    - 动漫肖像
  • meinamix
    - 高质量动漫艺术作品
浏览全部模型:https://modelslab.com/models

Key Parameters

关键参数

ParameterDescriptionRecommended Values
prompt
Text description of desired imageBe specific and detailed
negative_prompt
What to avoid"blurry, low quality, distorted"
width
/
height
Dimensions (divisible by 8)512, 768, 1024
samples
Number of images1-4
num_inference_steps
Quality (higher = better)20 (fast), 30 (balanced), 50 (quality)
guidance_scale
Prompt adherence7-8 (balanced), 10-15 (strict)
seed
Reproducibility
null
(random) or number
strength
img2img change amount0.3 (subtle), 0.7 (moderate), 0.9 (heavy)
safety_checker
NSFW filter"yes" or "no"
参数描述推荐值
prompt
目标图像的文本描述具体且详细
negative_prompt
要避免的内容"blurry, low quality, distorted"
width
/
height
图像尺寸(需为8的倍数)512, 768, 1024
samples
生成图像数量1-4
num_inference_steps
图像质量(值越高质量越好)20(快速), 30(平衡), 50(高质量)
guidance_scale
对提示词的遵循程度7-8(平衡), 10-15(严格遵循)
seed
结果可复现性
null
(随机)或具体数值
strength
img2img的变化幅度0.3(细微), 0.7(中等), 0.9(大幅)
safety_checker
NSFW内容过滤器"yes" 或 "no"

Best Practices

最佳实践

1. Craft Effective Prompts

1. 撰写有效的提示词

✗ Bad: "a car"
✓ Good: "A red Ferrari sports car, studio lighting, highly detailed, 4k, photorealistic"

Include: Subject, style, lighting, quality descriptors
✗ 差:"a car"
✓ 好:"A red Ferrari sports car, studio lighting, highly detailed, 4k, photorealistic"

包含:主体、风格、光线、质量描述词

2. Use Negative Prompts

2. 使用负面提示词

python
negative_prompt = "blurry, low quality, distorted, deformed, ugly, bad anatomy, extra limbs"
python
negative_prompt = "blurry, low quality, distorted, deformed, ugly, bad anatomy, extra limbs"

3. Choose Right API

3. 选择合适的API

  • Realtime: Demos, prototypes, speed-critical
  • Community: Production, custom styles, quality
  • FLUX: When you need absolute best quality
  • Realtime:演示、原型、对速度要求高的场景
  • Community:生产环境、自定义风格、高质量需求
  • FLUX:需要绝对最佳质量的场景

4. Handle Async Operations

4. 处理异步操作

python
undefined
python
undefined

Always check status and poll if needed

始终检查状态,必要时进行轮询

if data["status"] == "processing": result = poll_result(data["id"], api_key)
undefined
if data["status"] == "processing": result = poll_result(data["id"], api_key)
undefined

5. Use Webhooks for Long Operations

5. 对长时间操作使用Webhooks

python
payload = {
    "key": api_key,
    "prompt": "...",
    "webhook": "https://yourserver.com/webhook",
    "track_id": "unique-identifier"
}
python
payload = {
    "key": api_key,
    "prompt": "...",
    "webhook": "https://yourserver.com/webhook",
    "track_id": "unique-identifier"
}

Common Use Cases

常见使用场景

Product Photography

产品摄影

python
image = generate_image(
    "Professional product photo of wireless headphones, white background, studio lighting, commercial photography",
    api_key,
    negative_prompt="shadows, cluttered background, low quality"
)
python
image = generate_image(
    "Professional product photo of wireless headphones, white background, studio lighting, commercial photography",
    api_key,
    negative_prompt="shadows, cluttered background, low quality"
)

Marketing Graphics

营销素材

python
image = generate_image(
    "Modern tech startup office, collaborative workspace, bright and airy, professional photography, 8k",
    api_key
)
python
image = generate_image(
    "Modern tech startup office, collaborative workspace, bright and airy, professional photography, 8k",
    api_key
)

Artistic Creations

艺术创作

python
image = generate_image(
    "A serene Japanese garden at sunset, cherry blossoms, koi pond, peaceful atmosphere, oil painting style",
    api_key,
    api_type="community"
)
python
image = generate_image(
    "A serene Japanese garden at sunset, cherry blossoms, koi pond, peaceful atmosphere, oil painting style",
    api_key,
    api_type="community"
)

Image Variations (Same Seed)

图像变体(相同Seed)

python
seed = 12345
for i in range(4):
    image = generate_image(
        f"A cozy coffee shop interior, variation {i+1}",
        api_key,
        seed=seed
    )
python
seed = 12345
for i in range(4):
    image = generate_image(
        f"A cozy coffee shop interior, variation {i+1}",
        api_key,
        seed=seed
    )

Error Handling

错误处理

python
try:
    image = generate_image(prompt, api_key)
    print(f"Success: {image}")
except Exception as e:
    print(f"Generation failed: {e}")
    # Log error, retry, or notify user
python
try:
    image = generate_image(prompt, api_key)
    print(f"Success: {image}")
except Exception as e:
    print(f"Generation failed: {e}")
    # 记录错误、重试或通知用户

Resources

资源

Related Skills

相关技能

  • modelslab-image-editing
    - Edit and enhance images
  • modelslab-video-generation
    - Generate videos from images
  • modelslab-webhooks
    - Async operation handling
  • modelslab-sdk-usage
    - Use official SDKs
  • modelslab-image-editing
    - 编辑和增强图像
  • modelslab-video-generation
    - 从图像生成视频
  • modelslab-webhooks
    - 异步操作处理
  • modelslab-sdk-usage
    - 使用官方SDK