来自:《Mastering Opencv ...读书笔记系列》车牌识别(I)
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;
bool vertifySize(RotatedRect rect)
{
float error = 0.4; //纵横比误差
float aspect = 4.7272; //西班牙标准车牌纵横比
float minArea = 15 * aspect * 15;
float maxArea = 125 * aspect * 125;
float rmin = aspect - aspect * error;
float rmax = aspect + aspect * error;
int area = rect.size.width * rect.size.height;
float r = (float)rect.size.width / (float)rect.size.height;
if(r < 1)
r = (float)rect.size.height / (float)rect.size.width;
if( (area < minArea || area > maxArea) || (r < rmin || r > rmax) )
return false;
else
return true;
}
int main(int argc, char** argv)
{
Mat image = imread("test.jpeg");
Mat image_gray = imread("test.jpeg", CV_LOAD_IMAGE_GRAYSCALE);
//5*5高斯模糊
blur(image_gray, image_gray, Size(5, 5));
// imwrite("车牌识别/模糊化.png", image_gray);
Mat image_sobel;
Sobel(image_gray, image_sobel, CV_8U, 1, 0, 3, 1, 0, BORDER_DEFAULT);
// imshow("image_sobel", image_sobel);
// waitKey(0);
// imwrite("车牌识别/sobel.png", image_sobel);
Mat image_threshold;
threshold(image_gray, image_threshold, 0, 255, CV_THRESH_OTSU + CV_THRESH_BINARY);
// imshow("image_threshold", image_threshold);
// waitKey(0);
// imwrite("车牌识别/threshold.png", image_threshold);
Mat element = getStructuringElement(MORPH_RECT, Size(17, 3));
morphologyEx(image_threshold, image_threshold, CV_MOP_CLOSE, element);
// imshow("image_close", image_threshold);
// waitKey(0);
// imwrite("车牌识别/close.png", image_threshold);
vector<vector<Point> > contours;
findContours(image_threshold, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
vector<vector<Point> >::iterator itc = contours.begin();
vector<RotatedRect> rect;
while(itc != contours.end())
{
RotatedRect mr = minAreaRect(*itc);
if(!vertifySize(mr))
{
itc = contours.erase(itc);
}
else
{
itc++;
rect.push_back(mr);
}
}
Mat result;
image.copyTo(result);
drawContours(result, contours, -1, Scalar(0, 0, 255), 3);
// imshow("轮廓图", result);
// waitKey(0);
// imwrite("车牌识别/轮廓.png", result);
return 0;
}
模糊化:
sobel:
二值化:
闭运算:
筛选之后的轮廓: