#include<opencv2\opencv.hpp>
#include<iostream> using namespace cv; using namespace std; int areas;
//该函数用来验证是否是我们想要的区域,车牌定位原理其实就是在图片上寻找矩形,我们可以用长宽比例以及面积来验证是否是我们想要的矩形,宽高比为520/110=4.7272 (车牌的长除以宽),区域面积最小为15个像素,最大为125个像素
bool VerifySize(RotatedRect candidate) { float error = 0.4; //40%的误差范围
float aspect = 4.7272;//宽高比例
int min = 25 * aspect * 25; //最小像素为15
int max = 125 * aspect * 125;//最大像素为125
float rmin = aspect - aspect*error;//最小误差
float rmax = aspect + aspect*error;//最大误差
int area = candidate.size.height*candidate.size.width;//求面积
float r = (float)candidate.size.width / (float)candidate.size.height;//长宽比
if (r < 1)
r = 1 / r;
if (area<min || area>max || r<rmin || r>rmax)
return false;
else
return true; } int main(int argc, char** argv) {
Mat src;
src = imread("D:\\Car1.jpg");//读取含车牌的图片
if (!src.data) {
cout << "Could not open Car.jph.." << endl;
return -1;
}
Mat img_gray;
cvtColor(src, img_gray, CV_BGR2GRAY);//灰度转换
Mat img_blur;
blur(img_gray, img_blur, Size(5, 5));//用来降噪
Mat img_sobel;
Sobel(img_gray, img_sobel, CV_8U, 1, 0, 3);//Sobel滤波,对x进行求导,就是强调y方向,对y进行求导,就是强调x方向,在此我们对x求导,查找图片中的竖直边
Mat img_threshold;
threshold(img_sobel, img_threshold, 0, 255, THRESH_BINARY | THRESH_OTSU);
Mat element = getStructuringElement(MORPH_RECT, Size(21, 5));//这个Size很重要!!不同的图片适应不同的Size,待会在下面放图,大家就知道区别了
morphologyEx(img_threshold, img_threshold,MORPH_CLOSE,element);//闭操作,就是先膨胀后腐蚀,目的就是将图片联通起来,取决于element的Size
。 /*接下来就是提取轮廓*/
vector<vector<Point>>contours;
findContours(img_threshold, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
Mat result = Mat::zeros(src.size(), CV_8U);
drawContours(result, contours, -1, Scalar(255));
vector<RotatedRect> rects; //用来存放旋转矩形的容器
//Mat result1 = Mat::zeros(src.size(), CV_8U);
Mat result1;
src.copyTo(result1);
for (size_t i = 0; i < contours.size(); i++) {
Point2f vertices[4];//用来存放旋转矩形的四个点
RotatedRect mr = minAreaRect(Mat(contours[i]));
//minAreaRect 寻找最小的矩形
if (VerifySize(mr))//筛选是否是我们需要的区域,如果验证成功,就放到rects里,
{
&nbs