基本上,您可以计算轮廓区域并获取参考区域。所以,你可以限制你想要的轮廓。之后,您可以选择相关的投资回报率。
您可以使用以下代码:
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
#include <iostream>
using namespace cv;
using namespace std;
Mat src_gray;
int thresh = 100;
RNG rng(12345);
void thresh_callback(int, void *);
int main(int argc, char **argv)
{
Mat src = imread("../input/eyes.png");
if (src.empty())
{
cout << "Could not open or find the image!\n"
<< endl;
cout << "Usage: " << argv[0] << " <Input image>" << endl;
return -1;
}
cvtColor(src, src_gray, COLOR_BGR2GRAY);
blur(src_gray, src_gray, Size(5, 5));
const char *source_window = "Source";
namedWindow(source_window);
imshow(source_window, src);
const int max_thresh = 255;
createTrackbar("Canny thresh:", source_window, &thresh, max_thresh, thresh_callback);
thresh_callback(0, 0);
waitKey();
return 0;
}
void thresh_callback(int, void *)
{
Mat canny_output;
Canny(src_gray, canny_output, thresh, thresh * 2);
vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
findContours(canny_output, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE);
Mat drawing = Mat::zeros(canny_output.size(), CV_8UC3);
cv::Mat roi1, roi2;
int count = 0;
for (size_t i = 0; i < contours.size(); i++)
{
if (contourArea(contours[i]) > 1300)
{
count++;
std::cout << " Area: " << contourArea(contours[i]) << std::endl;
Scalar color = Scalar(rng.uniform(0, 256), rng.uniform(0, 256), rng.uniform(0, 256));
drawContours(drawing, contours, (int)i, color, 2, LINE_8, hierarchy, 0);
Rect box = boundingRect(contours[i]);
std::cout << " Box: " << box << std::endl;
if (count == 1)
{
roi1 = src_gray(box);
}
else if (count == 2)
{
roi2 = src_gray(box);
}
}
}
std::cout << " " << std::endl;
imshow("Contours", drawing);
imshow("roi1", roi1);
imshow("roi2", roi2);
}