app.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. # --------------------------------------------------------
  2. # Based on yolov10
  3. # https://github.com/THU-MIG/yolov10/app.py
  4. # --------------------------------------------------------'
  5. import gradio as gr
  6. import cv2
  7. import tempfile
  8. from ultralytics import YOLO
  9. import threading
  10. from fastapi import FastAPI
  11. from pydantic import BaseModel
  12. import uvicorn
  13. import logging
  14. # 设置日志格式和级别
  15. logging.basicConfig(level=logging.INFO, format='[%(asctime)s] %(levelname)s - %(message)s')
  16. def yolov12_inference(image, video, model_id, image_size, conf_threshold):
  17. model = YOLO(model_id)
  18. if image:
  19. results = model.predict(source=image, imgsz=image_size, conf=conf_threshold)
  20. annotated_image = results[0].plot()
  21. return annotated_image[:, :, ::-1], None
  22. else:
  23. video_path = tempfile.mktemp(suffix=".webm")
  24. with open(video_path, "wb") as f:
  25. with open(video, "rb") as g:
  26. f.write(g.read())
  27. cap = cv2.VideoCapture(video_path)
  28. fps = cap.get(cv2.CAP_PROP_FPS)
  29. frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
  30. frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
  31. output_video_path = tempfile.mktemp(suffix=".webm")
  32. out = cv2.VideoWriter(output_video_path, cv2.VideoWriter_fourcc(*'vp80'), fps, (frame_width, frame_height))
  33. while cap.isOpened():
  34. ret, frame = cap.read()
  35. if not ret:
  36. break
  37. results = model.predict(source=frame, imgsz=image_size, conf=conf_threshold)
  38. annotated_frame = results[0].plot()
  39. out.write(annotated_frame)
  40. cap.release()
  41. out.release()
  42. return None, output_video_path
  43. def yolov12_inference_for_examples(image, model_path, image_size, conf_threshold):
  44. annotated_image, _ = yolov12_inference(image, None, model_path, image_size, conf_threshold)
  45. return annotated_image
  46. def app():
  47. with gr.Blocks():
  48. with gr.Row():
  49. with gr.Column():
  50. image = gr.Image(type="pil", label="Image", visible=True)
  51. video = gr.Video(label="Video", visible=False)
  52. input_type = gr.Radio(
  53. choices=["Image", "Video"],
  54. value="Image",
  55. label="Input Type",
  56. )
  57. model_id = gr.Dropdown(
  58. label="Model",
  59. choices=[
  60. "yolov12n.pt",
  61. "yolov12s.pt",
  62. "yolov12m.pt",
  63. "yolov12l.pt",
  64. "yolov12x.pt",
  65. ],
  66. value="yolov12m.pt",
  67. )
  68. image_size = gr.Slider(
  69. label="Image Size",
  70. minimum=320,
  71. maximum=1280,
  72. step=32,
  73. value=640,
  74. )
  75. conf_threshold = gr.Slider(
  76. label="Confidence Threshold",
  77. minimum=0.0,
  78. maximum=1.0,
  79. step=0.05,
  80. value=0.25,
  81. )
  82. yolov12_infer = gr.Button(value="Detect Objects")
  83. with gr.Column():
  84. output_image = gr.Image(type="numpy", label="Annotated Image", visible=True)
  85. output_video = gr.Video(label="Annotated Video", visible=False)
  86. def update_visibility(input_type):
  87. image = gr.update(visible=True) if input_type == "Image" else gr.update(visible=False)
  88. video = gr.update(visible=False) if input_type == "Image" else gr.update(visible=True)
  89. output_image = gr.update(visible=True) if input_type == "Image" else gr.update(visible=False)
  90. output_video = gr.update(visible=False) if input_type == "Image" else gr.update(visible=True)
  91. return image, video, output_image, output_video
  92. input_type.change(
  93. fn=update_visibility,
  94. inputs=[input_type],
  95. outputs=[image, video, output_image, output_video],
  96. )
  97. def run_inference(image, video, model_id, image_size, conf_threshold, input_type):
  98. if input_type == "Image":
  99. return yolov12_inference(image, None, model_id, image_size, conf_threshold)
  100. else:
  101. return yolov12_inference(None, video, model_id, image_size, conf_threshold)
  102. yolov12_infer.click(
  103. fn=run_inference,
  104. inputs=[image, video, model_id, image_size, conf_threshold, input_type],
  105. outputs=[output_image, output_video],
  106. )
  107. gr.Examples(
  108. examples=[
  109. [
  110. "ultralytics/assets/bus.jpg",
  111. "yolov12s.pt",
  112. 640,
  113. 0.25,
  114. ],
  115. [
  116. "ultralytics/assets/zidane.jpg",
  117. "yolov12x.pt",
  118. 640,
  119. 0.25,
  120. ],
  121. ],
  122. fn=yolov12_inference_for_examples,
  123. inputs=[
  124. image,
  125. model_id,
  126. image_size,
  127. conf_threshold,
  128. ],
  129. outputs=[output_image],
  130. cache_examples='lazy',
  131. )
  132. gradio_app = gr.Blocks()
  133. with gradio_app:
  134. gr.HTML(
  135. """
  136. <h1 style='text-align: center'>
  137. YOLOv12: Attention-Centric Real-Time Object Detectors
  138. </h1>
  139. """)
  140. gr.HTML(
  141. """
  142. <h3 style='text-align: center'>
  143. <a href='https://arxiv.org/abs/2502.12524' target='_blank'>arXiv</a> | <a href='https://github.com/sunsmarterjie/yolov12' target='_blank'>github</a>
  144. </h3>
  145. """)
  146. with gr.Row():
  147. with gr.Column():
  148. app()
  149. def start_gradio():
  150. gradio_app.launch(server_name="0.0.0.0", server_port=7860)
  151. # FastAPI部分
  152. app_fastapi = FastAPI()
  153. class TrainParams(BaseModel):
  154. """
  155. 用于接收/yolov12/train接口的训练参数,所有参数均需前端传入。
  156. """
  157. data: str # 数据集配置文件路径
  158. epochs: int # 训练轮数
  159. batch: int # 批次大小
  160. imgsz: int # 输入图片尺寸
  161. scale: float # 随机缩放增强比例
  162. mosaic: float # mosaic数据增强概率
  163. mixup: float # mixup数据增强概率
  164. copy_paste: float # copy-paste数据增强概率
  165. device: str # 训练设备
  166. project: str # 工程名
  167. name: str # 实验名
  168. exist_ok: bool # 是否允许覆盖同名目录
  169. @app_fastapi.post("/yolov12/train")
  170. def yolov12_train(params: TrainParams):
  171. """
  172. RESTful POST接口:/yolov12/train
  173. 接收训练参数,调用YOLO模型训练,并返回训练结果。
  174. 返回格式:{"code": 0/1, "msg": "success/错误原因", "result": 训练结果或None}
  175. """
  176. logging.info("收到/yolov12/train训练请求")
  177. logging.info(f"请求参数: {params}")
  178. try:
  179. model = YOLO("yolov12.yaml") # 如有yolov12n.yaml可替换
  180. logging.info("开始模型训练...")
  181. results = model.train(
  182. data=params.data,
  183. epochs=params.epochs,
  184. batch=params.batch,
  185. imgsz=params.imgsz,
  186. scale=params.scale,
  187. mosaic=params.mosaic,
  188. mixup=params.mixup,
  189. copy_paste=params.copy_paste,
  190. device=params.device,
  191. project=params.project,
  192. name=params.name,
  193. exist_ok=params.exist_ok,
  194. )
  195. logging.info("模型训练完成")
  196. logging.info(f"训练结果: save_dir={results.save_dir}, metrics={results.metrics}, epoch={results.epoch}, best_fitness={getattr(results, 'best_fitness', None)}")
  197. return {
  198. "code": 0,
  199. "msg": "success",
  200. "result": {
  201. "save_dir": str(results.save_dir),
  202. "metrics": str(results.metrics),
  203. "epoch": results.epoch,
  204. "best_fitness": getattr(results, "best_fitness", None)
  205. }
  206. }
  207. except Exception as e:
  208. logging.error(f"训练过程发生异常: {e}")
  209. return {
  210. "code": 1,
  211. "msg": str(e),
  212. "result": None
  213. }
  214. if __name__ == "__main__":
  215. threading.Thread(target=start_gradio, daemon=True).start()
  216. uvicorn.run(app_fastapi, host="0.0.0.0", port=8000)