對我而言,有效的方法是比較形狀周邊區域的平方根。大約0.145(+/- 0.0015,因爲一些邊緣沒有完美呈現)。六角形爲0.255,三角形爲0.21,方形爲.247,五角形爲.250。圓形度也起作用(其中三角形的進入角度爲0.26到0.27),並且它也有類似的區別(三角形的.83爲三角形的.55-.56,方形的爲0.77, 78五角大樓)
下面是它的C++代碼(我沒有在這裏我的電腦上蟒蛇,但這個想法是一樣的):
#include "stdafx.h"
#include <opencv/cxcore.h>
#include <opencv2\core\mat.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
#include <opencv/cxcore.h>
#include <opencv/highgui.h>
#include <opencv/cv.h>
#include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>
using namespace cv;
using namespace std;
RNG rngee(12345);
int main() {
Mat im = imread("C:/this/is.a/path/image.png", CV_LOAD_IMAGE_COLOR);
Mat imgrey = im.clone();
cvtColor(im, imgrey, CV_RGB2GRAY);
vector<vector<Point> > imContours;
vector<Vec4i> hierarchy;
double divMaxSize = 0.175, divMinSize = 0.125;
namedWindow("Image", CV_WINDOW_NORMAL| CV_WINDOW_KEEPRATIO | CV_GUI_EXPANDED);
threshold(imgrey, imgrey, 100, 255, 0);
findContours(imgrey, imContours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));
for (int i=0; i < imContours.size(); i++) {
Scalar color = Scalar(rngee.uniform(0, 255), rngee.uniform(0,255), rngee.uniform(0,255));
cout << "sqrt(Area)/arcLength = " << sqrt(contourArea(imContours[i]))/arcLength(imContours[i], true) << endl;
if(sqrt(contourArea(imContours[i]))/arcLength(imContours[i], true) < divMaxSize && sqrt(contourArea(imContours[i]))/arcLength(imContours[i], true) > divMinSize)
{
drawContours(im, imContours, i, color, 2, 8, hierarchy, 0, Point());
cout << "I'm a star!" << endl;
}
imshow("Image", im);
waitKey(0);
}
imshow("Image", im);
waitKey(0);
}
兩種方式 - 無論是使用圓或我的sqrt(area)/ arclength method - results in:
from(dense或sparse)contour,try matc hShape函數:http://docs.opencv.org/2.4/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html#double%20matchShapes%28InputArray%20contour1,%20InputArray%20contour2,%20int%20method,%20double%20parameter%29 – Micka
您可以使用_circularity_來檢測形狀:'(4 * pi * area)/(perimeter^2)'。星形的圓度大約爲0.25,例如 – Miki