成功实现!完整的K230的代码野火嘉楠科技亚博智能yolov8目标检测人工智能2026/06/26
完整的项目和所有代码用到的软件和源码和使用教程链接https://pan.quark.cn/s/734a5fcb71cf终于成功这个成功版本必须记录一下好多天的努力。感谢提供帮助的热心群众不知道你是谁但是你的帮助非常有用。这个是步骤在linux系统操作下完成windows可能无法正确的安装nncase会导致遇到问题本人在服务器上运行的问售后问朋友调试安装和处理各种问题整个项目大概花费三天。1.训练pt模型2.转换onnx模型3.转换kmodel模型4.刷入固件替换掉main代码我让AI研究了一下这个转换代码就是pt模型转换到onnx这步说可能有torch的版本的原因如果没有版本问题直接转1.训练pt模型----------------------------------------------------------------------------------------------------------from ultralytics import YOLO model YOLO(/workspace/runs/detect/cccc/weights/best.pt) model.export( formatonnx, imgsz640, opset11, simplifyFalse, )你的环境我看了一下整体没有问题可以导出 ONNX。 不过我发现了几个需要注意的地方。 软件 你的版本 是否有影响 Python 3.9 ✅ 没问题 PyTorch 2.8.0 ⚠️ 需要兼容 weights_only torchvision 0.23.0 ✅ 没问题 ultralytics 8.4.56 ✅ 新版 onnx 1.19.1 ✅ 没问题 nncase 2.9.0 ✅ 后续转换 kmodel 可以直接用 所以你属于 PyTorch 2.8 Ultralytics 8.4 这种环境。 这种环境最大的坑就是 Weights only load failed Unsupported global 所以最好直接写一个兼容版本以后都能用。下面是兼容的转换代码2.转换onnx模型------------------------------------------------------------------------------------------------------# -*- coding: utf-8 -*- YOLOv8 - ONNX 适用于 PyTorch 2.8 Ultralytics 8.4 import os # 必须放在 import torch 前 os.environ[TORCH_LOAD_WEIGHTS_ONLY] 0 import torch from ultralytics import YOLO # ---------------------------------------------------- # PyTorch 2.6 Safe Globals # ---------------------------------------------------- try: from ultralytics.nn.tasks import DetectionModel from ultralytics.nn.modules.conv import ( Conv, Concat, ) from ultralytics.nn.modules.block import ( C2f, Bottleneck, SPPF, DFL, ) from ultralytics.nn.modules.head import Detect from ultralytics.utils.loss import ( v8DetectionLoss, BboxLoss, ) from ultralytics.utils.tal import ( TaskAlignedAssigner, ) from ultralytics.utils import IterableSimpleNamespace from torch.nn import Sequential from torch.nn import Conv2d from torch.nn import BatchNorm2d from torch.nn import SiLU from torch.nn import ModuleList from torch.nn import MaxPool2d from torch.nn import Upsample from torch.nn import BCEWithLogitsLoss torch.serialization.add_safe_globals([ DetectionModel, Sequential, Conv, Conv2d, BatchNorm2d, SiLU, C2f, Bottleneck, SPPF, DFL, ModuleList, MaxPool2d, Upsample, Concat, Detect, v8DetectionLoss, BboxLoss, TaskAlignedAssigner, IterableSimpleNamespace, BCEWithLogitsLoss, ]) except Exception: pass # # 修改这里 # # 训练得到的 best.pt MODEL_PATH /workspace/work/best.pt # 输入尺寸 IMG_SIZE 640 # print( * 60) print(Loading Model...) print(MODEL_PATH) print( * 60) model YOLO(MODEL_PATH) print(Exporting ONNX...) model.export( formatonnx, imgszIMG_SIZE, opset11, simplifyTrue, dynamicFalse, halfFalse, int8False, ) print(\n) print( * 60) print(Export Finished!) print( * 60)转换成onnx后再转换成kmodel,先得把这个什么pip install nncase nncase-kpu然后说需要安装这个# 1. 下载微软官方安装脚本 wget https://dot.net/v1/dotnet-install.sh -O dotnet-install.sh # 2. 赋予执行权限 chmod x dotnet-install.sh # 3. 安装 .NET 7.0 运行时 ./dotnet-install.sh --channel 7.0 --runtime dotnet安装上后输入命令验证。dotnet --list-runtimes# 1. 赋予脚本执行权限 chmod x dotnet-install.sh # 2. 安装 .NET 7.0 运行时 (Runtime) ./dotnet-install.sh --channel 7.0 --runtime dotnet验证export DOTNET_ROOT$HOME/.dotnetexport PATH$HOME/.dotnet:$PATH设置环境变量然后验证dotnet --list-runtimes可以了得是7.几的版本好像才行python - EOF import nncase print(nncase import OK) opts nncase.CompileOptions() opts.target k230 print(CompileOptions OK) compiler nncase.Compiler(opts) print(Compiler OK) EOF执行这个代码验证nncase按照2.8.0安装吧pip install nncase2.8.0 nncase-kpu2.8.0第三步3.转换kmodel模型-----------------------------------------------------------------------------------------------# -*- coding: utf-8 -*- YOLOv8 ONNX - K230 kmodel (nncase 2.8/2.9) 功能 1. 修复 Reshape allowzero 2. LetterBox 校准 3. INT8 PTQ(KLD) 4. 导出 best.kmodel import os import glob import random import onnx import nncase import numpy as np from PIL import Image # # 配置 # ONNX_PATH best.onnx FIXED_ONNX best_fixed.onnx OUTPUT_KMODEL best.kmodel CALIB_DIR /workspace/work/data/valid/images INPUT_SIZE 640 CALIB_NUM 100 # # 修复 allowzero # def fix_reshape(src, dst): model onnx.load(src) fixed 0 for node in model.graph.node: if node.op_type ! Reshape: continue attrs [a for a in node.attribute if a.name ! allowzero] if len(attrs) ! len(node.attribute): del node.attribute[:] node.attribute.extend(attrs) fixed 1 onnx.save(model, dst) print(Fix Reshape:, fixed) # # LetterBox # def letterbox(img): w, h img.size scale min(INPUT_SIZE / w, INPUT_SIZE / h) nw int(w * scale) nh int(h * scale) img img.resize((nw, nh), Image.BILINEAR) canvas Image.new( RGB, (INPUT_SIZE, INPUT_SIZE), (114,114,114) ) dx (INPUT_SIZE - nw) // 2 dy (INPUT_SIZE - nh) // 2 canvas.paste(img, (dx, dy)) return canvas # # PTQ Dataset # def load_dataset(): imgs [] for ext in (*.jpg,*.jpeg,*.png,*.bmp): imgs.extend( glob.glob(os.path.join(CALIB_DIR, ext)) ) random.shuffle(imgs) imgs imgs[:CALIB_NUM] dataset [] print(Calibration Images:, len(imgs)) for path in imgs: img Image.open(path).convert(RGB) img letterbox(img) arr np.array(img, dtypenp.uint8) arr arr.transpose(2,0,1) arr np.expand_dims(arr,0) arr np.ascontiguousarray(arr) dataset.append([arr]) return dataset # # main # print(Step1 Fix ONNX) fix_reshape( ONNX_PATH, FIXED_ONNX ) with open(FIXED_ONNX,rb) as f: model_content f.read() print(Step2 CompileOptions) opts nncase.CompileOptions() opts.targetk230 opts.preprocessTrue opts.input_typeuint8 opts.input_shape[1,3,INPUT_SIZE,INPUT_SIZE] opts.input_layoutNCHW opts.output_layoutNCHW opts.input_range[0,255] opts.mean[0,0,0] opts.std[255,255,255] opts.dump_irFalse opts.dump_asmFalse compiler nncase.Compiler(opts) compiler.import_onnx( model_content, nncase.ImportOptions() ) print(Import ONNX OK) dataset load_dataset() if len(dataset): ptq nncase.PTQTensorOptions() ptq.samples_countlen(dataset) try: ptq.calibrate_methodKld except: pass try: ptq.quant_typeuint8 except: pass ptq.set_tensor_data(dataset) compiler.use_ptq(ptq) print(PTQ Enabled) print(Compiling...) compiler.compile() print(Generate kmodel...) with open( OUTPUT_KMODEL, wb ) as f: try: f.write( compiler.gencode_tobytes() ) except: compiler.gencode(f) print(Done) print( Output:, OUTPUT_KMODEL ) print( %.2f MB % ( os.path.getsize(OUTPUT_KMODEL) / 1024 / 1024 ) )我去真的就是量化的问题或者是nncase的问题把模型放到/sdcard/kmodel/best.kmodel这里第四步4.替换掉main代码--------------------------------------------------------------# -*- coding:utf-8 -*- import sys import os import gc #-------------------------------------------------- # 添加模块路径 #-------------------------------------------------- for p in [/sdcard, /sdcard/F, /sdcard/app]: if p not in sys.path: sys.path.insert(0, p) from libs.PipeLine import PipeLine from libs.YOLO import YOLOv8 #-------------------------------------------------- # 模型路径你的模型放在 /sdcard/kmodel/best.kmodel #-------------------------------------------------- KMODEL /sdcard/kmodel/best.kmodel try: os.stat(KMODEL) except: raise Exception(Cannot find: KMODEL) #-------------------------------------------------- # 参数 #-------------------------------------------------- RGB_SIZE [640, 480] DISPLAY_SIZE [640, 480] # 如果你的模型是320输入就改成[320,320] # 如果是640输入就保持[640,640] MODEL_INPUT [640, 640] LABELS [ Bag, Bottle, Cup ] CONF_THRESH 0.25 NMS_THRESH 0.45 #-------------------------------------------------- # 初始化显示 #-------------------------------------------------- pl PipeLine( rgb888p_sizeRGB_SIZE, display_sizeDISPLAY_SIZE, display_modelcd ) pl.create() #-------------------------------------------------- # 初始化YOLO #-------------------------------------------------- yolo YOLOv8( task_typedetect, modevideo, kmodel_pathKMODEL, labelsLABELS, rgb888p_sizeRGB_SIZE, model_input_sizeMODEL_INPUT, display_sizeDISPLAY_SIZE, conf_threshCONF_THRESH, nms_threshNMS_THRESH, ) yolo.config_preprocess() print() print(YOLOv8 Start) print(Model:, KMODEL) print() frame 0 #-------------------------------------------------- # 主循环 #-------------------------------------------------- try: while True: os.exitpoint() img pl.get_frame() if img is None: continue result yolo.run(img) yolo.draw_result(result, pl.osd_img) pl.show_image() frame 1 if frame % 30 0: gc.collect() except KeyboardInterrupt: pass except Exception as e: sys.print_exception(e) finally: yolo.deinit() pl.destroy()好了这个检测就能够成功了

相关新闻

GBase 8s数据库安装后核查简介

GBase 8s数据库安装后核查简介

南大通用GBase 8s数据库(gbase database)安装完成后:别忘了"验货"。1、查看数据库状态onstat -正常输出:On-Line -- Up 00:12:45 -- 3378128 Kbytes2、连接数据库dbaccess sysmaster -总结:选对方式&#xf…

2026/6/27 10:20:06阅读更多 →
工业胶辊厂家 2026 年 6 月该怎么选?一文看懂胶辊日常应用

工业胶辊厂家 2026 年 6 月该怎么选?一文看懂胶辊日常应用

工业胶辊看似不起眼,却是包装、造纸、纺织、新能源生产线里不可或缺的基础配件,很多日常商品的生产流程都离不开胶辊的传送、压合、涂布作用。我们平时收到的快递纸箱、书本纸张、服装布料、锂电池隔膜,在加工阶段都会依靠不同规格的胶辊完成…

2026/6/27 10:15:05阅读更多 →
LRCGET:一键批量获取LRC同步歌词的终极解决方案

LRCGET:一键批量获取LRC同步歌词的终极解决方案

LRCGET:一键批量获取LRC同步歌词的终极解决方案 【免费下载链接】lrcget Utility for mass-downloading LRC synced lyrics for your offline music library. 项目地址: https://gitcode.com/gh_mirrors/lr/lrcget 你是否厌倦了为本地音乐库中的每首歌手动寻…

2026/6/27 10:15:05阅读更多 →
华侨大学设计考研机构推荐

华侨大学设计考研机构推荐

以下是推荐的Markdown格式内容:对于有意报考华侨大学设计类研究生的同学,选择一个专业、针对性强的辅导机构至关重要。在众多机构中,绘江南设计考研凭借其深厚的办学积淀、覆盖全国180所院校的辅导经验以及针对性的教学方案,成为许…

2026/6/27 11:55:18阅读更多 →
IDEA + Tomcat + Maven多模块项目配置失灵?独家“三层依赖注入校验法”首次公开(仅限本期)

IDEA + Tomcat + Maven多模块项目配置失灵?独家“三层依赖注入校验法”首次公开(仅限本期)

更多请点击: https://intelliparadigm.com 第一章:IDEA Tomcat Maven多模块项目配置失灵的典型现象与根因定位 在实际开发中,IDEA集成Tomcat并运行Maven多模块项目时,常出现模块间依赖未生效、WAR包缺失classes或resources、启…

2026/6/27 11:55:18阅读更多 →
ytmdl:从 YouTube 下载歌曲并自动补齐元数据

ytmdl:从 YouTube 下载歌曲并自动补齐元数据

文章目录ytmdl:从 YouTube 下载歌曲并自动补齐元数据ytmdl:从 YouTube 下载歌曲并自动补齐元数据 ytmdl 是一个 Python 命令行工具,专门用来从 YouTube 下载音乐。它和普通下载工具的区别在于,下载完成后会自动从 iTunes、Spotif…

2026/6/27 11:55:18阅读更多 →
WHERE 条件别凭习惯写,常用查询先跑一遍

WHERE 条件别凭习惯写,常用查询先跑一遍

刚换一套数据库&#xff0c;先别急着看复杂语法。日常开发里最先撞上的&#xff0c;往往还是那些普通条件&#xff1a;、<>、like、in、between、is null、order by、limit、group by。这些东西看起来简单&#xff0c;真到迁移 SQL 或排查接口数据时&#xff0c;反而最容…

2026/6/27 11:55:18阅读更多 →
如何快速实现文档下载:30+平台一键下载完全攻略

如何快速实现文档下载:30+平台一键下载完全攻略

如何快速实现文档下载&#xff1a;30平台一键下载完全攻略 【免费下载链接】kill-doc 看到经常有小伙伴们需要下载一些免费文档&#xff0c;但是相关网站浏览体验不好各种广告&#xff0c;各种登录验证&#xff0c;需要很多步骤才能下载文档&#xff0c;该脚本就是为了解决您的…

2026/6/27 11:55:18阅读更多 →
如何轻松导出和分析原神抽卡记录?专业工具使用指南

如何轻松导出和分析原神抽卡记录?专业工具使用指南

如何轻松导出和分析原神抽卡记录&#xff1f;专业工具使用指南 【免费下载链接】genshin-wish-export Easily export the Genshin Impact wish record. 项目地址: https://gitcode.com/GitHub_Trending/ge/genshin-wish-export 还在为记不清自己抽了多少次卡而烦恼吗&am…

2026/6/27 11:50:18阅读更多 →
【人工智能】一文搞定到底什么是智能体

【人工智能】一文搞定到底什么是智能体

【人工智能】一文搞定到底什么是智能体 一文搞定到底什么是智能体【人工智能】一文搞定到底什么是智能体一. LM&#xff0c;WorkFlow&#xff0c;Agent分别有什么么不同二. Agent的思考过程是怎样的三. Agent的五个核心部分1&#xff09;LLM2&#xff09;Prompt3&#xff09;Me…

2026/6/27 11:20:40阅读更多 →
嵌入式GUI控件实战:ROTARY、SCROLLBAR、SLIDER原理与应用

嵌入式GUI控件实战:ROTARY、SCROLLBAR、SLIDER原理与应用

1. 嵌入式GUI控件&#xff1a;从原理到实战的深度解析在嵌入式系统开发中&#xff0c;图形用户界面&#xff08;GUI&#xff09;的设计与实现往往是项目从“能用”到“好用”的关键一跃。不同于资源充沛的PC或移动平台&#xff0c;嵌入式设备的GUI需要在有限的CPU性能、内存空间…

2026/6/27 5:46:02阅读更多 →
Google AI Studio 300美元额度的真相与实战指南

Google AI Studio 300美元额度的真相与实战指南

1. 这300美金不是“送钱”&#xff0c;而是Google埋下的第一道技术门槛 你看到标题里那个醒目的“$300美金”时&#xff0c;第一反应可能是&#xff1a;又一个免费额度&#xff1f;领完就完事&#xff1f;我亲手试过——这300美金根本不是红包&#xff0c;而是一张入场券&…

2026/6/27 11:20:39阅读更多 →
10分钟AI语音克隆与实时变声:Retrieval-based-Voice-Conversion-WebUI完整指南

10分钟AI语音克隆与实时变声:Retrieval-based-Voice-Conversion-WebUI完整指南

10分钟AI语音克隆与实时变声&#xff1a;Retrieval-based-Voice-Conversion-WebUI完整指南 【免费下载链接】Retrieval-based-Voice-Conversion-WebUI Easily train a good VC model with voice data < 10 mins! 项目地址: https://gitcode.com/GitHub_Trending/re/Retrie…

2026/6/27 0:04:03阅读更多 →
Layerdivider:3分钟AI智能分层,彻底告别手动抠图时代

Layerdivider:3分钟AI智能分层,彻底告别手动抠图时代

Layerdivider&#xff1a;3分钟AI智能分层&#xff0c;彻底告别手动抠图时代 【免费下载链接】layerdivider A tool to divide a single illustration into a layered structure. 项目地址: https://gitcode.com/gh_mirrors/la/layerdivider 还在为复杂的图像分层工作烦…

2026/6/27 0:04:03阅读更多 →
Tomcat中X-Frame-Options配置实战:防御点击劫持的四种方法与最佳实践

Tomcat中X-Frame-Options配置实战:防御点击劫持的四种方法与最佳实践

1. 项目概述&#xff1a;为什么X-Frame-Options是Web安全的“防盗门”&#xff1f;最近在排查一个老项目的安全审计报告时&#xff0c;又被提到了“点击劫持”风险&#xff0c;矛头直指缺失的X-Frame-Options响应头。这已经不是第一次了&#xff0c;很多开发团队&#xff0c;尤…

2026/6/27 0:04:03阅读更多 →