代码
#include<opencv2/opencv.hpp>
#include <iostream>
#include<string>
using namespace std;
using namespace cv;
int main()
{
int i = 0;
Mat frame1;
// VideoCapture capture(0);
//if (!capture.isOpened()) return 0;
while(1)
{
// capture >> frame1;
// imshow("pic", frame1);
Mat frame1 = imread("0.jpg");
Mat dst1;
inRange(frame1, Scalar(30, 30, 130), Scalar(82, 79, 209), dst1);
Mat element = getStructuringElement(MORPH_RECT, Size(3, 3));
morphologyEx(dst1, dst1, MORPH_OPEN, element);//开运算
morphologyEx(dst1, dst1, MORPH_CLOSE, element);//闭运算
vector<vector<Point>>contours1;
// imshow("pic", dst1);
// waitKey(0);
findContours(dst1, contours1, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point(0, 0));
vector<Rect> boundRect1(contours1.size()); //包围点集的最小矩形vector
// if (contours1.size() == 0) waitKey(0);
for (int i = 0; i < contours1.size(); i++)
{
boundRect1[i] = boundingRect(Mat(contours1[i]));
cout << boundRect1[i].x << " " << boundRect1[i].y << endl << boundRect1[i].x << " " << boundRect1[i].y + boundRect1[i].height << endl;
cout << boundRect1[i].x + boundRect1[i].width << " " << boundRect1[i].y << endl;
boundRect1[i] = boundingRect(Mat(contours1[i])); //计算并返回包围轮廓点集的最小矩形
rectangle(frame1 , boundRect1[i].tl(), boundRect1[i].br(), Scalar(190, 50, 0), 2, 8, 0);
}
drawContours(frame1, contours1, -1, Scalar(255, 0, 0), 10);
imshow("srcpic", frame1);
waitKey(0);
// char a = waitKey(30);
/* if (a == 's')
{
string Img_Name = to_string(i++) + ".jpg";
imwrite(Img_Name, frame1);
}
if (a == 'q') break;
*/
}
return 0;
}
分析
主要是设一个Videocapture