本篇博客記錄了一個深度學習在工業領域的應用項目。功能是檢測視野範圍內的零件總數,如果數量少於設定的標準數量,則報警,如果放置了不同型號的零件,同樣需要報警。常規方法是用傳統的圖像處理的模板匹配,但使用halcon和opencv的模板匹配效果都不好,於是嘗試用深度學習目標檢測。
效果如下圖所示:識別率超過99%(可以獲取到目標的個數,類別,概率,矩形框位置,可以適應一定的光照、角度、大小變化)
目錄:
1.安裝darknet yolov3環境
2.採集並製作數據集,用yolov3訓練
3.在opencv3.4版本使用訓練好的模型、
4.在vs裏編寫軟件
正文:
1.yolov3環境搭建參考另一篇博客https://blog.csdn.net/sinat_41852207/article/details/90906309
我的編譯環境是yolov3 win10 cuda8.0 vs2017
2.採集並製作數據集,用yolov3訓練
2.1 如何製作數據集和一些工程經驗
參考:數據集構造流程https://blog.csdn.net/u011574296/article/details/78953681
文件夾存放的是xml格式的標籤文件,每個xml文件都對應於JPEGImages文件夾的一張圖片,同名
Action存放的是人的動作,我們暫時不用;Layout存放的人體部位的數據。我們暫時不用
Main存放的是圖像物體識別的數據,分爲20類,當然我們自己製作就不一定了, Main裏面有test.txt , train.txt, val.txt ,trainval.txt.這四個文件我們後面會生成
1)把你的圖片放到JPEGSImages裏面,在VOC2007裏面,人家的圖片文件名都是000001.jpg類似這樣的,我們也統一格式,把我們的圖片名字重命名成這樣的,如果你的文件太多怎麼辦,請看另一篇文章http://blog.csdn.net/gaohuazhao/article/details/60324715 能批量重命名文件
網上很多教程,但是我覺得都很麻煩,可以下載精靈標註助手,手動標註,會自動生成圖片信息的xml文件
1)一張張的慢慢畫框。。。。。。。。。大約過了幾個小時,好繼續下一步
2)保存的路徑就是我們的Annatations文件夾,別保存別的地方去了,,,
第四步:搞定ImageSets文件夾中的Main文件夾中的四個文件(這四個txt文檔是幹嘛的,看名字就知道,就是分分多少圖片作爲訓練,多少圖片作爲測試)
原文:https://blog.csdn.net/gaohuazhao/article/details/60871886
用這個python腳本生成四個txt文件(隨機分配訓練集、驗證集、測試集),於ImageSets/Main中。
經驗總結:由於工業中採集的圖片非常單一,零件總是位於同一背景下,數據的單一使得訓練的模型容易過於簡化,很容易誤識別。舉個例子就是如果訓練貓的時候,總是將貓放到綠色的草地上,模型可能認爲草地上只要有一坨東西,就是貓。這樣訓練的結果可能是,放一隻狗到草地上,模型可能也會認爲是貓。所以訓練的時候,訓練集一定不能太單一,訓練圖片中除了零件,還要改變零件所在的背景,比如添加一些干擾物體,這樣訓練的模型誤識別率纔會降低。
2.2 使用yolov3訓練自己的數據集,並測試
這部分見這篇博客:https://mp.csdn.net/postedit
我用了300張左右的圖片訓練,總共迭代2萬次,batchsize爲8。在迭代1萬次左右後已經收斂的差不多了,2萬次迭代後,loss值收斂到0.2左右。
如果難以收斂,考慮(1)有沒有過多髒數據(標註錯誤的數據)(2)嘗試降低學習率。
如果訓練收斂了,但實際測試的時候,有誤識別,考慮在訓練的時候增加干擾物,在物體周邊增加多種不相關物體。
如果訓練收斂了,但實際測試的時候有漏識別,考慮(1)增加訓練圖片數量,訓練集應該包含一些光照、角度、位置的變化,增強泛化性能。(2)訓練的時候,loss曲線是否收斂的不夠接近0。我的loss最終爲0.2左右,如果太大,說明不夠收斂,需要在訓練到瓶頸的時候減小學習率。
3 在opencv中調用訓練好的模型,進行目標識別
把裏面的路徑改成自己的就可以
//在debug模式下沒有優化,要在release下運行 速度快
#include <fstream>
#include <sstream>
#include <iostream>
#include <opencv2/dnn.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include<vector>
using namespace std;
using namespace cv;
using namespace dnn;
vector<string> classes;
vector<String> getOutputsNames(Net&net);
void drawPred(int classId, float conf, int left, int top, int right, int bottom, Mat& frame);
void postprocess(Mat& frame, const vector<Mat>& outs, float confThreshold, float nmsThreshold);
int main()
{
string names_file = "D:/software_engineer/darknet/darknet/cfg/voc.name";
String model_def = "D:/software_engineer/darknet/darknet/cfg/yolov3.cfg";
String weights = "D:/software_engineer/darknet/darknet/backup/yolov3_last.weights";
int in_w, in_h;
double thresh = 0.5;//閾值
double nms_thresh = 0.25;
in_w = in_h = 416;
//read names
ifstream ifs(names_file.c_str());
string line;
while (getline(ifs, line))
classes.push_back(line);
//init model
Net net1 = readNetFromDarknet(model_def, weights);
net1.setPreferableBackend(DNN_BACKEND_DEFAULT);
net1.setPreferableTarget(DNN_TARGET_CPU);
Net net2 = readNetFromDarknet(model_def, weights);
net2.setPreferableBackend(DNN_BACKEND_DEFAULT);
net2.setPreferableTarget(DNN_TARGET_CPU);
//read image and forward
Mat inputImg, blob;
inputImg = imread("D:/測試3/1.jpg");//待檢圖片
if (inputImg.empty())
{
cout << "can't find image" << endl;
waitKey(0);
}
//capture >> inputImg;
blobFromImage(inputImg, blob, 1 / 255.0, Size(in_w, in_h), Scalar(), true, false);
vector<Mat> mat_blob;
imagesFromBlob(blob, mat_blob);
//Sets the input to the network
net1.setInput(blob);
// Runs the forward pass to get output of the output layers
vector<Mat> outs;
net1.forward(outs, getOutputsNames(net1));
postprocess(inputImg, outs, thresh, nms_thresh);
vector<double> layersTimes;
double freq = getTickFrequency() / 1000;
double t = net1.getPerfProfile(layersTimes) / freq;
string label = format("Inference time for a frame : %.2f ms", t);
putText(inputImg, label, Point(0, 15), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 0, 255));
namedWindow("res", WINDOW_NORMAL);
imshow("res", inputImg);
waitKey(0);
}
vector<String> getOutputsNames(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;
}
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(255, 178, 50), 3);
//Get the label for the class name and its confidence
string label = format("%.5f", conf);
if (!classes.empty())
{
CV_Assert(classId < (int)classes.size());
label = classes[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);
rectangle(frame, Point(left, top - round(1.5*labelSize.height)), Point(left + round(1.5*labelSize.width), top + baseLine), Scalar(255, 255, 255), FILLED);
putText(frame, label, Point(left, top), FONT_HERSHEY_SIMPLEX, 0.75, Scalar(0, 0, 0), 1);
}
void postprocess(Mat& frame, const vector<Mat>& outs, float confThreshold, float nmsThreshold)
{
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;
NMSBoxes(boxes, confidences, confThreshold, nmsThreshold, indices);
size_t i;
for (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);
}
cout << "目標數量數量:" << i << endl;
}
最終測試,1500張圖片,漏識別零件1個,沒有誤識別,就是沒有零件的地方和不同型號的零件一定不會被識別出來。這樣就達到了檢測目的。