发布时间:2026/7/14 0:02:17
Florence-2 多视觉任务实战检测、描述、OCR、区域理解与分割提示这篇教程根据我复现 Florence-2 多任务推理流程时整理集中演示同一个模型在目标检测、图像描述、短语定位、开放词汇检测、OCR 和区域理解任务上的用法。Florence-2 的价值在于统一任务接口。只要切换任务 token 和输入文本就可以覆盖多个视觉理解任务适合作为视觉大模型能力测试模板。本文会重点跑通以下流程安装 Florence-2 推理依赖并准备示例图片封装通用推理函数和可视化函数运行图像描述、目标检测和短语定位运行开放词汇检测、密集区域描述和 OCR通过交互框完成区域类别与区域描述任务如果你正在系统学习目标检测、实例分割、OCR、多目标跟踪或视觉大模型建议收藏本文配套 notebook、示例图片和运行环境说明后续会继续整理。如果环境配置卡住可以在评论区说明具体报错。 文章目录Florence-2 多视觉任务实战检测、描述、OCR、区域理解与分割提示⚙️ 环境准备 加载 Florence-2 预训练模型 运行 Florence-2 多任务推理 区域交互输入 区域类别与区域描述 小结 同系列教程汇总⚙️ 环境准备先检查 GPU 运行环境并准备后续训练和推理依赖。建议优先使用 Colab GPU 或本地 NVIDIA GPU 环境。!nvidia-smi!pip install-q transformers timm einops supervision jupyter_bbox_widgetimportos HOMEos.getcwd()print(HOME:,HOME)!mkdir-p{HOME}/data# 请从数据集后台下载示例图片和 OCR 图片并放到 {HOME}/data 目录。# 默认文件名dog.jpeg、dog-2.jpeg、dog-3.jpeg、dog-4.jpeg、license_plate_1.jpg、handwritten-text.jpg 加载 Florence-2 预训练模型加载模型和 processor 后后面的任务都通过任务 token 切换。importtorchfromtransformersimportAutoModelForCausalLM,AutoProcessor# CHECKPOINT microsoft/Florence-2-base-ftCHECKPOINTmicrosoft/Florence-2-large-ftDEVICEtorch.device(cudaiftorch.cuda.is_available()elsecpu)modelAutoModelForCausalLM.from_pretrained(CHECKPOINT,trust_remote_codeTrue,revisionrefs/pr/38).to(DEVICE)processorAutoProcessor.from_pretrained(CHECKPOINT,trust_remote_codeTrue,revisionrefs/pr/38) 运行 Florence-2 多任务推理Florence-2 的不同任务共用一套run_inference入口区别主要是 task 和 text。# title Wrap annotation code into utility functionimportsupervisionassvfromPILimportImagedefannotate_image(image:Image,detections:sv.Detections)-Image:根据 detections 在图像上绘制 mask、检测框和标签。text_scalesv.calculate_optimal_text_scale(resolution_whimage.size)thicknesssv.calculate_optimal_line_thickness(resolution_whimage.size)ifdetections.maskisnotNone:mask_annotatorsv.MaskAnnotator(color_lookupsv.ColorLookup.INDEX)imagemask_annotator.annotate(image,detections)else:box_annotatorsv.BoxAnnotator(color_lookupsv.ColorLookup.INDEX,thicknessthickness)imagebox_annotator.annotate(image,detections)label_annotatorsv.LabelAnnotator(color_lookupsv.ColorLookup.INDEX,text_colorsv.Color.BLACK,text_scaletext_scale,text_thicknessthickness-1,smart_positionTrue)imagelabel_annotator.annotate(image,detections)returnimage# title Example object detection (OB) inferenceimportsupervisionassvfromPILimportImage imageImage.open(f{HOME}/data/dog-3.jpeg)textODtaskODinputsprocessor(texttext,imagesimage,return_tensorspt).to(DEVICE)generated_idsmodel.generate(input_idsinputs[input_ids],pixel_valuesinputs[pixel_values],max_new_tokens1024,num_beams3)generated_textprocessor.batch_decode(generated_ids,skip_special_tokensFalse)[0]resultprocessor.post_process_generation(generated_text,tasktask,image_sizeimage.size)detectionssv.Detections.from_vlm(sv.VLM.FLORENCE_2,resultresult,resolution_whimage.size)imageannotate_image(imageimage,detectionsdetections)image.thumbnail((800,800))image# title Wrap inference code into utility functiondefrun_inference(image:Image,task:str,text:str):prompttasktext inputsprocessor(textprompt,imagesimage,return_tensorspt).to(DEVICE)generated_idsmodel.generate(input_idsinputs[input_ids],pixel_valuesinputs[pixel_values],max_new_tokens1024,num_beams3)generated_textprocessor.batch_decode(generated_ids,skip_special_tokensFalse)[0]returnprocessor.post_process_generation(generated_text,tasktask,image_sizeimage.size)# title Example CAPTION inferenceimportsupervisionassvfromPILimportImage imageImage.open(f{HOME}/data/dog-3.jpeg)taskCAPTIONresponserun_inference(imageimage,tasktask)response# title Example DETAILED_CAPTION inferenceimportsupervisionassvfromPILimportImage imageImage.open(f{HOME}/data/dog-3.jpeg)taskDETAILED_CAPTIONresponserun_inference(imageimage,tasktask)response# title Example MORE_DETAILED_CAPTION inferenceimportsupervisionassvfromPILimportImage imageImage.open(f{HOME}/data/dog-3.jpeg)taskMORE_DETAILED_CAPTIONresponserun_inference(imageimage,tasktask)response# title Example CAPTION_TO_PHRASE_GROUNDING inferenceimportsupervisionassvfromPILimportImage imageImage.open(f{HOME}/data/dog-3.jpeg)taskCAPTION_TO_PHRASE_GROUNDINGtexttailresultrun_inference(imageimage,tasktask,texttext)detectionssv.Detections.from_vlm(sv.VLM.FLORENCE_2,resultresult,resolution_whimage.size)imageannotate_image(imageimage,detectionsdetections)image.thumbnail((800,800))image# title Example DETAILED_CAPTION CAPTION_TO_PHRASE_GROUNDING combo inferenceimportsupervisionassvfromPILimportImage imageImage.open(f{HOME}/data/dog-3.jpeg)taskDETAILED_CAPTIONresponserun_inference(imageimage,tasktask)textresponse[task]taskCAPTION_TO_PHRASE_GROUNDINGresultrun_inference(imageimage,tasktask,texttext)detectionssv.Detections.from_vlm(sv.VLM.FLORENCE_2,resultresult,resolution_whimage.size)imageannotate_image(imageimage,detectionsdetections)image.thumbnail((800,800))print(text)image# title Example OPEN_VOCABULARY_DETECTION inferenceimportsupervisionassvfromPILimportImage imageImage.open(f{HOME}/data/dog-3.jpeg)taskOPEN_VOCABULARY_DETECTIONtextfingerresultrun_inference(imageimage,tasktask,texttext)detectionssv.Detections.from_vlm(sv.VLM.FLORENCE_2,resultresult,resolution_whimage.size)imageannotate_image(imageimage,detectionsdetections)image.thumbnail((800,800))image# title Example DENSE_REGION_CAPTION inferenceimportsupervisionassvfromPILimportImage imageImage.open(f{HOME}/data/dog-3.jpeg)taskDENSE_REGION_CAPTIONresultrun_inference(imageimage,tasktask)detectionssv.Detections.from_vlm(sv.VLM.FLORENCE_2,resultresult,resolution_whimage.size)imageannotate_image(imageimage,detectionsdetections)image.thumbnail((800,800))image# title Example REGION_PROPOSAL inferenceimportsupervisionassvfromPILimportImage imageImage.open(f{HOME}/data/dog-3.jpeg)taskREGION_PROPOSALresultrun_inference(imageimage,tasktask)detectionssv.Detections.from_vlm(sv.VLM.FLORENCE_2,resultresult,resolution_whimage.size)imageannotate_image(imageimage,detectionsdetections)image.thumbnail((800,800))image# title Example OCR_WITH_REGION inferenceimportsupervisionassvfromPILimportImage imageImage.open(f{HOME}/data/license_plate_1.jpg)taskOCR_WITH_REGIONresultrun_inference(imageimage,tasktask)detectionssv.Detections.from_vlm(sv.VLM.FLORENCE_2,resultresult,resolution_whimage.size)imageannotate_image(imageimage,detectionsdetections)image.thumbnail((800,800))imageimportsupervisionassvfromPILimportImage imageImage.open(f{HOME}/data/handwritten-text.jpg)taskOCR_WITH_REGIONresultrun_inference(imageimage,tasktask)detectionssv.Detections.from_vlm(sv.VLM.FLORENCE_2,resultresult,resolution_whimage.size)imageannotate_image(imageimage,detectionsdetections)image.thumbnail((800,800))image# title Example OCR inferenceimportsupervisionassvfromPILimportImage imageImage.open(f{HOME}/data/handwritten-text.jpg)taskOCRresponserun_inference(imageimage,tasktask)response[task]# title Example REFERRING_EXPRESSION_SEGMENTATION inferenceimportsupervisionassvfromPILimportImage imageImage.open(f{HOME}/data/dog-3.jpeg)taskREFERRING_EXPRESSION_SEGMENTATIONtextmanresultrun_inference(imageimage,tasktask,texttext)detectionssv.Detections.from_vlm(sv.VLM.FLORENCE_2,resultresult,resolution_whimage.size)imageannotate_image(imageimage,detectionsdetections)image.thumbnail((800,800))image 区域交互输入区域任务需要先把交互框转换成 Florence-2 使用的loc_*坐标文本。!pip install-q jupyter_bbox_widgetimportbase64defencode_image(filepath):withopen(filepath,rb)asf:image_bytesf.read()encodedstr(base64.b64encode(image_bytes),utf-8)returndata:image/jpg;base64,encodedIS_COLABTrueIMAGE_PATHf{HOME}/data/dog-3.jpegifIS_COLAB:fromgoogle.colabimportoutput output.enable_custom_widget_manager()fromjupyter_bbox_widgetimportBBoxWidget widgetBBoxWidget()widget.imageencode_image(IMAGE_PATH)widgetwidget.bboxesimportnumpyasnp# 如果没有在上方图片中手动画框就使用默认框default_box{x:243,y:733,width:52,height:211,label:}boxwidget.bboxes[0]ifwidget.bboxeselsedefault_box boxnp.array([box[x],box[y],box[x]box[width],box[y]box[height]])imageImage.open(IMAGE_PATH)w,himage.size boxbox/np.array([w,h,w,h])boxbox*1000boxbox.astype(np.int32)boxtext.join([floc_{coordinate}forcoordinateinbox])text 区域类别与区域描述给定区域后模型可以输出类别或区域描述。# title Example REGION_TO_CATEGORY inferenceimportsupervisionassvfromPILimportImage taskREGION_TO_CATEGORYimageImage.open(IMAGE_PATH)resultrun_inference(imageimage,tasktask,texttext)detectionssv.Detections.from_vlm(sv.VLM.FLORENCE_2,resultresult,resolution_whimage.size)imageannotate_image(imageimage,detectionsdetections)image.thumbnail((800,800))image# title Example REGION_TO_DESCRIPTION inferenceimportsupervisionassvfromPILimportImage taskREGION_TO_DESCRIPTIONimageImage.open(IMAGE_PATH)resultrun_inference(imageimage,tasktask,texttext)detectionssv.Detections.from_vlm(sv.VLM.FLORENCE_2,resultresult,resolution_whimage.size)imageannotate_image(imageimage,detectionsdetections)image.thumbnail((800,800))image 小结Florence-2 多任务推理的核心是任务 token。实际使用时可以先封装统一的run_inference再按任务类型把输出解析为文本、检测框、mask 或 OCR 结果。这一类 notebook 建议按“先环境、再数据、再单样例、最后批量推理”的顺序复现。遇到报错时优先检查 GPU、依赖版本、数据集目录和模型权重路径。后续我会继续按源项目顺序整理同系列中的目标检测、实例分割、OCR、多目标跟踪和视觉大模型教程。 同系列教程汇总Google Gemini 3.5 Flash 零样本目标检测教程从提示词到可视化结果GLM-OCR 文档识别实战教程从验证码、公式到车牌 OCRRF-DETR ByteTrack 多目标跟踪实战教程从命令行到 Python 视频轨迹可视化SAM 3 图像分割实战教程文本、框和点提示的多种分割方式Florence-2 多视觉任务实战检测、描述、OCR、区域理解与分割提示-本文