3)车牌字符切割
a. 阈值滤波,使用CV_THRESH_BINARY参数通过把白色值变为黑色,黑色值变为白色来实现阈值输出的反转,因为需要获取字符的轮廓,而轮廓的算法寻找的是白色像素;
b. 查找轮廓;
c. 验证轮廓是否为字符,去除那些规格太小的或者宽高比不正确的区域。字符是45/77的宽高比,允许0.35的误差。如果一个区域面积高于80%(就是像素大于0的超过80%),则认为这个区域是一个黑色块,不是字符。
/* charSlicer.cpp */
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
//包围字符的矩形筛选
bool charDetection(Mat rect)
{
float error = 0.35;
const float width_height = 45.0 / 77.0;
float char_width_height = (float)rect.cols / (float)rect.rows;
float min_value = 0.2;
float max_value = width_height*(1 + error);
float min_height = 20;
float max_height = 30;
int pixels = countNonZero(rect);
float area = rect.cols*rect.rows;
float ratio = pixels / area;//获得矩形区域黑色所占的比例
return ratio<0.8&&char_width_height>min_value&&char_width_height < max_value
&&rect.rows >= min_height && rect.rows <= max_height;
}
void plateChar(Mat srcImg)
{
//1. 二值化图像,像素值大于60设为0,反之设为255
Mat plateImg;
threshold(srcImg, plateImg, 60, 255, CV_THRESH_BINARY_INV);
//imshow("反转图像", plateImg);
//2. 寻找轮廓,findContours函数会改变输入图像,可对其clone
Mat contoursImg = plateImg.clone();
vector<vector<Point>> contours;//定义轮廓,每个轮廓是一个点集
/*void findContours(InputOutputArray Img, OutputArrayOfArrays contours, OutputArray hierarchy,
int mode, int method, Point offset=Point())*/
findContours(contoursImg, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
cout << "轮廓数量:" << contours.size() << endl;
//3. 获得各个字符图像的外部矩形边界,在原图中找出字符
Mat oriImg = imread("plateOri.jpg");
for (int i = 0; i < contours.size(); i++)
{
drawContours(oriImg, contours, i, Scalar(0, 255, 0), 1);//绿色填充所有轮廓
Rect rect = boundingRect(contours[i]);//获得字符轮廓点集的外部矩形边界
rect.height += 1;//切割较大的图像
rect.width += 1;
/*void rectangle(Mat& img, Rect rec, const Scalar& color, int thickness=1, int lineType=8,
int shift=0 )*/
rectangle(oriImg, rect, S