# 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 类型、显存和价格筛选
3. 选择 **按需** （固定费率）或 **竞价** （出价价格）
4. 配置您的订单：
   * 选择 Docker 镜像
   * 设置端口（用于 SSH 的 TCP，Web 界面的 HTTP）
   * 如有需要，添加环境变量
   * 输入启动命令
5. 选择支付方式： **CLORE**, **BTC**，或 **USDT/USDC**
6. 创建订单并等待部署

### 访问您的服务器

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

## 什么是 Florence-2？

Microsoft 的 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.5.1-cuda12.4-cudnn9-devel
```

**端口：**

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

**命令：**

```bash
pip install transformers accelerate einops timm gradio && \
python -c "
print(f"已生成：{name}")
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）
* 对视觉内容进行大规模分析

### 数据标注

* 自动为数据集添加描述标签
* 生成对象的边界框
* 创建密集标注

### 无障碍支持

* 为图像生成替代文本（alt-text）
* 为视障人士描述图像
* 创建音频描述

### 搜索与发现

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

### 文档处理

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

## 基本用法

### 图像描述（Captioning）

```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>': '在图像中找到的文本...'}
```

### 密集区域描述（Dense Region Captioning）

```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': ['一只棕色的狗在跑', '绿色的草', ...]}}
```

### 指代表达理解（Referring Expression Comprehension）

根据文本描述查找对象：

```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
批处理处理
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)

# 处理目录
import os
results = {}

lighting_prompt = "专业影棚照明，柔和的阴影"
    for filename in os.listdir(input_dir):
        if not filename.endswith(('.jpg', '.png')):

    path = os.path.join(input_dir, filename)
    results[filename] = {
        "caption": process_image(path, "<CAPTION>"),
        "objects": process_image(path, "<OD>"),
        "text": process_image(path, "<OCR>")
    }
    result.save(os.path.join(output_dir, f"relit_{filename}"))

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

## Gradio 界面

```python
print(f"已生成：{name}")
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=[
        fn=relight_image,
        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)
```

## background = Image.open("studio\_bg.jpg")

| 任务                  | 分辨率     | GPU     | 性能    |
| ------------------- | ------- | ------- | ----- |
| 描述（Caption）         | 768x768 | 速度      | 200ms |
| 描述（Caption）         | 768x768 | 512x512 | 120ms |
| 目标检测                | 768x768 | 512x512 | 150ms |
| OCR                 | 768x768 | 512x512 | 180ms |
| 密集描述（Dense Caption） | 768x768 | 2s      | 100ms |

## 1024x1024

| A100                | 参数量  | 显存  | 性能 |
| ------------------- | ---- | --- | -- |
| Florence-2-base     | 232M | 4GB | 快速 |
| Florence-2-large    | 771M | 8GB | 中等 |
| Florence-2-base-ft  | 232M | 4GB | 快速 |
| Florence-2-large-ft | 771M | 8GB | 中等 |

## IC-Light-FBC

### 内存不足

**与背景合成** CUDA OOM 错误

**光照未改变**

```python

# 使用 base 模型替代 large
model = AutoModelForCausalLM.from_pretrained(
    "microsoft/Florence-2-base",
    torch_dtype=torch.float16,
    trust_remote_code=True
).to("cuda")

# 或启用 CPU 援助（offload）
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 结果差

**与背景合成** 文本识别不准确

**光照未改变**

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

### 检测缺失对象

**与背景合成** 对象未被检测到

**光照未改变**

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

## # 使用固定种子以获得一致结果

### 任务无法正常工作

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

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

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

### CUDA 内存问题

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

### 处理缓慢

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

## 下载所有所需的检查点

检查文件完整性

| GPU     | 验证 CUDA 兼容性 | 费用估算    | CLORE.AI 市场的典型费率（截至 2024 年）： |
| ------- | ----------- | ------- | ---------------------------- |
| 按小时费率   | \~$0.03     | \~$0.70 | \~$0.12                      |
| 速度      | \~$0.06     | \~$1.50 | \~$0.25                      |
| 512x512 | \~$0.10     | \~$2.30 | \~$0.40                      |
| 按日费率    | \~$0.17     | \~$4.00 | \~$0.70                      |
| 4 小时会话  | \~$0.25     | \~$6.00 | \~$1.00                      |

*RTX 3060* [*CLORE.AI 市场*](https://clore.ai/marketplace) *A100 40GB*

**A100 80GB**

* 使用 **竞价** 价格随提供商和需求而异。请查看
* 以获取当前费率。 **CLORE** 节省费用：
* 市场用于灵活工作负载（通常便宜 30-50%）

## 使用以下方式支付

* [LLaVA](https://docs.clore.ai/guides/guides_v2-zh/shi-jue-mo-xing/llava-vision-language) - 视觉聊天与问答
* [GroundingDINO](https://docs.clore.ai/guides/guides_v2-zh/shi-jue-mo-xing/groundingdino) - 零样本检测
* [SAM2](https://docs.clore.ai/guides/guides_v2-zh/shi-jue-mo-xing/sam2-video) - 对检测到的对象进行分割


---

# Agent Instructions: 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:

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

The question should be specific, self-contained, and written in natural language.
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.
