对象提取,简而言之就是获取指定图像,去除其他图像.
解决思路
二值处理 + 形态学处理(开运算+闭运算,轮廓发现) + 横纵比过滤计算 .
#include
#include
#include
#include
#include
#include
using namespace cv;
using namespace std;
Mat src,binary,dst;
int main()
{
src = imread("E:\\Users\\opencvCoder\\image\\yuan.png", IMREAD_GRAYSCALE);
if (src.empty())
{
printf("could not load image...\n");
return -1;
}
namedWindow("input image", WINDOW_AUTOSIZE);
imshow("input image", src);
threshold(src, binary, 0, 255, THRESH_BINARY | THRESH_OTSU);
imshow("binary image", binary);
Mat kernel = getStructuringElement(MORPH_RECT, Size(3, 3), Point(-1, -1));
morphologyEx(binary, dst, MORPH_CLOSE, kernel, Point(-1, -1));
imshow("close image", dst);
kernel = getStructuringElement(MORPH_RECT, Size(3, 3), Point(-1, -1));
morphologyEx(binary, dst, MORPH_OPEN, kernel, Point(-1, -1));
imshow("open image", dst);
vector<vector<Point>>contours;
vector<Vec4i>hireachy;
findContours(dst, contours, hireachy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point());
Mat resultImage = Mat::zeros(src.size(), CV_8UC3);
for (size_t t = 0; t < contours.size(); t++)
{
double area = contourArea(contours[t]);
if (area < 100) continue;
Rect rect = boundingRect(contours[t]);
float ratio = float(rect.width) / float(rect.height);
if (ratio < 1.1 && ratio>0.9)
{
drawContours(resultImage, contours, t, Scalar(0, 0, 255), 2, 8, Mat(), 0, Point());
printf("circle area:%f\n", area);
printf("circle length:%f\n", arcLength(contours[t],true));
}
}
imshow("result image", resultImage);
vector<Vec3f>myCircles;
Mat gray_result;
cvtColor(resultImage, gray_result, COLOR_BGR2GRAY);
HoughCircles(gray_result, myCircles, HOUGH_GRADIENT, 1, 10,100,30,10,gray_result.rows/4);
Mat circleImage = src.clone();
cvtColor(circleImage, circleImage, COLOR_GRAY2BGR);
for (int i = 0; i < myCircles.size(); i++)
{
Vec3f circleInfo = myCircles[i];
circle(circleImage, Point(circleInfo[0], circleInfo[1]),circleInfo[2], Scalar(0, 0, 255), 2, 8, 0);
}
imshow("Final Result", circleImage);
waitKey(0);
return 0;
}