app.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  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": {"save_dir": "保存目录", "filename": "文件名"}}
  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. # 确保保存结果
  275. predict_kwargs['save'] = True
  276. results = model.predict(**predict_kwargs)
  277. logging.info("模型预测完成")
  278. # 获取保存目录和最终文件名
  279. result = results[0]
  280. save_dir = result.save_dir if hasattr(result, 'save_dir') else None
  281. # 获取最终生成的文件名
  282. final_filename = None
  283. if save_dir:
  284. import os
  285. import glob
  286. if os.path.exists(save_dir):
  287. # 检查输入源类型
  288. source = params.source
  289. if source:
  290. source_ext = os.path.splitext(source)[1].lower()
  291. video_extensions = ['.mp4', '.avi', '.mov', '.mkv', '.webm', '.flv', '.wmv']
  292. # 如果输入是图片,返回图片文件
  293. if source_ext not in video_extensions:
  294. image_files = []
  295. for ext in ['*.jpg', '*.jpeg', '*.png']:
  296. image_files.extend(glob.glob(os.path.join(save_dir, ext)))
  297. if image_files:
  298. latest_image = max(image_files, key=os.path.getmtime)
  299. final_filename = os.path.basename(latest_image)
  300. logging.info(f"输入为图片,返回图片文件: {final_filename}")
  301. # 如果输入是视频,检查并转换为MP4
  302. else:
  303. # 查找所有视频文件
  304. video_files = []
  305. for ext in ['*.avi', '*.webm', '*.mov']:
  306. video_files.extend(glob.glob(os.path.join(save_dir, ext)))
  307. # 如果找到非MP4视频文件,转换为MP4
  308. for video_file in video_files:
  309. output_mp4 = video_file.rsplit('.', 1)[0] + '.mp4'
  310. try:
  311. import cv2
  312. cap = cv2.VideoCapture(video_file)
  313. fps = cap.get(cv2.CAP_PROP_FPS)
  314. width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
  315. height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
  316. # 尝试不同的MP4编码器
  317. fourcc_options = ['mp4v', 'avc1', 'H264']
  318. out = None
  319. for fourcc in fourcc_options:
  320. try:
  321. fourcc_code = cv2.VideoWriter_fourcc(*fourcc)
  322. out = cv2.VideoWriter(output_mp4, fourcc_code, fps, (width, height))
  323. if out.isOpened():
  324. logging.info(f"使用编码器 {fourcc} 创建MP4文件")
  325. break
  326. except:
  327. continue
  328. if out and out.isOpened():
  329. while cap.isOpened():
  330. ret, frame = cap.read()
  331. if not ret:
  332. break
  333. out.write(frame)
  334. cap.release()
  335. out.release()
  336. # 删除原文件
  337. os.remove(video_file)
  338. logging.info(f"视频已转换为MP4格式: {output_mp4}")
  339. else:
  340. logging.warning(f"无法创建MP4编码器,保持原格式")
  341. except Exception as e:
  342. logging.error(f"转换视频格式时出错: {e}")
  343. # 获取MP4文件
  344. mp4_files = glob.glob(os.path.join(save_dir, "*.mp4"))
  345. if mp4_files:
  346. latest_mp4 = max(mp4_files, key=os.path.getmtime)
  347. final_filename = os.path.basename(latest_mp4)
  348. logging.info(f"输入为视频,返回MP4文件: {final_filename}")
  349. # 如果无法确定输入类型或未找到文件,返回最新文件
  350. if not final_filename:
  351. all_files = []
  352. for ext in ['*.jpg', '*.jpeg', '*.png', '*.mp4']:
  353. all_files.extend(glob.glob(os.path.join(save_dir, ext)))
  354. if all_files:
  355. latest_file = max(all_files, key=os.path.getmtime)
  356. final_filename = os.path.basename(latest_file)
  357. logging.info(f"返回最新文件: {final_filename}")
  358. return {
  359. "code": 0,
  360. "msg": "success",
  361. "result": save_dir+"/"+final_filename
  362. }
  363. except Exception as e:
  364. logging.error(f"预测过程发生异常: {e}")
  365. return {
  366. "code": 1,
  367. "msg": str(e),
  368. "result": None
  369. }
  370. # 全局异常处理器:参数校验失败时统一返回格式
  371. @app_fastapi.exception_handler(RequestValidationError)
  372. async def validation_exception_handler(request, exc):
  373. err_msg = f"参数校验失败: 路径={request.url.path}, 错误={exc.errors()}"
  374. logging.error(err_msg)
  375. return JSONResponse(
  376. status_code=status.HTTP_200_OK,
  377. content={
  378. "code": 422,
  379. "msg": err_msg,
  380. "result": None
  381. }
  382. )
  383. if __name__ == "__main__":
  384. threading.Thread(target=start_gradio, daemon=True).start()
  385. uvicorn.run(app_fastapi, host="0.0.0.0", port=8000)