o1-preview-2024-09-12· OpenAI
WildChat-4.8M (AI2)
帮我写一个python 调用 yolov3 转换后的 ncnn模型的函数
- User
帮我写一个python 调用 yolov3 转换后的 ncnn模型的函数
- Assistant
帮我写一个python 调用 yolov3 转换后的 ncnn模型的函数
好的,这里提供一个使用 Python 调用转换为 ncnn 模型的 YOLOv3 的示例函数。该函数将加载 ncnn 格式的 YOLOv3 模型,对输入图像进行检测,并返回检测结果。
首先,您需要确保已经安装了 ncnn 的 Python 绑定,可以通过 pip install ncnn 进行安装。如果尚未安装,请先安装。
import ncnn
import cv2
import numpy as np
class YoloV3Detector:
def __init__(self, param_path, bin_path, target_size=416, num_threads=4, prob_threshold=0.5, nms_threshold=0.45):
self.target_size = target_size
self.num_threads = num_threads
self.prob_threshold = prob_threshold
self.nms_threshold = nms_threshold
# 加载 ncnn 模型
self.net = ncnn.Net()
self.net.load_param(param_path)
self.net.load_model(bin_path)
# COCO 数据集的 80 个类名
self.class_names = [
'person', 'bicycle', 'car', 'motorbike', 'aeroplane', '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', 'sofa', 'potted plant',
'bed', 'dining table', 'toilet', 'TV monitor', 'laptop', 'mouse',
'remote', 'keyboard', 'cell phone', 'microwave', 'oven', 'toaster',
'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear',
'hair drier', 'toothbrush'
]
# YOLOv3 的 anchors 和 masks
self.anchors = [
[10,13, 16,30, 33,23],
[30,61, 62,45, 59,119],
[116,90, 156,198, 373,326]
]
self.anchor_masks = [
[6,7,8],
[3,4,5],
[0,1,2]
]
# 输出层名称,根据您的模型修改
self.output_layers = ['yolo82', 'yolo94', 'yolo106']
def __del__(self):
self.net = None
def detect(self, image):
# 获取图像宽高
img_h, img_w = image.shape[:2]
# 图像预处理:缩放并填充到目标尺寸
scale = min(self.target_size / img_w, self.target_size / img_h)
new_w = int(img_w * scale)
new_h = int(img_h * scale)
resized_img = cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_LINEAR)
padded_img = np.full((self.target_size, self.target_size, 3), 128, dtype=np.uint8)
padded_img[0:new_h, 0:new_w, :] = resized_img
# BGR 转 RGB,归一化
padded_img = padded_img[:, :, ::-1]
padded_img = padded_img.astype(np.float32) / 255.0
# 维度调整为 CHW
padded_img = padded_img.transpose((2, 0, 1))
# 创建 ncnn 的 Mat 输入
mat_in = ncnn.Mat(padded_img)
# 创建 extractor
ex = self.net.create_extractor()
ex.set_num_threads(self.num_threads)
ex.input("data", mat_in)
all_boxes = []
for idx, output_layer in enumerate(self.output_layers):
# 提取输出
ret, mat_out = ex.extract(output_layer)
if ret != 0:
continue
# 处理输出,获取检测框
boxes = self._process_output(mat_out, idx, scale, img_w, img_h)
all_boxes.extend(boxes)
# 非极大值抑制
detections = self._nms(all_boxes)
return detections
def _process_output(self, mat_out, idx, scale, img_w, img_h):
# 获取输出的尺寸
grid_h = mat_out.h
grid_w = mat_out.w
num_anchors = len(self.anchor_masks[idx])
# 将 mat_out 转为 numpy 数组
mat_out = np.array(mat_out)
mat_out = mat_out.reshape((grid_h, grid_w, num_anchors, -1))
boxes = []
for i in range(grid_h):
for j in range(grid_w):
for k in range(num_anchors):
data = mat_out[i, j, k, :]
box, score = self._decode_box(data, j, i, idx, k, scale, img_w, img_h)
if score > self.prob_threshold:
boxes.append(box)
return boxes
def _decode_box(self, data, x, y, idx, anchor_idx, scale, img_w, img_h):
# 获取当前特征层的 anchor
anchor = self.anchors[idx][anchor_idx * 2: (anchor_idx + 1) * 2]
# 数据解析
tx, ty, tw, th = data[0], data[1], data[2], data[3]
obj_score = data[4]
class_scores = data[5:]
# 激活函数
tx = 1 / (1 + np.exp(-tx))
ty = 1 / (1 + np.exp(-ty))
tw = np.exp(tw)
th = np.exp(th)
obj_score = 1 / (1 + np.exp(-obj_score))
class_scores = 1 / (1 + np.exp(-class_scores))
# 计算预测框位置
box_cx = (x + tx) / (mat_out.w)
box_cy = (y + ty) / (mat_out.h)
box_w = (tw * anchor[0]) / self.target_size
box_h = (th * anchor[1]) / self.target_size
# 转换为左上角和右下角坐标
x1 = (box_cx - box_w / 2) * img_w
y1 = (box_cy - box_h / 2) * img_h
x2 = (box_cx + box_w / 2) * img_w
y2 = (box_cy + box_h / 2) * img_h
# 获取类别和得分
class_id = np.argmax(class_scores)
class_score = class_scores[class_id]
score = obj_score * class_score
box = {
'x1': x1,
'y1': y1,
'x2': x2,
'y2': y2,
'score': score,
'class_id': class_id
}
return box, score
def _nms(self, boxes):
if len(boxes) == 0:
return []
boxes_array = np.array([[box['x1'], box['y1'], box['x2'], box['y2'], box['score'], box['class_id']] for box in boxes])
keep = []
for class_id in set(boxes_array[:,5]):
idxs = np.where(boxes_array[:,5]==class_id)[0]
class_boxes = boxes_array[idxs]
x1 = class_boxes[:,0]
y1 = class_boxes[:,1]
x2 = class_boxes[:,2]
y2 = class_boxes[:,3]
scores = class_boxes[:,4]
areas = (x2 - x1) * (y2 - y1)
order = scores.argsort()[::-1]
while order.size > 0:
i = order[0]
keep.append(class_boxes[i, :])
xx1 = np.maximum(x1[i], x1[order[1:]])
yy1 = np.maximum(y1[i], y1[order[1:]])
xx2 = np.minimum(x2[i], x2[order[1:]])
yy2 = np.minimum(y2[i], y2[order[1:]])
w = np.maximum(0.0, xx2 - xx1)
h = np.maximum(0.0, yy2 - yy1)
inter = w * h
ovr = inter / (areas[i] + areas[order[1:]] - inter)
inds = np.where(ovr <= self.nms_threshold)[0]
order = order[inds + 1]
# 转换回字典列表
detections = []
for det in keep:
detections.append({
'x1': det[0],
'y1': det[1],
'x2': det[2],
'y2': det[3],
'score': det[4],
'class_id': int(det[5])
})
return detections
# 使用示例
if __name__ == '__main__':
# 模型文件路径
param_path = 'yolov3.param'
bin_path = 'yolov3.bin'
# 加载图像
image_path = 'input.jpg'
image = cv2.imread(image_path)
# 创建检测器
detector = YoloV3Detector(param_path, bin_path)
# 进行检测
detections = detector.detect(image)
# 绘制检测结果
for det in detections:
x1 = int(det['x1'])
y1 = int(det['y1'])
x2 = int(det['x2'])
y2 = int(det['y2'])
score = det['score']
class_id = det['class_id']
label = detector.class_names[class_id]
cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 2)
text = f'{label}: {score:.2f}'
cv2.putText(image, text, (x1, y1 - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1)
# 显示结果图像
cv2.imshow('Detections', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
注意事项:
模型文件路径: 请确保 yolov3.param 和 yolov3.bin 是正确的模型文件路径。
输出层名称: 根据您的模型结构,可能需要修改 self.output_layers 中的输出层名称。
anchors 和 masks: 如果您的模型使用了不同的 anchors 或者 anchors masks,需要相应地修改 self.anchors 和 self.anchor_masks。
输入名称: 在 ex.input("data", mat_in) 中,"data" 是输入层的名称,可能需要根据您的模型修改。
类名列表: 目前提供的是 COCO 数据集的类名,如果您的模型使用了其他数据集,请更新 self.class_names。
依赖库版本: 请确保您的 ncnn Python 版本与模型兼容。
代码调整: 由于模型的转换方式和具体实现可能有所不同,您可能需要根据实际情况调整代码。
总结:
以上代码提供了一个基本的 YOLOv3 ncnn 模型的 Python 调用示例,包括模型加载、前向推理、结果解析、非极大值抑制以及结果绘制等步骤。您可以根据自己的需求进行调整和优化。
Not yet included in a published release.