from libs.YOLO import YOLOv8
import os,sys,gc
import ulab.numpy as np
import image
# 如果是 COCO-80 模型,请使用完整列表:
labels = [
"person","bicycle","car","motorcycle","airplane","bus","train","truck","boat","traffic light",
"fire hydrant","stop sign","parking meter","bench","bird","cat","dog","horse","sheep","cow",
"elephant","bear","zebra","giraffe","backpack","umbrella","handbag","tie","suitcase","frisbee",
"skis","snowboard","sports ball","kite","baseball bat","baseball glove","skateboard","surfboard",
"tennis racket","bottle","wine glass","cup","fork","knife","spoon","bowl","banana","apple","sandwich",
"orange","broccoli","carrot","hot dog","pizza","donut","cake","chair","couch","potted plant","bed",
"dining table","toilet","tv","laptop","mouse","remote","keyboard","cell phone","microwave","oven",
"toaster","sink","refrigerator","book","clock","vase","scissors","teddy bear","hair drier","toothbrush"
]
# —— 确保最前面就定义好 split_path ——
def split_path(path):
parts = path.rsplit('/', 1)
if len(parts) == 1:
dir_path, filename = '', parts[0]
else:
dir_path, filename = parts
name_parts = filename.rsplit('.', 1)
if len(name_parts) == 1:
name, ext = name_parts[0], ''
else:
name, ext = name_parts
ext = '.' + ext
return dir_path, name, ext
# 从本地读入图片,并实现HWC转CHW
def read_img(img_path):
img_data = image.Image(img_path)
img_data_rgb888=img_data.to_rgb888()
img_hwc=img_data_rgb888.to_numpy_ref()
shape=img_hwc.shape
img_tmp = img_hwc.reshape((shape[0] * shape[1], shape[2]))
img_tmp_trans = img_tmp.transpose()
img_res=img_tmp_trans.copy()
img_return=img_res.reshape((shape[2],shape[0],shape[1]))
print(img_return.shape[2],"," ,img_return.shape[1])
print(img_data_rgb888.height())
return img_return,img_data_rgb888
if __name__=="__main__":
# 可以根据您的模型自行修改路径参数
img_path="/data/test_apple.jpg"
kmodel_path="/sdcard/examples/kmodel/yolov8n_320.kmodel"
# labels = ["apple","banana","orange"]
# print("hello")
confidence_threshold = 0.5
nms_threshold = 0.45
model_input_size=[320,320]
img,img_ori=read_img(img_path)
# print(img.shape[2],img.shape[1])
rgb888p_size=[img.shape[2],img.shape[1]] #img.shape[2]=1024,img.shape[1]=1024
# 初始化YOLOv8实例
yolo=YOLOv8(task_type="detect",
mode="image",
kmodel_path=kmodel_path,
labels=labels,
rgb888p_size=rgb888p_size,
model_input_size=model_input_size,
conf_thresh=confidence_threshold,
nms_thresh=nms_threshold,
debug_mode=0)
yolo.config_preprocess()
try:
res=yolo.run(img)
valid_res = []
if res is None or len(res) == 0:
print("⚠️ 未检测到任何目标!")
else:
print(f"✅ 共检测到 {len(res)} 条原始结果:")
for i, row in enumerate(res):
cid = int(row[5])
name = labels[cid] if 0 <= cid < len(labels) else "unknown"
print(f" {i}: class_id={cid} ({name}), conf={row[4]:.2f}, box={[int(x) for x in row[:4]]}")
yolo.draw_result(res, img_ori)
# 生成功能:拼接保存路径
dir_path, name, ext = split_path(img_path)
save_name = "{}_result{}".format(name, ext)
save_path = dir_path + '/' + save_name if dir_path else save_name
img_to_save = img_ori.to_jpeg(quality=95)
# 保存结果图像
img_to_save.save(save_path)
print("检测结果已保存到:", save_path)
gc.collect()
except Exception as e:
sys.print_exception(e)
finally:
yolo.deinit()