毕设之Opencv批量圆拟合
程序思路:编写read_csv()函数读取图片目录下txt文档,获取各BMP文件绝对路径以及对应圆的圆心坐标、半径参数。读取各BMP图像,转为灰度图,二值化后检测轮廓,然后检测最小圆;并将检测结果和实际结果存入txt文档。
不需调参;对于完美圆的检测优于霍夫圆变换。
功能小结:
1、read_csv()函数
void read_csv(string&csvPath, vector<String>&CirclePath, vector<int>&Circle_x, vector<int>&Circle_y, vector<int>&Circle_r)
csvPath:txt路径
CirclePath:从txt中读取的bmp路径
Circle_x:bmp图像中圆的圆心x坐标
Circle_y:bmp图像中圆的圆心y坐标
Circle_r:bmp图像中圆的半径r
2、创建txt文本,并写入数据
#include <iostream>
#include <sstream>
#include <fstream>
ofstream file("filepath",ios::out);
if (file.is_open())
{
file <<;
}
file.close();
3、转化为灰度图
cvtColor(srcImage,midImage, COLOR_BGR2GRAY);//转化边缘检测后的图为灰度图
@paramsrc input image: 8-bit unsigned, 16-bit unsigned ( CV_16UC... ), orsingle-precision
floating-point.
@paramdst output image of the same size and depth as src.
@paramcode color space conversion code (see cv::ColorConversionCodes).
@paramdstCn number of channels in the destination image; if the parameter is 0, thenumber of the
channelsis derived automatically from src and code.
4、图像二值化Threshold()
函数 Threshold对单通道数组应用固定阈值操作。该函数的典型应用是对灰度图像进行阈值操作得到二值图像。(cvCmpS也可以达到此目的)或者是去掉噪声,例如过滤很小或很大像素值的图像点。本函数支持的对图像取阈值的方法由 threshold_type确定。
CV_EXPORTS_W double threshold( InputArray src,OutputArray dst,
double thresh, double maxval, int type );
/**@brief Applies a fixed-level threshold to each array element.
Thefunction applies fixed-level thresholding to a single-channel array. Thefunction is typically
usedto get a bi-level (binary) image out of a grayscale image ( cv::compare couldbe also used for
thispurpose) or for removing a noise, that is, filtering out pixels with too smallor too large
values.There are several types of thresholding supported by the function. They aredetermined by
typeparameter.
Also,the special values cv::THRESH_OTSU or cv::THRESH_TRIANGLE may be combined withone of the
abovevalues. In these cases, the function determines the optimal threshold valueusing the Otsu's
orTriangle algorithm and uses it instead of the specified thresh . The functionreturns the
computedthreshold value. Currently, the Otsu's and Triangle methods are implementedonly for 8-bit
images.
@paramsrc input array (single-channel, 8-bit or 32-bit floating point).
@paramdst output array of the same size and type as src.
@paramthresh threshold value.
@parammaxval maximum value to use with the THRESH_BINARY and THRESH_BINARY_INVthresholding
types.
@paramtype thresholding type (see the cv::ThresholdTypes).
@sa adaptiveThreshold, findContours, compare,min, max
*/
5、检索轮廓FindContours()
函数FindContours从二值图像中检索轮廓,并返回检测到的轮廓的个数。first_contour的值由函数填充返回,它的值将为第一个外轮廓的指针,当没有轮廓被检测到时为NULL。其它轮廓可以使用h_next和v_next连接,从first_contour到达。
CV_EXPORTS_W void findContours( InputOutputArray image,OutputArrayOfArrays contours,
OutputArray hierarchy, int mode,
int method,Point offset = Point());
/**@brief Finds contours in a binary image.
Thefunction retrieves contours from the binary image using the algorithm @citeSuzuki85 . The contours
area useful tool for shape analysis and object detection and recognition. Seesquares.c in the
OpenCVsample directory.
@noteSource image is modified by this function. Also, the function does not takeinto account
1-pixelborder of the image (it's filled with 0's and used for neighbor analysis in thealgorithm),
thereforethe contours touching the image border will be clipped.
@paramimage Source, an 8-bit single-channel image. Non-zero pixels are treated as1's. Zero
pixelsremain 0's, so the image is treated as binary . You can use compare , inRange ,threshold ,
adaptiveThreshold, Canny , and others to create a binary image out of a grayscale or color one.
Thefunction modifies the image while extracting the contours. If mode equals toRETR_CCOMP
orRETR_FLOODFILL, the input can also be a 32-bit integer image of labels(CV_32SC1).
@paramcontours Detected contours. Each contour is stored as a vector of points.
@paramhierarchy Optional output vector, containing information about the imagetopology. It has
asmany elements as the number of contours. For each i-th contour contours[i] ,the elements
hierarchy[i][0], hiearchy[i][1] , hiearchy[i][2] , and hiearchy[i][3] are set to 0-basedindices
incontours of the next and previous contours at the same hierarchical level, thefirst child
contourand the parent contour, respectively. If for the contour i there are no next,previous,
parent,or nested contours, the corresponding elements of hierarchy[i] will benegative.
@parammode Contour retrieval mode, see cv::RetrievalModes
@parammethod Contour approximation method, see cv::ContourApproximationModes
@paramoffset Optional offset by which every contour point is shifted. This is usefulif the
contoursare extracted from the image ROI and then they should be analyzed in the wholeimage
context.
*/
6、最小圆逼近minEnclosingCircle()
CV_EXPORTS_W void minEnclosingCircle(InputArray points,
CV_OUT Point2f& center, CV_OUT float& radius );
/**@brief Finds a circle of the minimum area enclosing a 2D point set.
Thefunction finds the minimal enclosing circle of a 2D point set using aniterative algorithm. See
theOpenCV sample minarea.cpp .
@parampoints Input vector of 2D points, stored in std::vector\<\> or Mat
@paramcenter Output center of the circle.
@paramradius Output radius of the circle.
*/
源码:
//--------------------------------------【程序说明】-------------------------------------------
// 程序描述: 利用霍夫变换检测圆
// 开发测试所用操作系统: Windows 7 64bit
// 开发测试所用IDE版本:VisualStudio 2015
// 开发测试所用OpenCV版本: 3.1
// 2015年5月 Created by @姬波林
// 2015年5月 Revised by @姬波林
//------------------------------------------------------------------------------------------------
//---------------------------------【头文件、命名空间包含部分】----------------------------
// 描述:包含程序所使用的头文件和命名空间
//------------------------------------------------------------------------------------------------
#include <opencv2/opencv.hpp>
#include <opencv2/imgproc/imgproc.hpp>
using namespace cv;
using namespace std;
#include <iostream>
#include <sstream>
#include <fstream>
//-----------------------------------【宏定义部分】--------------------------------------------
// 描述:定义一些辅助宏
//------------------------------------------------------------------------------------------------
//--------------------------------【全局函数声明部分】-------------------------------------
// 描述:全局函数声明
//-----------------------------------------------------------------------------------------------
void read_csv(string&csvPath, vector<String>&CirclePath, vector<int>&Circle_x, vector<int>&Circle_y, vector<int>&Circle_r)
{
string line, path, classLabel1, classLabel2, classLabel3;
ifstream file(csvPath.c_str(),ifstream::in);
while (getline(file, line))
{
stringstream lines(line);
getline(lines, path, '(');
getline(lines, classLabel1,',');
if (!classLabel1.empty())
{
Circle_x.push_back(atoi(classLabel1.c_str()));
}
getline(lines, classLabel2, ')');
if (!classLabel2.empty())
{
Circle_y.push_back(atoi(classLabel2.c_str()));
}
getline(lines, classLabel3, '.');
if (!classLabel3.empty())
{
Circle_r.push_back(atoi(classLabel3.c_str()));
}
if (!path.empty())
{
CirclePath.push_back(path+"("+ classLabel1+","+ classLabel2+")" + classLabel3+".bmp");
}
}
}
//-----------------------------------【ShowpText( )函数】----------------------------------
// 描述:输出一些帮助信息
//----------------------------------------------------------------------------------------------
void ShowText()
{
//输出程序说明
printf("绘制100个半径随机、圆心随机的圆,并保存为500X500BMP文件\n");
printf("存储位置:D:\\圆\n");
printf("命名规则:序号+圆心坐标+半径\n");
printf("当前使用的OpenCV版本为:"CV_VERSION );
printf("\n\n ----------------------------------------------------------------------------\n");
}
//---------------------------------------【main( )函数】--------------------------------------
// 描述:控制台应用程序的入口函数,我们的程序从这里开始执行
//-----------------------------------------------------------------------------------------------
const int kvalue = 15;//双边滤波邻域大小
int main()
{
//批量读入圆路径
string CircleCsvPath ="D:\\Circle\\at.txt";
vector<String> vecCirclePath;
vector<int> Circle_x, Circle_y, Circle_r;
read_csv(CircleCsvPath, vecCirclePath,Circle_x, Circle_y, Circle_r);
ofstream file("D:\\Circle\\圆拟合检测结果.txt",ios::out);
if (file.is_open())
{
file << "序号" <<"\t" <<"圆心x"<< "\t"<< "圆心y"<< "\t"<< "半径r"<< endl;
}
cout << "圆心x" <<"\t" <<"圆心y"<< "\t"<< "半径r"<< endl;
Mat threshold_output, srcImage;
Mat midImage, dstImage;//临时变量和目标图的定义
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
for (size_t i = 0; i < 100; i++)
{
srcImage = imread(vecCirclePath[i].c_str(), 1);//读取原彩色图
//【3】转为灰度图并进行图像平滑
cvtColor(srcImage, midImage, COLOR_BGR2GRAY);//转化边缘检测后的图为灰度图
//GaussianBlur(midImage, midImage, Size(9, 9), 2,2);
//blur(midImage, midImage, Size(3, 3));
//imshow("图像平滑", midImage);
/// Detect edges using Threshold
threshold(midImage, threshold_output,100, 255, THRESH_BINARY);
/// Find contours
findContours(threshold_output, contours,hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE,Point(0, 0));
/// Approximate contours to polygons+ get bounding rects and circles
vector<vector<Point> > contours_poly(contours.size());
vector<Rect> boundRect(contours.size());
vector<Point2f>center(contours.size());
vector<float>radius(contours.size());
for (int j = 0; j < 1; j++)
{
approxPolyDP(Mat(contours[j]), contours_poly[j], 3,true);
boundRect[j]= boundingRect(Mat(contours_poly[j]));
minEnclosingCircle((Mat)contours_poly[j], center[j], radius[j]);
//绘制圆心
circle(srcImage, center[j], 1,Scalar(0, 255, 0), -1, 8,0);
//绘制圆轮廓
circle(srcImage, center[j], radius[j],Scalar(155, 50, 255), 1,8, 0);
if (file.is_open())
{
file << i << "\t" << Circle_x[i]<< "\t"<< Circle_y[i]<< "\t"
<< Circle_r[i]<< "\t"<< "实际结果"<< endl;
file << i << "\t" << center[j].x<< "\t"<< center[j].y<< "\t"
<< radius[j]<< "\t"<< "检测结果"<< endl;//在控制台输出圆心坐标和半径
}
std::cout << Circle_x[i]<< "\t"<< Circle_y[i]<< "\t"
<< Circle_r[i]<< "\t"<< "实际结果"<< endl;
std::cout << center[j].x<< "\t"<< center[j].y<< "\t"
<< radius[j]<< "\t"<< "检测结果"<< endl;//在控制台输出圆心坐标和半径
}
}
/// Show in a window
//namedWindow("Contours", CV_WINDOW_AUTOSIZE);
//imshow("Contours", srcImage);
file.close();
waitKey();
return 0;
}
效果图: