我有这个代码来绘制运行视频帧的轮廓。
vector<vector<cv::Point>> contours;
Mat canny_output;
vector<Vec4i> hierarchy;
/// Detect edges using canny
Canny(src, canny_output, thresh, thresh * 2, 3);
/// Find contours
findContours(canny_output, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE);
sort(contours.begin(), contours.end(), compareContourAreas);
/// Draw contours
Mat drawing = Mat::zeros(canny_output.size(), CV_8UC3);
cv::Scalar colors[3];
colors[0] = cv::Scalar(255, 255, 255);
colors[1] = cv::Scalar(255, 255, 255);
colors[2] = cv::Scalar(255, 255, 255);
for (int i = contours.size()-3; i < contours.size(); i++)
{
drawContours(drawing, contours, i, colors[i % 3]);
}
/* Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));
drawContours(drawing, contours, i, color, 2, 8, hierarchy, 0);*/
imshow("Contours", drawing);
我过滤了轮廓,在屏幕上画出最大的3,忽略其余的。 我需要找出这三个中有多少个轮廓出现在屏幕上,我怎么做呢? 例如,如果只有2个轮廓显示在屏幕上,则变量存储为2,如果所有3个轮廓都出现了,则变量存储为3,依此类推。
您正在尝试使用这篇文章中提到的代码。 这个是关于等高线区域的,但看起来像是你试图对它们的长度进行排序。
下面是代码,我将所有轮廓的大小(按像素计算的长度)分配给一个数组,并对该数组进行排序。 然后重新绘制图片中最大的3个轮廓。
代码:
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
using namespace std;
using namespace cv;
int main()
{
int thresh = 100;
Mat src = imread("/ur/img/directory/flower.jpeg");
medianBlur(src,src,5) ;
vector<vector<cv::Point>> contours;
Mat canny_output;
vector<Vec4i> hierarchy;
/// Detect edges using canny
Canny(src, canny_output, thresh, thresh * 2, 3);
/// Find contours
findContours(canny_output, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE);
/// Draw contours
Mat drawing_all = Mat::zeros(canny_output.size(), CV_8UC3);
Mat drawing_biggest_3 = Mat::zeros(canny_output.size(), CV_8UC3);
vector<int> contour_sizes;
for (int i = 0; i < contours.size(); i++)
{
contour_sizes.push_back(contours[i].size());
drawContours(drawing_all, contours, i, Scalar(255,255,255));
}
std::sort(contour_sizes.begin(),contour_sizes.end());
for (int i = 0; i < contours.size(); i++)
{
if(contours[i].size()==contour_sizes[contour_sizes.size()-1] || contours[i].size()==contour_sizes[contour_sizes.size()-2]
|| contours[i].size()==contour_sizes[contour_sizes.size()-3])
drawContours(drawing_biggest_3, contours, i, Scalar(255,255,255));
}
imshow("Contours All", drawing_all);
imshow("Contours Biggest", drawing_biggest_3);
waitKey(0);
return 0;
}
输入图像示例:
发现的所有国家:
最大3个等高线