> For the complete documentation index, see [llms.txt](https://docs.clore.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.clore.ai/guides/guides_v2-zh/shi-jue-mo-xing/florence2.md).

# Florence-2

用于图像描述、检测和分割的 Microsoft Florence-2

微软强大的视觉模型，可用于图像描述、检测、分割等任务。

{% hint style="success" %}
所有示例都可以在通过以下方式租用的 GPU 服务器上运行 [CLORE.AI 市场](https://clore.ai/marketplace).
{% endhint %}

{% hint style="info" %}
本指南中的所有示例都可以在通过以下方式租用的 GPU 服务器上运行 [CLORE.AI 市场](https://clore.ai/marketplace) 市场。
{% endhint %}

## 在 CLORE.AI 上租用

1. 访问 [CLORE.AI 市场](https://clore.ai/marketplace)
2. 按 GPU 类型、VRAM 和价格筛选
3. 选择 **按需** （固定费率）或 **竞价** （出价）
4. 配置你的订单：
   * 选择 Docker 镜像
   * 设置端口（SSH 用 TCP，Web UI 用 HTTP）
   * 如有需要，添加环境变量
   * 输入启动命令
5. 选择支付方式： **CLORE**, **BTC**，或 **USDT/USDC**
6. 创建订单并等待部署

### 访问你的服务器

* 在以下位置查找连接信息 **我的订单**
* Web 界面：使用 HTTP 端口 URL
* SSH： `ssh -p <port> root@<proxy-address>`

## 什么是 Florence-2？

微软的 Florence-2 是一个可处理以下任务的视觉基础模型：

* 图像描述（简要和详细）
* 目标检测与定位
* 密集区域描述
* 指代表达理解
* OCR 和文本识别
* 视觉问答

## 资源

* **HuggingFace：** [microsoft/Florence-2-large](https://huggingface.co/microsoft/Florence-2-large)
* **论文：** [Florence-2 论文](https://arxiv.org/abs/2311.06242)
* **GitHub：** [microsoft/Florence-2](https://github.com/microsoft/Florence-2)
* **演示：** [HuggingFace Space](https://huggingface.co/spaces/microsoft/Florence-2)

## 推荐硬件

| 组件  | 最低            | 推荐            | 最佳            |
| --- | ------------- | ------------- | ------------- |
| GPU | RTX 3060 12GB | RTX 4080 16GB | RTX 4090 24GB |
| 显存  | 8GB           | 12GB          | 16GB          |
| CPU | 4 核           | 8 核           | 16 核          |
| 内存  | 16GB          | 32GB          | 64GB          |
| 存储  | 30GB SSD      | 50GB NVMe     | 100GB NVMe    |
| 网络  | 100 Mbps      | 500 Mbps      | 1 Gbps        |

## 在 CLORE.AI 上快速部署

**Docker 镜像：**

```
pytorch/pytorch:2.11.0-cuda12.8-cudnn9-devel
```

**端口：**

```
22/tcp
7860/http
```

**命令：**

```bash
pip install transformers accelerate einops timm gradio && \
python -c "
import gradio as gr
from transformers import AutoProcessor, AutoModelForCausalLM
import torch
from PIL import Image

model = AutoModelForCausalLM.from_pretrained('microsoft/Florence-2-large', torch_dtype=torch.float16, trust_remote_code=True).to('cuda')
processor = AutoProcessor.from_pretrained('microsoft/Florence-2-large', trust_remote_code=True)

def process(image, task):
    inputs = processor(text=task, images=image, return_tensors='pt').to('cuda', torch.float16)
    generated_ids = model.generate(input_ids=inputs['input_ids'], pixel_values=inputs['pixel_values'], max_new_tokens=1024)
    result = processor.batch_decode(generated_ids, skip_special_tokens=False)[0]
    return processor.post_process_generation(result, task=task, image_size=image.size)

gr.Interface(fn=process, inputs=[gr.Image(type='pil'), gr.Dropdown(['<CAPTION>', '<DETAILED_CAPTION>', '<OD>'])], outputs='json').launch(server_name='0.0.0.0')
"
```

## 访问你的服务

部署后，找到你的 `http_pub` URL 在 **我的订单**:

1. 前往 **我的订单** 页面
2. 点击你的订单
3. 找到 `http_pub` URL（例如， `abc123.clorecloud.net`)

使用 `https://YOUR_HTTP_PUB_URL` 替代 `localhost` 在下面的示例中。

## 安装

```bash
pip install transformers accelerate einops timm
pip install flash-attn --no-build-isolation  # 可选，用于更快的推理
```

## 你可以创建什么

### 内容分析

* 自动生成图像描述
* 从图像中提取文本（OCR）
* 大规模分析视觉内容

### 数据标注

* 使用描述自动标注数据集
* 为对象生成边界框
* 创建密集标注

### 无障碍

* 为图像生成替代文本
* 为视障用户描述图像
* 创建音频描述

### 搜索与发现

* 按内容索引图像
* 构建视觉搜索系统
* 内容审核

### 文档处理

* 从文档中提取文本
* 理解图表和示意图
* 处理扫描材料

## 基础用法

### 图像描述

```python
from transformers import AutoProcessor, AutoModelForCausalLM
from PIL import Image
import torch

model = AutoModelForCausalLM.from_pretrained(
    "microsoft/Florence-2-large",
    torch_dtype=torch.float16,
    trust_remote_code=True
).to("cuda")

processor = AutoProcessor.from_pretrained(
    "microsoft/Florence-2-large",
    trust_remote_code=True
)

image = Image.open("photo.jpg")

# 简短描述
task = "<CAPTION>"
inputs = processor(text=task, images=image, return_tensors="pt").to("cuda", torch.float16)
generated_ids = model.generate(
    input_ids=inputs["input_ids"],
    pixel_values=inputs["pixel_values"],
    max_new_tokens=1024
)
result = processor.batch_decode(generated_ids, skip_special_tokens=False)[0]
caption = processor.post_process_generation(result, task=task, image_size=image.size)
print(caption)

# 输出: {'<CAPTION>': '一只狗在公园里玩耍'}

# 详细描述
task = "<DETAILED_CAPTION>"
inputs = processor(text=task, images=image, return_tensors="pt").to("cuda", torch.float16)
generated_ids = model.generate(
    input_ids=inputs["input_ids"],
    pixel_values=inputs["pixel_values"],
    max_new_tokens=1024
)
result = processor.batch_decode(generated_ids, skip_special_tokens=False)[0]
detailed = processor.post_process_generation(result, task=task, image_size=image.size)
print(detailed)
```

### 目标检测

```python
task = "<OD>"  # 目标检测
inputs = processor(text=task, images=image, return_tensors="pt").to("cuda", torch.float16)
generated_ids = model.generate(
    input_ids=inputs["input_ids"],
    pixel_values=inputs["pixel_values"],
    max_new_tokens=1024
)
result = processor.batch_decode(generated_ids, skip_special_tokens=False)[0]
detections = processor.post_process_generation(result, task=task, image_size=image.size)

# 输出: {'<OD>': {'bboxes': [[x1, y1, x2, y2], ...], 'labels': ['dog', 'ball', ...]}}
```

### OCR（文本识别）

```python
task = "<OCR>"
inputs = processor(text=task, images=image, return_tensors="pt").to("cuda", torch.float16)
generated_ids = model.generate(
    input_ids=inputs["input_ids"],
    pixel_values=inputs["pixel_values"],
    max_new_tokens=1024
)
result = processor.batch_decode(generated_ids, skip_special_tokens=False)[0]
text = processor.post_process_generation(result, task=task, image_size=image.size)
print(text)

# 输出: {'<OCR>': '图像中找到的文本...'}
```

### 密集区域描述

```python
task = "<DENSE_REGION_CAPTION>"
inputs = processor(text=task, images=image, return_tensors="pt").to("cuda", torch.float16)
generated_ids = model.generate(
    input_ids=inputs["input_ids"],
    pixel_values=inputs["pixel_values"],
    max_new_tokens=1024
)
result = processor.batch_decode(generated_ids, skip_special_tokens=False)[0]
regions = processor.post_process_generation(result, task=task, image_size=image.size)

# 输出: {'<DENSE_REGION_CAPTION>': {'bboxes': [...], 'labels': ['一只奔跑的棕色狗', '绿色草地', ...]}}
```

### 指代表达理解

根据文本描述查找对象：

```python
task = "<CAPTION_TO_PHRASE_GROUNDING>"
text_input = "左边的红色汽车"

inputs = processor(
    text=task + text_input,
    images=image,
    return_tensors="pt"
).to("cuda", torch.float16)

generated_ids = model.generate(
    input_ids=inputs["input_ids"],
    pixel_values=inputs["pixel_values"],
    max_new_tokens=1024
)
result = processor.batch_decode(generated_ids, skip_special_tokens=False)[0]
grounding = processor.post_process_generation(result, task=task, image_size=image.size)

# 返回“左边的红色汽车”的边界框
```

## 所有可用任务

```python
TASKS = [
    "<CAPTION>",                    # 简短描述
    "<DETAILED_CAPTION>",           # 详细描述
    "<MORE_DETAILED_CAPTION>",      # 非常详细的描述
    "<OD>",                          # 目标检测
    "<DENSE_REGION_CAPTION>",       # 区域描述
    "<REGION_PROPOSAL>",            # 提议感兴趣区域
    "<CAPTION_TO_PHRASE_GROUNDING>", # 从文本中查找对象
    "<REFERRING_EXPRESSION_SEGMENTATION>", # 根据文本进行分割
    "<REGION_TO_SEGMENTATION>",     # 分割指定区域
    "<OPEN_VOCABULARY_DETECTION>",  # 使用文本标签进行检测
    "<REGION_TO_CATEGORY>",         # 对区域分类
    "<REGION_TO_DESCRIPTION>",      # 描述区域
    "<OCR>",                         # 提取文本
    "<OCR_WITH_REGION>",            # 提取带位置的文本
]
```

## 批量处理

```python
import os
from transformers import AutoProcessor, AutoModelForCausalLM
from PIL import Image
import torch
import json

model = AutoModelForCausalLM.from_pretrained(
    "microsoft/Florence-2-large",
    torch_dtype=torch.float16,
    trust_remote_code=True
).to("cuda")
processor = AutoProcessor.from_pretrained("microsoft/Florence-2-large", trust_remote_code=True)

def process_image(image_path, task):
    image = Image.open(image_path)
    inputs = processor(text=task, images=image, return_tensors="pt").to("cuda", torch.float16)
    generated_ids = model.generate(
        input_ids=inputs["input_ids"],
        pixel_values=inputs["pixel_values"],
        max_new_tokens=1024
    )
    result = processor.batch_decode(generated_ids, skip_special_tokens=False)[0]
    return processor.post_process_generation(result, task=task, image_size=image.size)

# 处理目录
input_dir = "./images"
results = {}

for filename in os.listdir(input_dir):
    if not filename.endswith(('.jpg', '.png')):
        continue

    path = os.path.join(input_dir, filename)
    results[filename] = {
        "caption": process_image(path, "<CAPTION>"),
        "objects": process_image(path, "<OD>"),
        "text": process_image(path, "<OCR>")
    }
    print(f"已处理：{filename}")

with open("results.json", "w") as f:
    json.dump(results, f, indent=2)
```

## Gradio 界面

```python
import gradio as gr
from transformers import AutoProcessor, AutoModelForCausalLM
from PIL import Image, ImageDraw
import torch

model = AutoModelForCausalLM.from_pretrained(
    "microsoft/Florence-2-large",
    torch_dtype=torch.float16,
    trust_remote_code=True
).to("cuda")
processor = AutoProcessor.from_pretrained("microsoft/Florence-2-large", trust_remote_code=True)

def run_task(image, task):
    inputs = processor(text=task, images=image, return_tensors="pt").to("cuda", torch.float16)
    generated_ids = model.generate(
        input_ids=inputs["input_ids"],
        pixel_values=inputs["pixel_values"],
        max_new_tokens=1024
    )
    result = processor.batch_decode(generated_ids, skip_special_tokens=False)[0]
    parsed = processor.post_process_generation(result, task=task, image_size=image.size)

    # 如果是检测任务，则绘制框
    output_image = image.copy()
    if task in ["<OD>", "<DENSE_REGION_CAPTION>"]:

        draw = ImageDraw.Draw(output_image)
        if "bboxes" in parsed.get(task, {}):
            for box, label in zip(parsed[task]["bboxes"], parsed[task]["labels"]):
                draw.rectangle(box, outline="red", width=2)
                draw.text((box[0], box[1]-15), label, fill="red")

    return output_image, str(parsed)

demo = gr.Interface(
    fn=run_task,
    inputs=[
        gr.Image(type="pil", label="输入图像"),
        gr.Dropdown(
            choices=["<CAPTION>", "<DETAILED_CAPTION>", "<OD>", "<DENSE_REGION_CAPTION>", "<OCR>"],
            value="<CAPTION>",
            label="任务"
        )
    ],
    outputs=[
        gr.Image(label="结果"),
        gr.Textbox(label="输出", lines=10)
    ],
    title="Florence-2 视觉 AI",
    description="多任务视觉模型。运行于 CLORE.AI GPU 服务器。"
)

demo.launch(server_name="0.0.0.0", server_port=7860)
```

## 性能

| 任务   | 分辨率     | GPU      | 速度    |
| ---- | ------- | -------- | ----- |
| 图像描述 | 768x768 | RTX 3090 | 200ms |
| 图像描述 | 768x768 | RTX 4090 | 120ms |
| 目标检测 | 768x768 | RTX 4090 | 150ms |
| OCR  | 768x768 | RTX 4090 | 180ms |
| 密集描述 | 768x768 | A100     | 100ms |

## 模型变体

| 模型                  | 参数   | 显存  | 速度 |
| ------------------- | ---- | --- | -- |
| Florence-2-base     | 232M | 4GB | 快  |
| Florence-2-large    | 771M | 8GB | 中等 |
| Florence-2-base-ft  | 232M | 4GB | 快  |
| Florence-2-large-ft | 771M | 8GB | 中等 |

## 常见问题与解决方案

### 内存不足

**问题：** CUDA OOM 错误

**解决方案：**

```python

# 使用基础模型而不是大型模型
model = AutoModelForCausalLM.from_pretrained(
    "microsoft/Florence-2-base",
    torch_dtype=torch.float16,
    trust_remote_code=True
).to("cuda")

# 或启用 CPU 卸载
model = AutoModelForCausalLM.from_pretrained(
    "microsoft/Florence-2-large",
    torch_dtype=torch.float16,
    trust_remote_code=True,
    device_map="auto"
)
```

### 推理缓慢

**问题：** 处理时间过长

**解决方案：**

* 使用 Florence-2-base 以获得更快推理
* 安装 flash-attention 以加速
* 将多张图像批量处理
* 在生产环境中使用 A100 GPU

```bash
pip install flash-attn --no-build-isolation
```

### OCR 结果不佳

**问题：** 文本识别不准确

**解决方案：**

* 确保图像分辨率较高（至少 768 像素）
* 使用 `<OCR_WITH_REGION>` 以获得更好的定位
* 预处理：增强对比度，校正图像倾斜
* 在 OCR 前裁剪到文本区域

### 检测缺失对象

**问题：** 未检测到对象

**解决方案：**

* 使用 `<DENSE_REGION_CAPTION>` 以获得更多区域
* 尝试 `<OPEN_VOCABULARY_DETECTION>` 使用特定标签
* 结合 GroundingDINO 检测特定对象

## 故障排查

### 任务无法运行

* 检查任务名称的确切语法
* 某些任务需要特定的输入格式
* 验证模型版本是否与任务匹配

### 输出格式不符合预期

* 不同任务返回不同格式
* 根据任务类型解析输出
* 查看文档中的任务输出说明

### CUDA 内存问题

* Florence-2-large 需要约 8GB 显存
* 使用 Florence-2-base 以减少内存占用
* 启用梯度检查点

### 处理缓慢

* 尽可能使用批量推理
* 启用 FP16 模式
* 考虑使用 TensorRT 优化

## 成本估算

CLORE.AI 市场常见费率（截至 2024 年）：

| GPU       | 小时费率    | 日费率     | 4 小时会话  |
| --------- | ------- | ------- | ------- |
| RTX 3060  | \~$0.03 | \~$0.70 | \~$0.12 |
| RTX 3090  | \~$0.06 | \~$1.50 | \~$0.25 |
| RTX 4090  | \~$0.10 | \~$2.30 | \~$0.40 |
| A100 40GB | \~$0.17 | \~$4.00 | \~$0.70 |
| A100 80GB | \~$0.25 | \~$6.00 | \~$1.00 |

*价格因提供商和需求而异。请查看* [*CLORE.AI 市场*](https://clore.ai/marketplace) *以获取当前费率。*

**节省费用：**

* 使用 **竞价** 可中断工作市场——约三分之一的服务器将现货价格定得低于按需价格（中位数约优惠 13%），其余则与按需价格持平
* 使用 **CLORE** 代币支付
* 比较不同提供商的价格

## 下一步

* [LLaVA](/guides/guides_v2-zh/shi-jue-mo-xing/llava-vision-language.md) - 视觉对话与问答
* [GroundingDINO](/guides/guides_v2-zh/shi-jue-mo-xing/groundingdino.md) - 零样本检测
* [SAM2](/guides/guides_v2-zh/shi-jue-mo-xing/sam2-video.md) - 分割检测到的对象


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.clore.ai/guides/guides_v2-zh/shi-jue-mo-xing/florence2.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
