Opencv 基于C++識別綠燈
**

基本思路
1.對inRange影像 獲取綠色像素點區域
2.對影像二值化處理
3.框選ROI區域
圖片:
帶尺寸的圖片:
甘特圖功能
整體代碼就是這樣:
#include <opencv4/opencv2/opencv.hpp>
#include <opencv4/opencv2/highgui/highgui.hpp>
#include <opencv4/opencv2/imgproc/imgproc.hpp>
#include<iostream>
#include <time.h>
using namespace cv;
using namespace std;
clock_t start,finish;
Mat srcImage;
vector<Vec3f>circles;
Mat templateImage;
Mat resultImage;
//void processFrame(Mat& img, Rect& rect);//繪制外接矩形
double area=0.0;
void processFrame(Mat & img, Rect & rect)
{
//尋找外接輪廓
vector<vector<Point>>contours;
vector<Vec4i>hierarchy;
findContours(img, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point(-1, -1));
if (contours.size() > 0)
{
for (size_t i = 0; i < contours.size(); i++)
{
double contours_Area = contourArea(contours[static_cast<int>(i)]);//面積
rect = boundingRect(contours[static_cast<int>(i)]);//外接矩形
if (contours_Area > area)
{
area = contours_Area;
}
}
}
else
{
rect.x = rect.y = rect.width = rect.height = 0;
}
}
int main(int argc, char** argv)
{
Rect roi;//存盤最大外接矩形的資料
VideoCapture capture;
capture.open(2);
if (!capture.isOpened())
{
cout << "影像讀取錯誤!~" << endl;
return -1;
}
Mat frame,dst;
int Number_of_successful=-1;
int number=-1;
Mat kernel = getStructuringElement(MORPH_RECT, Size(3, 3), Point(-1, -1));
Mat kernel_dilite = getStructuringElement(MORPH_RECT, Size(7, 7), Point(-1, -1));
while (capture.read(frame))
{
start = clock();
//篩選出綠色
inRange(frame, Scalar(0, 127, 0), Scalar(120, 255, 120), dst);
//開操作去噪點
morphologyEx(dst, dst, MORPH_OPEN, kernel, Point(-1, -1), 1);
//膨脹操作把綠燈具體化的顯示出來
dilate(dst, dst, kernel_dilite, Point(-1, -1), 2);
imshow("output video", dst);
processFrame(dst, roi);
rectangle(frame, roi, Scalar(0, 0, 255), 3, 8, 0);
if(area>=800) //根據距離調引數 (800)
{
cout<<"綠燈完成"<<endl;
cout<<"開始啟動"<<endl;
}
finish= clock();
double Frame1 = 1000/(double(finish-start)/CLOCKS_PER_SEC*1000);
// cout<<"演算法進行時間為:"<<time<<endl;
// cout<<"視覺識別幀率為:"<<Frame<<endl;
std::string str = std::to_string(Frame1);
string Frame_name = "FPS:";
Frame_name +=str;
//cout<<"視覺識別幀率為:"<<Frame_name<<endl;
putText(frame,Frame_name,Point(0,50),FONT_HERSHEY_COMPLEX,1,Scalar(0,0,255));
imshow("input video", frame);
char c = waitKey(50);
if (c == 27)
{
break;
}
}
capture.release();
waitKey(0);
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/435424.html
標籤:AI
下一篇:ResNet網路 殘差塊的作用
