标记蓝色区域的外部轮廓
这里简单记录一下轮廓的提取,便于以后需要时查找。
#include <opencv2/core/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
using namespace std;
int main(int argc, char **argv)
{
cv::Mat img = cv::imread("./3.JPG");
if(img.empty())
{
cout << "CANNOT LOAD!" << endl;
return -1;
}
cv::Mat image;
image = img.clone();
int height = image.rows;
int width = image.cols;
for(int row = 0; row < height; row++)
{
for(int col = 0; col < width; col++)
{
if(image.at<cv::Vec3b>(row, col)[2] >= 50){
if(image.at<cv::Vec3b>(row, col)[1] <= 50){
image.at<cv::Vec3b>(row, col)[0] = 255;
image.at<cv::Vec3b>(row, col)[1] = 0;
image.at<cv::Vec3b>(row, col)[2] = 0;
}
}
}
}
cv::Mat img_gray, output_bin;
cv::cvtColor(image, img_gray, CV_BGR2GRAY);
cv::threshold(img_gray, output_bin, 50, 255, CV_THRESH_BINARY_INV);
vector<vector<cv::Point>> contours;
vector<vector<cv::Point>> contours_max;
vector<cv::Vec4i> hierarchy;
cv::findContours(output_bin, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
int size = 0;
int index = 0;
int number = 0;
for(int i = 0; i < contours.size(); i++)
{
number = contours[i].size();
if(number > size){
size = number;
index = i;
}
}
cout << "The current largest contours is " << index <<"; Size : "<< size << endl;
contours_max.push_back(contours[index]);
int itv = 0;
int rem = size%64;
if(rem == 0){
itv = size/64;
}
if(rem != 0){
itv = (size - rem)/64;
}
cout << "The sample spacing is : "<< itv <<endl;
int j = 0;
vector<cv::Point> points;
while(j < (itv*64))
{
cv::Point P = contours[index][j];
points.push_back(P);
j += itv;
}
cout << "The number of points : "<< points.size() <<endl;
cout << points << endl;
cv::drawContours(img, contours_max, -1, cv::Scalar(0, 0, 255), 2);
for(int i = 0; i < points.size(); i++)
{
cv::Point P = points[i];
cv::circle(img, P, 5, cv::Scalar(255, 255, 255));
}
cv::imshow("image", img);
cv::waitKey();
return 0;
}
原图:
标记后:
|