电子商务网站建设臧良运课后答案,樱花16q808a,烟台网站制作步骤,响应式网站新闻部分怎么做目录 0. 前言——为什么需要自定义可视化#xff1f;
1. 核心功能点
2. 技术细节#xff1a;如何实现“红底白字”#xff1f;
3. 完整代码实现
4. 使用说明
5. 总结 0. 前言——为什么需要自定义可视化#xff1f;
在使用 Ultralytics YOLO#xff08;v8/v9/v10/v1…目录0. 前言——为什么需要自定义可视化1. 核心功能点2. 技术细节如何实现“红底白字”3. 完整代码实现4. 使用说明5. 总结0. 前言——为什么需要自定义可视化在使用 Ultralytics YOLOv8/v9/v10/v11进行目标检测时我们通常直接调用 model.predict(saveTrue)。虽然官方自带的可视化很方便但它会根据不同的类别分配不同的颜色。在某些学术论文、工业报告或特定演示场景下我们往往需要更统一、更专业的视觉风格——例如亮红色的检测框、红色的标签背景搭配纯白色的文字。今天分享一个实用的 Python 脚本直接绕过官方 UI利用OpenCV重新绘制红色边框、红色标签底、纯白文字。让你的检测结果图瞬间达到出版级水准1. 核心功能点极简视觉风格统一采用“红框 红底 白字”重点突出风格专业。双重输出既生成自定义样式的图片也支持同步保存标准 YOLO 格式的 .txt 标签。坐标精准处理自动处理标签背景框越界问题当物体在图片顶部时标签会自动调整位置。参数化配置支持通过命令行调整置信度、框粗细、字体大小等。2. 技术细节如何实现“红底白字”官方的 plot() 函数高度封装难以精细修改颜色逻辑。本脚本通过以下逻辑实现提取结果利用 result.boxes 获取坐标、类别和置信度。OpenCV 绘制cv2.rectangle画出红色BGR: 0, 0, 255的边框。cv2.getTextSize计算文字宽度动态生成背景红色矩形。cv2.putText在红色背景上叠写白色文字。3. 完整代码实现您可以直接将以下代码保存为 custom_predict.py 并运行。import argparse import os import warnings import cv2 from ultralytics import YOLO warnings.filterwarnings(ignore) def save_txt_yolo_format(result, img_w, img_h, txt_path, save_confTrue): 保存 YOLO 格式标签: class x_center y_center w h [conf] 归一化到 0~1 lines [] if result.boxes is None or len(result.boxes) 0: open(txt_path, w).close() return boxes_xyxy result.boxes.xyxy.cpu().numpy() clss result.boxes.cls.cpu().numpy().astype(int) confs result.boxes.conf.cpu().numpy() if result.boxes.conf is not None else None for i, (x1, y1, x2, y2) in enumerate(boxes_xyxy): x1, y1, x2, y2 float(x1), float(y1), float(x2), float(y2) xc (x1 x2) / 2.0 / img_w yc (y1 y2) / 2.0 / img_h bw (x2 - x1) / img_w bh (y2 - y1) / img_h if save_conf and confs is not None: lines.append(f{clss[i]} {xc:.6f} {yc:.6f} {bw:.6f} {bh:.6f} {confs[i]:.6f}) else: lines.append(f{clss[i]} {xc:.6f} {yc:.6f} {bw:.6f} {bh:.6f}) with open(txt_path, w) as f: f.write(\n.join(lines)) def draw_red_box_red_bg_white_text(results, out_dir, save_txtFalse, save_confTrue, line_thickness2, font_scale0.6): 框红、标签底红、文字白色类别置信度 os.makedirs(out_dir, exist_okTrue) labels_dir os.path.join(out_dir, labels) if save_txt: os.makedirs(labels_dir, exist_okTrue) red (0, 0, 255) # BGR 红色 white (255, 255, 255) # BGR 白色 for r in results: img_path r.path img cv2.imread(img_path) if img is None: print(f⚠️ 读图失败: {img_path}) continue h, w img.shape[:2] names r.names # dict: class_id - class_name # 保存 txt if save_txt: base os.path.splitext(os.path.basename(img_path))[0] txt_path os.path.join(labels_dir, base .txt) save_txt_yolo_format(r, w, h, txt_path, save_confsave_conf) # 画框 标签 if r.boxes is not None and len(r.boxes) 0: boxes r.boxes.xyxy.cpu().numpy() confs r.boxes.conf.cpu().numpy() if r.boxes.conf is not None else None clss r.boxes.cls.cpu().numpy().astype(int) if r.boxes.cls is not None else None for i, (x1, y1, x2, y2) in enumerate(boxes): x1, y1, x2, y2 map(int, [x1, y1, x2, y2]) # 红框 cv2.rectangle(img, (x1, y1), (x2, y2), red, line_thickness) # 标签文本class conf label if clss is not None: label names.get(int(clss[i]), str(int(clss[i]))) if save_conf and confs is not None: label f {confs[i]:.2f} if label.strip(): (tw, th), baseline cv2.getTextSize( label, cv2.FONT_HERSHEY_SIMPLEX, font_scale, 2 ) # 标签放在框上方避免越界放不下就顶到0 y_top max(0, y1 - th - baseline - 6) # 标签背景红色 cv2.rectangle( img, (x1, y_top), (x1 tw 6, y1), red, -1 ) # 标签文字白色 cv2.putText( img, label, (x1 3, y1 - 4), cv2.FONT_HERSHEY_SIMPLEX, font_scale, white, 2, cv2.LINE_AA ) save_path os.path.join(out_dir, os.path.basename(img_path)) cv2.imwrite(save_path, img) def main(opt): model YOLO(opt.weights) print(f 开始预测{opt.source}) print(f✅ 权重{opt.weights}) # 预测关闭官方保存自己画才能控颜色 results model.predict( sourceopt.source, imgszopt.img_size, deviceopt.device, confopt.conf, saveFalse, verboseFalse ) out_dir os.path.join(opt.project, opt.name) draw_red_box_red_bg_white_text( results, out_dirout_dir, save_txtopt.save_txt, save_confTrue, line_thicknessopt.thickness, font_scaleopt.font_scale ) print(f✅ 完成红框红底白字输出目录{out_dir}) if opt.save_txt: print(f✅ txt 已保存到{os.path.join(out_dir, labels)}) if __name__ __main__: parser argparse.ArgumentParser() parser.add_argument( --weights, typestr, default/root/autodl-tmp/ultralytics-main/runs/detect/train3/weights/best.pt, helpmodel weight path ) parser.add_argument( --source, typestr, default/root/autodl-tmp/ultralytics-main/images, helpimage dir or image file ) parser.add_argument(--img_size, typeint, default640, helpimage size) parser.add_argument(--device, typestr, default0, helpcuda device) parser.add_argument(--conf, typefloat, default0.25, helpconfidence threshold) parser.add_argument(--project, typestr, defaultruns/predict, helpsave root dir) parser.add_argument(--name, typestr, defaulttrain1_pred, helpsave sub dir name) parser.add_argument(--save_txt, actionstore_true, helpsave yolo txt labels) parser.add_argument(--thickness, typeint, default2, helpbox line thickness) parser.add_argument(--font_scale, typefloat, default0.6, helplabel font scale) opt parser.parse_args() main(opt)4. 使用说明1. 基础预测codeBashdownloadcontent_copyexpand_lesspython custom_predict.py --weights ./runs/train/best.pt --source ./data/test_images2. 调整线条粗细与字体适合高分辨率图codeBashdownloadcontent_copyexpand_lesspython custom_predict.py --weights best.pt --source ./images --thickness 4 --font_scale 0.83. 同时生成标签文件用于辅助标注codeBashdownloadcontent_copyexpand_lesspython custom_predict.py --weights best.pt --source ./images --save_txt5. 总结通过简单的 OpenCV 二次开发我们可以轻松突破 YOLO 官方库的可视化限制。这种红底白字的风格不仅统一了视觉语言更在复杂背景下提供了极佳的辨识度。如果你觉得这个脚本有用欢迎点赞、收藏并关注我的 CSDN 账号获取更多深度学习实用工具