Article Directory
0. Preface
-
This article does not care how to convert the yolov5 model to ncnn form
- In all likelihood, it was converted with onnx2ncnn, but the relevant information was not checked
-
Run NCNN Yolov5 example
- In fact, according to comments in an address to this download yolov5 related files, to save
/path/to/ncnn/examples
in. - After
/path/to/ncnn/examples
running../build/examples/yolov5 /path/to/image.jpg
it through OpenCV display test results.
- In fact, according to comments in an address to this download yolov5 related files, to save
-
The follow-up content of this article mainly includes:
- Yolov5 model construction and weight import
- Yolov5 model reasoning
- Post-processing of test results: familiarize yourself with OpenCV
1. Model construction and weight import
- Model building and importing the source code is unremarkable, just
detect_yolov5
the following in the method- The actual work of ncnn's model construction and weight import is to create a blank Net object and import the model structure file (param) and weight file (bin)
- There may be some other operations, such as customizing Layer, that is,
register_custom_layer
operations
ncnn::Net yolov5;
yolov5.opt.use_vulkan_compute = true;
// yolov5.opt.use_bf16_storage = true;
yolov5.register_custom_layer("YoloV5Focus", YoloV5Focus_layer_creator);
// original pretrained model from https://github.com/ultralytics/yolov5
// the ncnn model https://github.com/nihui/ncnn-assets/tree/master/models
yolov5.load_param("yolov5s.param");
yolov5.load_model("yolov5s.bin");
2. Model Reasoning
-
Model reasoning includes several parts:
- Construct the model input and bind it to the model class (ie Net).
-
Model input construction, the main work includes
- Resize the image, let the long side be target_size, and the short side will change proportionally
- Perform pad operation to make the side length divisible by 32
- Define norm related
- Bind model input to model
// 获取当前图片的尺寸
int img_w = bgr.cols;
int img_h = bgr.rows;
// letterbox pad to multiple of 32
// 长边为 target_size,短边按比例变化
int w = img_w;
int h = img_h;
float scale = 1.f;
if (w > h)
{
scale = (float)target_size / w;
w = target_size;
h = h * scale;
}
else
{
scale = (float)target_size / h;
h = target_size;
w = w * scale;
}
// resize 图片
ncnn::Mat in = ncnn::Mat::from_pixels_resize(bgr.data, ncnn::Mat::PIXEL_BGR2RGB, img_w, img_h, w, h);
// 执行pad操作,令图片尺寸可以被32整除
// pad to target_size rectangle
// yolov5/utils/datasets.py letterbox
int wpad = (w + 31) / 32 * 32 - w;
int hpad = (h + 31) / 32 * 32 - h;
ncnn::Mat in_pad;
// 实现pad操作
ncnn::copy_make_border(in, in_pad, hpad / 2, hpad - hpad / 2, wpad / 2, wpad - wpad / 2, ncnn::BORDER_CONSTANT, 114.f);
// norm 操作参数
const float norm_vals[3] = {
1 / 255.f, 1 / 255.f, 1 / 255.f};
in_pad.substract_mean_normalize(0, norm_vals);
ncnn::Extractor ex = yolov5.create_extractor();
// 设置模型输入
ex.input("images", in_pad);
- Perform model reasoning, the main functions include
- Build bbox based on model results, anchors and other parameters
- Implement NMS
- Convert bbox size to original image size
// yolov5 的输出由3个特征图生成,即下面的 stride 8/16/32
// 每个部分都是根据 anchors 和输出结果构建最终预测结果(即bbox)
// 预测结果都保存到 proposals 中,通过 Object 对象保存
// struct Object
// {
// cv::Rect_<float> rect;
// int label;
// float prob;
// };
// anchor setting from yolov5/models/yolov5s.yaml
// stride 8
{
ncnn::Mat out;
ex.extract("output", out);
ncnn::Mat anchors(6);
anchors[0] = 10.f;
anchors[1] = 13.f;
anchors[2] = 16.f;
anchors[3] = 30.f;
anchors[4] = 33.f;
anchors[5] = 23.f;
std::vector<Object> objects8;
generate_proposals(anchors, 8, in_pad, out, prob_threshold, objects8);
proposals.insert(proposals.end(), objects8.begin(), objects8.end());
}
// stride 16
{
ncnn::Mat out;
ex.extract("781", out);
ncnn::Mat anchors(6);
anchors[0] = 30.f;
anchors[1] = 61.f;
anchors[2] = 62.f;
anchors[3] = 45.f;
anchors[4] = 59.f;
anchors[5] = 119.f;
std::vector<Object> objects16;
generate_proposals(anchors, 16, in_pad, out, prob_threshold, objects16);
proposals.insert(proposals.end(), objects16.begin(), objects16.end());
}
// stride 32
{
ncnn::Mat out;
ex.extract("801", out);
ncnn::Mat anchors(6);
anchors[0] = 116.f;
anchors[1] = 90.f;
anchors[2] = 156.f;
anchors[3] = 198.f;
anchors[4] = 373.f;
anchors[5] = 326.f;
std::vector<Object> objects32;
generate_proposals(anchors, 32, in_pad, out, prob_threshold, objects32);
proposals.insert(proposals.end(), objects32.begin(), objects32.end());
}
// 根据score对所有proposals排序
// sort all proposals by score from highest to lowest
qsort_descent_inplace(proposals);
// 执行NMS
// apply nms with nms_threshold
std::vector<int> picked;
nms_sorted_bboxes(proposals, picked, nms_threshold);
// resize 所有bbox到原始尺寸
int count = picked.size();
objects.resize(count);
for (int i = 0; i < count; i++)
{
objects[i] = proposals[picked[i]];
// adjust offset to original unpadded
float x0 = (objects[i].rect.x - (wpad / 2)) / scale;
float y0 = (objects[i].rect.y - (hpad / 2)) / scale;
float x1 = (objects[i].rect.x + objects[i].rect.width - (wpad / 2)) / scale;
float y1 = (objects[i].rect.y + objects[i].rect.height - (hpad / 2)) / scale;
// clip
x0 = std::max(std::min(x0, (float)(img_w - 1)), 0.f);
y0 = std::max(std::min(y0, (float)(img_h - 1)), 0.f);
x1 = std::max(std::min(x1, (float)(img_w - 1)), 0.f);
y1 = std::max(std::min(y1, (float)(img_h - 1)), 0.f);
objects[i].rect.x = x0;
objects[i].rect.y = y0;
objects[i].rect.width = x1 - x0;
objects[i].rect.height = y1 - y0;
}
3. Post-processing of test results
- In fact, it is to use OpenCV to draw bbox, mainly the two functions of rectangle and putText
cv::Mat image = bgr.clone();
for (size_t i = 0; i < objects.size(); i++)
{
const Object& obj = objects[i];
fprintf(stderr, "%d = %.5f at %.2f %.2f %.2f x %.2f\n", obj.label, obj.prob,
obj.rect.x, obj.rect.y, obj.rect.width, obj.rect.height);
cv::rectangle(image, obj.rect, cv::Scalar(255, 0, 0));
char text[256];
sprintf(text, "%s %.1f%%", class_names[obj.label], obj.prob * 100);
int baseLine = 0;
cv::Size label_size = cv::getTextSize(text, cv::FONT_HERSHEY_SIMPLEX, 0.5, 1, &baseLine);
int x = obj.rect.x;
int y = obj.rect.y - label_size.height - baseLine;
if (y < 0)
y = 0;
if (x + label_size.width > image.cols)
x = image.cols - label_size.width;
cv::rectangle(image, cv::Rect(cv::Point(x, y), cv::Size(label_size.width, label_size.height + baseLine)),
cv::Scalar(255, 255, 255), -1);
cv::putText(image, text, cv::Point(x, y + label_size.height),
cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 0, 0));
}
cv::imshow("image", image);
cv::waitKey(0);