火焰检测c++opencv
时间: 2023-11-15 14:04:58 浏览: 194
火焰检测是指通过图像处理技术来检测图像中是否存在火焰。在C++中,可以使用OpenCV库来实现火焰检测。可以采用YOLO4TINY的模型来进行检测,该模型具有移植性好、速度快等优点。以下是实现火焰检测的步骤:
```C++
// 1. 导入OpenCV库
#include <opencv2/opencv.hpp>
using namespace cv;
int main()
{
// 2. 读取图像
Mat image = imread("fire.jpg");
// 3. 创建YOLO4TINY模型
dnn::Net net = dnn::readNetFromDarknet("yolov4-tiny.cfg", "yolov4-tiny.weights");
net.setPreferableBackend(dnn::DNN_BACKEND_OPENCV);
net.setPreferableTarget(dnn::DNN_TARGET_CPU);
// 4. 获取输出层名称
std::vector<String> names;
std::ifstream ifs("coco.names");
std::string line;
while (std::getline(ifs, line)) names.push_back(line);
// 5. 进行目标检测
Mat blob = dnn::blobFromImage(image,1 / 255.0, Size(416, 416), Scalar(), true, false);
net.setInput(blob);
std::vector<Mat> outs;
net.forward(outs, net.getUnconnectedOutLayersNames());
std::vector<int> classIds;
std::vector<float> confidences;
std::vector<Rect> boxes;
for (size_t i = 0; i < outs.size(); ++i)
{
// 获取每个输出层的信息
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;
minMaxLoc(scores, 0, &confidence, 0, &classIdPoint);
if (confidence > 0.5)
{
int centerX = (int)(data[0] * image.cols);
int centerY = (int)(data[1] * image.rows);
int width = (int)(data[2] * image.cols);
int height = (int)(data[3] * image.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));
}
}
}
// 6. 绘制检测结果
std::vector<int> indices;
dnn::NMSBoxes(boxes, confidences, 0.5, 0.4, indices);
for (size_t i = 0; i < indices.size(); ++i)
{
int idx = indices[i];
Rect box = boxes[idx];
int classId = classIds[idx];
float confidence = confidences[idx];
Scalar color = Scalar(0, 0, 255);
rectangle(image, box, color, 2);
String label = format("%s: %.2f", (const char*)names[classId].c_str(), confidence);
int baseLine;
Size labelSize = getTextSize(label, FONT_HERSHEY_SIMPLEX, 0.5, 1, &baseLine);
rectangle(image, Point(box.x, box.y - labelSize.height - baseLine), Point(box.x + labelSize.width, box.y), color, FILLED);
putText(image, label, Point(box.x, box.y - baseLine), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255, 255, 255));
}
// 7. 显示检测结果
imshow("Fire Detection", image);
waitKey(0);
return 0;
}
```
相关问题:
阅读全文