<textarea readonly="readonly" name="code" class="c++">
#include<opencv2/opencv.hpp>
#include<iostream>
using namespace cv;
using namespace std;
Mat src, dst;
int main(int argc, char** argv)
{
src = imread("E:/picture/case3.jpg", IMREAD_GRAYSCALE);
imshow("Input image", src);
//xingtaixue 闭操作把区域连起来
threshold(src, src, 0, 255, THRESH_BINARY | THRESH_OTSU);
Mat morph_img;
Mat kernel1 = getStructuringElement(MORPH_RECT, Size(3,3), Point(-1, -1));
morphologyEx(src, morph_img, MORPH_CLOSE, kernel1, Point(-1, -1));
//imshow("erod_image", morph_img);
//开把小白色区域去掉
Mat kernel2 = getStructuringElement(MORPH_RECT, Size(3, 3), Point(-1, -1));
morphologyEx(morph_img, morph_img, MORPH_OPEN, kernel1, Point(-1, -1));
imshow("erod_image", morph_img);
// find contours
Mat resultimg = Mat:: zeros(src.size(), CV_8UC3);
vector<vector<Point>> contours;
vector<Vec4i> hireachy;
findContours(morph_img,contours,hireachy,RETR_TREE,CHAIN_APPROX_SIMPLE);
Point cricle_point;
//面积过滤
for (size_t k = 0; k < contours.size(); k++)
{
double area = contourArea(contours[k]);
if (area < 100)
continue;
Rect rect = boundingRect(contours[k]);
//横纵比过滤
float ratio = float(rect.width) / float(rect..height);
if (ratio<1.1&&ratio>0.9)
{
drawContours(resultimg, contours, k, Scalar(0, 0, 255), 1, 8);
}
}
imshow("Outimage", resultimg);
waitKey(0);
return 0;
}
</textarea>