app.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  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. # 确保保存结果,并强制使用MP4格式
  275. predict_kwargs['save'] = True
  276. # 如果输入是视频,强制设置输出格式为MP4
  277. source = params.source
  278. if source:
  279. import os
  280. source_ext = os.path.splitext(source)[1].lower()
  281. video_extensions = ['.mp4', '.avi', '.mov', '.mkv', '.webm', '.flv', '.wmv']
  282. if source_ext in video_extensions:
  283. # 对于视频输入,设置项目名和实验名以确保输出路径
  284. if not predict_kwargs.get('project'):
  285. predict_kwargs['project'] = 'runs/detect'
  286. if not predict_kwargs.get('name'):
  287. predict_kwargs['name'] = 'predict'
  288. results = model.predict(**predict_kwargs)
  289. logging.info("模型预测完成")
  290. # 获取保存目录和最终文件名
  291. result = results[0]
  292. save_dir = result.save_dir if hasattr(result, 'save_dir') else None
  293. # 获取最终生成的文件名
  294. final_filename = None
  295. if save_dir:
  296. import os
  297. import glob
  298. if os.path.exists(save_dir):
  299. # 检查输入源类型
  300. source = params.source
  301. if source:
  302. source_ext = os.path.splitext(source)[1].lower()
  303. video_extensions = ['.mp4', '.avi', '.mov', '.mkv', '.webm', '.flv', '.wmv']
  304. # 如果输入是图片,返回图片文件
  305. if source_ext not in video_extensions:
  306. image_files = []
  307. for ext in ['*.jpg', '*.jpeg', '*.png']:
  308. image_files.extend(glob.glob(os.path.join(save_dir, ext)))
  309. if image_files:
  310. latest_image = max(image_files, key=os.path.getmtime)
  311. final_filename = os.path.basename(latest_image)
  312. logging.info(f"输入为图片,返回图片文件: {final_filename}")
  313. # 如果输入是视频,检查并转换为MP4
  314. else:
  315. # 查找所有视频文件
  316. video_files = []
  317. for ext in ['*.avi', '*.webm', '*.mov']:
  318. video_files.extend(glob.glob(os.path.join(save_dir, ext)))
  319. # 如果找到非MP4视频文件,转换为MP4
  320. for video_file in video_files:
  321. output_mp4 = video_file.rsplit('.', 1)[0] + '.mp4'
  322. try:
  323. import subprocess
  324. # 使用ffmpeg转换为MP4
  325. cmd = [
  326. 'ffmpeg', '-i', video_file,
  327. '-c:v', 'libx264',
  328. '-preset', 'ultrafast',
  329. '-crf', '28',
  330. '-pix_fmt', 'yuv420p',
  331. '-y', output_mp4
  332. ]
  333. logging.info(f"使用ffmpeg转换视频: {video_file} -> {output_mp4}")
  334. result = subprocess.run(cmd, capture_output=True, text=True)
  335. if result.returncode == 0:
  336. os.remove(video_file)
  337. logging.info(f"✓ 成功转换为MP4: {output_mp4}")
  338. else:
  339. logging.error(f"ffmpeg转换失败: {result.stderr}")
  340. except (FileNotFoundError, subprocess.SubprocessError) as e:
  341. logging.error(f"ffmpeg不可用: {e}")
  342. # 如果ffmpeg不可用,尝试使用OpenCV
  343. try:
  344. import cv2
  345. cap = cv2.VideoCapture(video_file)
  346. fps = cap.get(cv2.CAP_PROP_FPS)
  347. width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
  348. height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
  349. # 尝试使用H264编码器
  350. fourcc = cv2.VideoWriter_fourcc(*'H264')
  351. out = cv2.VideoWriter(output_mp4, fourcc, fps, (width, height))
  352. if out.isOpened():
  353. while cap.isOpened():
  354. ret, frame = cap.read()
  355. if not ret:
  356. break
  357. out.write(frame)
  358. cap.release()
  359. out.release()
  360. os.remove(video_file)
  361. logging.info(f"使用OpenCV H264编码器生成MP4: {output_mp4}")
  362. else:
  363. logging.error("OpenCV H264编码器不可用")
  364. except Exception as cv_error:
  365. logging.error(f"OpenCV处理失败: {cv_error}")
  366. except Exception as e:
  367. logging.error(f"转换视频格式时出错: {e}")
  368. # 获取MP4或WebM文件
  369. video_output_files = []
  370. for ext in ['*.mp4', '*.webm']:
  371. video_output_files.extend(glob.glob(os.path.join(save_dir, ext)))
  372. if video_output_files:
  373. latest_video = max(video_output_files, key=os.path.getmtime)
  374. final_filename = os.path.basename(latest_video)
  375. logging.info(f"输入为视频,返回文件: {final_filename}")
  376. # 如果无法确定输入类型或未找到文件,返回最新文件
  377. if not final_filename:
  378. all_files = []
  379. for ext in ['*.jpg', '*.jpeg', '*.png', '*.mp4']:
  380. all_files.extend(glob.glob(os.path.join(save_dir, ext)))
  381. if all_files:
  382. latest_file = max(all_files, key=os.path.getmtime)
  383. final_filename = os.path.basename(latest_file)
  384. logging.info(f"返回最新文件: {final_filename}")
  385. return {
  386. "code": 0,
  387. "msg": "success",
  388. "result": save_dir+"/"+final_filename
  389. }
  390. except Exception as e:
  391. logging.error(f"预测过程发生异常: {e}")
  392. return {
  393. "code": 1,
  394. "msg": str(e),
  395. "result": None
  396. }
  397. # 全局异常处理器:参数校验失败时统一返回格式
  398. @app_fastapi.exception_handler(RequestValidationError)
  399. async def validation_exception_handler(request, exc):
  400. err_msg = f"参数校验失败: 路径={request.url.path}, 错误={exc.errors()}"
  401. logging.error(err_msg)
  402. return JSONResponse(
  403. status_code=status.HTTP_200_OK,
  404. content={
  405. "code": 422,
  406. "msg": err_msg,
  407. "result": None
  408. }
  409. )
  410. if __name__ == "__main__":
  411. threading.Thread(target=start_gradio, daemon=True).start()
  412. uvicorn.run(app_fastapi, host="0.0.0.0", port=8000)