AI 图像编辑 API 教程

强大的AI图像编辑能力,实现智能抠图、风格迁移、超分辨率等功能

智能编辑

AI理解编辑意图

局部重绘

精准区域编辑

风格迁移

艺术风格转换

图层处理

背景分离替换

一、基础图像编辑

快速开始

import requests
from PIL import Image
import base64
import io

# 基础图像编辑API
def edit_image(image_path: str, instruction: str):
    """AI图像编辑"""
    url = "https://api.n1n.ai/v1/images/edit"
    
    # 读取并编码图像
    with open(image_path, "rb") as image_file:
        image_base64 = base64.b64encode(image_file.read()).decode()
    
    headers = {
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json"
    }
    
    data = {
        "model": "dall-e-2",
        "image": image_base64,
        "prompt": instruction,  # 编辑指令
        "n": 1,
        "size": "1024x1024"
    }
    
    response = requests.post(url, headers=headers, json=data)
    
    if response.status_code == 200:
        result = response.json()
        return result["data"][0]["url"]
    else:
        raise Exception(f"编辑失败: {response.text}")

# 局部编辑(带mask)
def inpaint_image(image_path: str, mask_path: str, prompt: str):
    """局部区域重绘"""
    with open(image_path, "rb") as img:
        image_base64 = base64.b64encode(img.read()).decode()
    
    with open(mask_path, "rb") as mask:
        mask_base64 = base64.b64encode(mask.read()).decode()
    
    data = {
        "model": "dall-e-2",
        "image": image_base64,
        "mask": mask_base64,
        "prompt": prompt,
        "size": "1024x1024"
    }
    
    response = requests.post(
        "https://api.n1n.ai/v1/images/inpaint",
        headers=headers,
        json=data
    )
    
    return response.json()["data"][0]["url"]

# 图像变体生成
def create_variations(image_path: str, n: int = 3):
    """生成图像变体"""
    with open(image_path, "rb") as img:
        image_base64 = base64.b64encode(img.read()).decode()
    
    data = {
        "model": "dall-e-2",
        "image": image_base64,
        "n": n,
        "size": "1024x1024"
    }
    
    response = requests.post(
        "https://api.n1n.ai/v1/images/variations",
        headers=headers,
        json=data
    )
    
    return [item["url"] for item in response.json()["data"]]

二、高级编辑功能

专业工具集

# 高级图像编辑功能
class ImageEditor:
    def __init__(self, api_key: str):
        self.api_key = api_key
        self.base_url = "https://api.n1n.ai/v1/images"
    
    def smart_remove_object(self, image_url: str, object_description: str):
        """智能移除物体"""
        response = requests.post(
            f"{self.base_url}/remove-object",
            headers=self._get_headers(),
            json={
                "image_url": image_url,
                "object": object_description,
                "fill_method": "content_aware"  # 内容感知填充
            }
        )
        return response.json()
    
    def style_transfer(self, content_image: str, style_reference: str):
        """风格迁移"""
        response = requests.post(
            f"{self.base_url}/style-transfer",
            headers=self._get_headers(),
            json={
                "content_image": content_image,
                "style_image": style_reference,
                "style_strength": 0.8,
                "preserve_color": True
            }
        )
        return response.json()
    
    def enhance_image(self, image_url: str, enhancements: dict):
        """图像增强"""
        response = requests.post(
            f"{self.base_url}/enhance",
            headers=self._get_headers(),
            json={
                "image_url": image_url,
                "enhancements": {
                    "upscale": 4,  # 4x超分辨率
                    "denoise": True,  # 降噪
                    "sharpen": 0.5,  # 锐化
                    "color_correction": "auto",  # 自动色彩校正
                    "hdr": True  # HDR增强
                }
            }
        )
        return response.json()
    
    def background_replacement(self, image_url: str, background_prompt: str):
        """背景替换"""
        response = requests.post(
            f"{self.base_url}/replace-background",
            headers=self._get_headers(),
            json={
                "image_url": image_url,
                "background_prompt": background_prompt,
                "edge_blend": 0.3,  # 边缘混合
                "maintain_lighting": True  # 保持原始光照
            }
        )
        return response.json()
    
    def face_editing(self, image_url: str, edits: dict):
        """面部编辑"""
        response = requests.post(
            f"{self.base_url}/face-edit",
            headers=self._get_headers(),
            json={
                "image_url": image_url,
                "edits": {
                    "age": edits.get("age"),  # 年龄调整
                    "expression": edits.get("expression"),  # 表情
                    "hair_color": edits.get("hair_color"),
                    "makeup": edits.get("makeup"),
                    "beard": edits.get("beard")
                }
            }
        )
        return response.json()

# 批量处理
def batch_edit_images(images: list, operation: str):
    editor = ImageEditor(API_KEY)
    results = []
    
    for image in images:
        if operation == "enhance":
            result = editor.enhance_image(image, {"upscale": 2, "denoise": True})
        elif operation == "remove_bg":
            result = editor.background_replacement(image, "transparent")
        elif operation == "style":
            result = editor.style_transfer(image, style_reference)
        
        results.append(result)
    
    return results

三、编辑功能详解

🎨 创意编辑

  • ✅ 风格迁移:艺术风格转换
  • ✅ 智能填充:移除物体后自动填充
  • ✅ 变体生成:创建多个版本
  • ✅ 色彩调整:智能调色

🔧 技术增强

  • ✅ 超分辨率:4K画质提升
  • ✅ 降噪处理:去除图像噪点
  • ✅ HDR增强:动态范围优化
  • ✅ 锐化处理:细节增强