app.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. # --------------------------------------------------------
  2. # Based on yolov10
  3. # https://github.com/THU-MIG/yolov10/app.py
  4. # --------------------------------------------------------'
  5. import logging
  6. import tempfile
  7. import threading
  8. import cv2
  9. import gradio as gr
  10. import uvicorn
  11. from fastapi import FastAPI
  12. from fastapi import status
  13. from fastapi.exceptions import RequestValidationError
  14. from fastapi.responses import JSONResponse
  15. from pydantic import BaseModel
  16. from ultralytics import YOLO
  17. # 设置日志格式和级别
  18. logging.basicConfig(level=logging.INFO, format='[%(asctime)s] %(levelname)s - %(message)s')
  19. def yolov12_inference(image, video, model_id, image_size, conf_threshold):
  20. model = YOLO(model_id)
  21. if image:
  22. results = model.predict(source=image, imgsz=image_size, conf=conf_threshold)
  23. annotated_image = results[0].plot()
  24. return annotated_image[:, :, ::-1], None
  25. else:
  26. video_path = tempfile.mktemp(suffix=".webm")
  27. with open(video_path, "wb") as f:
  28. with open(video, "rb") as g:
  29. f.write(g.read())
  30. cap = cv2.VideoCapture(video_path)
  31. fps = cap.get(cv2.CAP_PROP_FPS)
  32. frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
  33. frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
  34. output_video_path = tempfile.mktemp(suffix=".webm")
  35. out = cv2.VideoWriter(output_video_path, cv2.VideoWriter_fourcc(*'vp80'), fps, (frame_width, frame_height))
  36. while cap.isOpened():
  37. ret, frame = cap.read()
  38. if not ret:
  39. break
  40. results = model.predict(source=frame, imgsz=image_size, conf=conf_threshold)
  41. annotated_frame = results[0].plot()
  42. out.write(annotated_frame)
  43. cap.release()
  44. out.release()
  45. return None, output_video_path
  46. def yolov12_inference_for_examples(image, model_path, image_size, conf_threshold):
  47. annotated_image, _ = yolov12_inference(image, None, model_path, image_size, conf_threshold)
  48. return annotated_image
  49. def app():
  50. with gr.Blocks():
  51. with gr.Row():
  52. with gr.Column():
  53. image = gr.Image(type="pil", label="Image", visible=True)
  54. video = gr.Video(label="Video", visible=False)
  55. input_type = gr.Radio(
  56. choices=["Image", "Video"],
  57. value="Image",
  58. label="Input Type",
  59. )
  60. model_id = gr.Dropdown(
  61. label="Model",
  62. choices=[
  63. "yolov12n.pt",
  64. "yolov12s.pt",
  65. "yolov12m.pt",
  66. "yolov12l.pt",
  67. "yolov12x.pt",
  68. ],
  69. value="yolov12m.pt",
  70. )
  71. image_size = gr.Slider(
  72. label="Image Size",
  73. minimum=320,
  74. maximum=1280,
  75. step=32,
  76. value=640,
  77. )
  78. conf_threshold = gr.Slider(
  79. label="Confidence Threshold",
  80. minimum=0.0,
  81. maximum=1.0,
  82. step=0.05,
  83. value=0.25,
  84. )
  85. yolov12_infer = gr.Button(value="Detect Objects")
  86. with gr.Column():
  87. output_image = gr.Image(type="numpy", label="Annotated Image", visible=True)
  88. output_video = gr.Video(label="Annotated Video", visible=False)
  89. def update_visibility(input_type):
  90. image = gr.update(visible=True) if input_type == "Image" else gr.update(visible=False)
  91. video = gr.update(visible=False) if input_type == "Image" else gr.update(visible=True)
  92. output_image = gr.update(visible=True) if input_type == "Image" else gr.update(visible=False)
  93. output_video = gr.update(visible=False) if input_type == "Image" else gr.update(visible=True)
  94. return image, video, output_image, output_video
  95. input_type.change(
  96. fn=update_visibility,
  97. inputs=[input_type],
  98. outputs=[image, video, output_image, output_video],
  99. )
  100. def run_inference(image, video, model_id, image_size, conf_threshold, input_type):
  101. if input_type == "Image":
  102. return yolov12_inference(image, None, model_id, image_size, conf_threshold)
  103. else:
  104. return yolov12_inference(None, video, model_id, image_size, conf_threshold)
  105. yolov12_infer.click(
  106. fn=run_inference,
  107. inputs=[image, video, model_id, image_size, conf_threshold, input_type],
  108. outputs=[output_image, output_video],
  109. )
  110. gr.Examples(
  111. examples=[
  112. [
  113. "ultralytics/assets/bus.jpg",
  114. "yolov12s.pt",
  115. 640,
  116. 0.25,
  117. ],
  118. [
  119. "ultralytics/assets/zidane.jpg",
  120. "yolov12x.pt",
  121. 640,
  122. 0.25,
  123. ],
  124. ],
  125. fn=yolov12_inference_for_examples,
  126. inputs=[
  127. image,
  128. model_id,
  129. image_size,
  130. conf_threshold,
  131. ],
  132. outputs=[output_image],
  133. cache_examples='lazy',
  134. )
  135. gradio_app = gr.Blocks()
  136. with gradio_app:
  137. gr.HTML(
  138. """
  139. <h1 style='text-align: center'>
  140. YOLOv12: Attention-Centric Real-Time Object Detectors
  141. </h1>
  142. """)
  143. gr.HTML(
  144. """
  145. <h3 style='text-align: center'>
  146. <a href='https://arxiv.org/abs/2502.12524' target='_blank'>arXiv</a> | <a href='https://github.com/sunsmarterjie/yolov12' target='_blank'>github</a>
  147. </h3>
  148. """)
  149. with gr.Row():
  150. with gr.Column():
  151. app()
  152. def start_gradio():
  153. gradio_app.launch(server_name="0.0.0.0", server_port=7860)
  154. # FastAPI部分
  155. app_fastapi = FastAPI()
  156. class TrainParams(BaseModel):
  157. """
  158. 用于接收/yolov12/train接口的训练参数,所有参数均需前端传入。
  159. """
  160. model: str # 训练底模
  161. data: str # 数据集配置文件路径
  162. epochs: int # 训练轮数
  163. batch: int # 批次大小
  164. imgsz: int # 输入图片尺寸
  165. scale: float # 随机缩放增强比例
  166. mosaic: float # mosaic数据增强概率
  167. mixup: float # mixup数据增强概率
  168. copy_paste: float # copy-paste数据增强概率
  169. device: str # 训练设备
  170. project: str # 工程名
  171. name: str # 实验名
  172. exist_ok: bool # 是否允许覆盖同名目录
  173. @app_fastapi.post("/yolov12/train")
  174. def yolov12_train(params: TrainParams):
  175. """
  176. RESTful POST接口:/yolov12/train
  177. 接收训练参数,调用YOLO模型训练,并返回训练结果。
  178. 返回格式:{"code": 0/1, "msg": "success/错误原因", "result": 训练结果或None}
  179. """
  180. logging.info("收到/yolov12/train训练请求")
  181. logging.info(f"请求参数: {params}")
  182. try:
  183. # 根据params.model动态确定配置文件
  184. if params.model.endswith('.pt'):
  185. # 如果是.pt文件,将后缀替换为.yaml
  186. config_file = params.model.replace('.pt', '.yaml')
  187. else:
  188. # 如果不是.pt文件,使用默认配置
  189. config_file = "yolov12.yaml"
  190. model = YOLO(config_file)
  191. model.load(params.model)
  192. logging.info("开始模型训练...")
  193. results = model.train(
  194. data=params.data,
  195. epochs=params.epochs,
  196. batch=params.batch,
  197. imgsz=params.imgsz,
  198. scale=params.scale,
  199. mosaic=params.mosaic,
  200. mixup=params.mixup,
  201. copy_paste=params.copy_paste,
  202. device=params.device,
  203. project=params.project,
  204. name=params.name,
  205. exist_ok=params.exist_ok,
  206. )
  207. logging.info("模型训练完成")
  208. # logging.info(f"训练结果: {str(results)}")
  209. return {
  210. "code": 0,
  211. "msg": "success",
  212. "result": str(results.save_dir)
  213. }
  214. except Exception as e:
  215. logging.error(f"训练过程发生异常: {e}")
  216. return {
  217. "code": 1,
  218. "msg": str(e),
  219. "result": None
  220. }
  221. class PredictParams(BaseModel):
  222. """
  223. 用于接收/yolov12/predict接口的预测参数,与YOLO predict方法保持一致。
  224. """
  225. model: str = "yolov12m.pt" # 模型路径
  226. source: str = None # 输入源(图片/视频路径、URL等)
  227. stream: bool = False # 是否流式处理
  228. conf: float = 0.25 # 置信度阈值
  229. iou: float = 0.7 # IoU阈值
  230. max_det: int = 300 # 最大检测数量
  231. imgsz: int = 640 # 输入图片尺寸
  232. batch: int = 1 # 批次大小
  233. device: str = "" # 设备
  234. show: bool = False # 是否显示结果
  235. save: bool = False # 是否保存结果
  236. save_txt: bool = False # 是否保存txt文件
  237. save_conf: bool = False # 是否保存置信度
  238. save_crop: bool = False # 是否保存裁剪图片
  239. show_labels: bool = True # 是否显示标签
  240. show_conf: bool = True # 是否显示置信度
  241. show_boxes: bool = True # 是否显示边界框
  242. line_width: int = None # 线条宽度
  243. vid_stride: int = 1 # 视频帧步长
  244. stream_buffer: bool = False # 流缓冲区
  245. visualize: bool = False # 可视化特征
  246. augment: bool = False # 数据增强
  247. agnostic_nms: bool = False # 类别无关NMS
  248. classes: list = None # 指定类别
  249. retina_masks: bool = False # 高分辨率分割掩码
  250. embed: list = None # 特征向量层
  251. half: bool = False # 半精度
  252. dnn: bool = False # OpenCV DNN
  253. project: str = "" # 项目名
  254. name: str = "" # 实验名
  255. exist_ok: bool = False # 是否覆盖现有目录
  256. verbose: bool = True # 详细输出
  257. @app_fastapi.post("/yolov12/predict")
  258. def yolov12_predict(params: PredictParams):
  259. """
  260. RESTful POST接口:/yolov12/predict
  261. 接收预测参数,调用YOLO模型进行预测,并返回预测结果。
  262. 返回格式:{"code": 0/1, "msg": "success/错误原因", "result": 预测结果或None}
  263. """
  264. logging.info("收到/yolov12/predict预测请求")
  265. logging.info(f"请求参数: {params}")
  266. try:
  267. model = YOLO(params.model)
  268. logging.info("开始模型预测...")
  269. # 构建预测参数
  270. predict_kwargs = {}
  271. for field, value in params.dict().items():
  272. if field not in ['model'] and value is not None:
  273. predict_kwargs[field] = value
  274. results = model.predict(**predict_kwargs)
  275. logging.info("模型预测完成")
  276. logging.info(f"预测结果: {str(results)}")
  277. return {
  278. "code": 0,
  279. "msg": "success",
  280. "result": results[0].save_dir
  281. }
  282. except Exception as e:
  283. logging.error(f"预测过程发生异常: {e}")
  284. return {
  285. "code": 1,
  286. "msg": str(e),
  287. "result": None
  288. }
  289. # 全局异常处理器:参数校验失败时统一返回格式
  290. @app_fastapi.exception_handler(RequestValidationError)
  291. async def validation_exception_handler(request, exc):
  292. err_msg = f"参数校验失败: 路径={request.url.path}, 错误={exc.errors()}"
  293. logging.error(err_msg)
  294. return JSONResponse(
  295. status_code=status.HTTP_200_OK,
  296. content={
  297. "code": 422,
  298. "msg": err_msg,
  299. "result": None
  300. }
  301. )
  302. if __name__ == "__main__":
  303. threading.Thread(target=start_gradio, daemon=True).start()
  304. uvicorn.run(app_fastapi, host="0.0.0.0", port=8000)