OpenCV实践:低对比度图像检测圆形轮廓

文章目录
前言
最近在答疑区有找到一个检测实例:在低对比度图像中检测圆形轮廓,这里分享给大家 。
问题链接:
1. 问题描述

OpenCV实践:低对比度图像检测圆形轮廓

文章插图
问题提出者想要在如下图片中找到圆形轮廓:
2.实现步骤
主要步骤如下:
OpenCV实践:低对比度图像检测圆形轮廓

文章插图
读取原图并转换为灰度图;提取ROI区域;阈值分割查找轮廓并根据圆形轮廓特征(半径大小,外界矩形长宽比)过滤轮廓绘制圆形轮廓;3. 源码实现
#include #include #include #include #include #include using namespace cv;int main(){std::string strImgFile = "C:\\Temp\\common\\Workspace\\Opencv\\images\\BlueROI.jpg";Mat mSrc = http://www.kingceram.com/post/imread(strImgFile);CV_Assert(!mSrc.empty());//resize(mSrc, mSrc, Size(mSrc.cols / 2, mSrc.rows / 2));Mat mGray;cvtColor(mSrc, mGray, COLOR_BGR2GRAY);CV_Assert(!mGray.empty());imshow("gray", mGray);Mat mRoi;mGray(Rect(Point(160, 70), Point(160 + 210, 70 + 220))).copyTo(mRoi);CV_Assert(!mRoi.empty());imshow("roi", mRoi);Mat mThresh;double thresh = threshold(mRoi, mThresh, 30, 255, THRESH_BINARY_INV);std::cout << "Threshold value:" << thresh << std::endl;CV_Assert(!mThresh.empty());imshow("threshold", mThresh);/*Mat mCircleKernel = getStructuringElement(MORPH_ELLIPSE, Size(3, 3));Mat mMorph;morphologyEx(mThresh, mMorph, MORPH_DILATE, mCircleKernel);CV_Assert(!mMorph.empty());imshow("morph", mMorph);*/Mat mSrcCopy = mSrc.clone();std::vector::vector> contours;findContours(mThresh, contours, RETR_EXTERNAL, CHAIN_APPROX_NONE);for (int i = 0; i < contours.size(); i++){Point2f center;float radius;minEnclosingCircle(contours[i], center, radius);RotatedRect rr = minAreaRect(contours[i]);int max = rr.size.width > rr.size.height ? rr.size.width : rr.size.height;int min = rr.size.height > rr.size.width ? rr.size.width : rr.size.height;if (radius > 10 && radius < 50 && max / min < 1.5){//drawContours(mSrcCopy, contours, i, Scalar(0, 0, 255), 1, 8, noArray(), 2000, Point(160, 70));circle(mSrcCopy, Point(int(center.x + 160), int(center.y + 70)), int(radius-5), Scalar(0, 0, 255));}}imshow("result", mSrcCopy);waitKey();destroyAllWindows();return 0;}
4. 结果展示
总结
【OpenCV实践:低对比度图像检测圆形轮廓】这里的实现比较粗糙,没有准确定位要检测的圆形轮廓,目前没有想到比较好的方法,如果有大神有好的方法,希望不吝赐教,谢谢!