OpenCV4.4开始支持YOLOv4模型的调用,需要使用Opencv的DNN模块。
编译安装OpenCV和OpenCV-contrib库步骤,点此链接
C++ OpenCV调用YOLO模型的完整代码点此下载
constexpr const char *darknet_cfg = "../face/yolov3-tiny.cfg";//网络文件
constexpr const char *darknet_weights = "../face/yolov3-tiny.weights";//模型文件
// 加载模型
cv::dnn::Net net = cv::dnn::readNetFromDarknet(darknet_cfg, darknet_weights);
//下面两行在使用CUDA检测时使用
net.setPreferableBackend(dnn::DNN_BACKEND_CUDA);
net.setPreferableTarget(dnn::DNN_TARGET_CUDA);
//下面一行在使用CPU检测时使用
//net.setPreferableTarget(dnn::DNN_TARGET_CPU);
constexpr const char *darknet_names = "../face/face.names"; //类别文件
std::vector<std::string> class_labels ;//类标签
// 加载标签集
//std::vector classLabels;
ifstream classNamesFile(darknet_names);
if (classNamesFile.is_open())
{
string className = "";
while (std::getline(classNamesFile, className))
class_labels.push_back(className);
}
// 读取待检测图片
cv::Mat img = cv::imread(image_path);
cv::Mat blob = cv::dnn::blobFromImage(img, 1.0 / 255.0, { inpWidth, inpHeight }, 0.00392, true);
net.setInput(blob);
// 检测
vector<Mat> detectionMat;
net.forward(detectionMat, getOutputsNames(net));// 6 845 1 W x H x C
//移除置信度低的box
postprocess(img, detectionMat);
// Get the names of the output layers
vector<String> getOutputsNames(const dnn::Net& net)
{
static vector<String> names;
if (names.empty())
{
//Get the indices of the output layers, i.e. the layers with unconnected outputs
vector<int> outLayers = net.getUnconnectedOutLayers();
//get the names of all the layers in the network
vector<String> layersNames = net.getLayerNames();
// Get the names of the output layers in names
names.resize(outLayers.size());
for (size_t i = 0; i < outLayers.size(); ++i)
names[i] = layersNames[outLayers[i] - 1];
}
return names;
}
// Draw the predicted bounding box
void drawPred(int classId, float conf, int left, int top, int right, int bottom, Mat& frame)
{
//Draw a rectangle displaying the bounding box
rectangle(frame, Point(left, top), Point(right, bottom), Scalar(0, 0, 255));
//Get the label for the class name and its confidence
string label = format("%.2f", conf);
if (!class_labels.empty())
{
//assert(classId < (int)classes.size());
label = class_labels[classId] + ":" + label;
}
//Display the label at the top of the bounding box
int baseLine;
Size labelSize = getTextSize(label, FONT_HERSHEY_SIMPLEX, 0.5, 1, &baseLine);
top = max(top, labelSize.height);
putText(frame, label, Point(left, top), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255, 255, 255));
}
// Remove the bounding boxes with low confidence using non-maxima suppression
void postprocess(Mat& frame, const vector<Mat>& outs)
{
vector<int> classIds;
vector<float> confidences;
vector<Rect> boxes;
for (size_t i = 0; i < outs.size(); ++i)
{
// Scan through all the bounding boxes output from the network and keep only the
// ones with high confidence scores. Assign the box's class label as the class
// with the highest score for the box.
float* data = (float*)outs[i].data;
for (int j = 0; j < outs[i].rows; ++j, data += outs[i].cols)
{
Mat scores = outs[i].row(j).colRange(5, outs[i].cols);
Point classIdPoint;
double confidence;
// Get the value and location of the maximum score
minMaxLoc(scores, 0, &confidence, 0, &classIdPoint);
if (confidence > confThreshold)
{
int centerX = (int)(data[0] * frame.cols);
int centerY = (int)(data[1] * frame.rows);
int width = (int)(data[2] * frame.cols);
int height = (int)(data[3] * frame.rows);
int left = centerX - width / 2;
int top = centerY - height / 2;
classIds.push_back(classIdPoint.x);
confidences.push_back((float)confidence);
boxes.push_back(Rect(left, top, width, height));
}
}
}
// Perform non maximum suppression to eliminate redundant overlapping boxes with
// lower confidences
vector<int> indices;
dnn::NMSBoxes(boxes, confidences, confThreshold, nmsThreshold, indices);
for (size_t i = 0; i < indices.size(); ++i)
{
int idx = indices[i];
Rect box = boxes[idx];
drawPred(classIds[idx], confidences[idx], box.x, box.y,
box.x + box.width, box.y + box.height, frame);
}
}