车牌提取
- 原理:首先对图片进行一系列的处理,步骤:去噪——sobel滤波——otsu阈值化——闭运算;然后绘制矩形,选择最接近的一个矩形;最后矩形轮廓提取。
#include "opencv2/imgproc.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include <iostream>
#include <map>
using namespace std;
using namespace cv;
bool verify(RotatedRect rect) {
float error = 0.4;
const float aspect = 4.7272;
int min = 15 * aspect * 15;
int max = 125 * aspect * 125;
float rmin = aspect - aspect * error;
float rmax = aspect + aspect * error;
int area = rect.size.width * rect.size.height;
float r = rect.size.width / rect.size.height;
r = r < 1 ? 1 / r : r;
return area >= min && area <= max && r >= rmin && r <= rmax;
}
int main()
{
string in = "D://OPENCV//实践小程序//pictures//车牌切割.jpg";
Mat image = imread(in, IMREAD_GRAYSCALE);
Mat image2 = imread(in);
Mat image3 = imread(in, IMREAD_GRAYSCALE);
if (image.empty()){
return -1;
}
imshow("【原始图】", image);
blur(image, image, Size(5, 5));
imshow("【去噪后】", image);
Sobel(image, image, CV_8U, 1, 0, 3, 1, 0);
imshow("【sobel滤波】", image);
threshold(image, image, 0, 255, CV_THRESH_OTSU);
imshow("【otsu阈值化】", image);
Mat element = getStructuringElement(MORPH_RECT, Size(17, 3));
morphologyEx(image, image, CV_MOP_CLOSE, element);
imshow("【闭运算】", image);
vector<vector<Point>> contours;
findContours(image, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);
map<int, RotatedRect> _map;
for (int i = 0; i < contours.size(); i++) {
drawContours(image, contours, i, Scalar(255), 1);
RotatedRect rect = minAreaRect(contours[i]);
Point2f vertices[4];
rect.points(vertices);
for (int i = 0; i < 4; i++) {
line(image, vertices[i], vertices[(i + 1) % 4], Scalar(255), 2);
}
if (verify(rect)) {
_map[i] = rect;
}
}
imshow("【轮廓提取】", image);
int min_diff = 100000;
int index = 0;
const float square = 27.75;
map<int, RotatedRect>::iterator iter;
iter = _map.begin();
while (iter != _map.end()) {
RotatedRect rect = iter->second;
Point2f vertices[4];
rect.points(vertices);
for (int j = 0; j < 4; j++) {
line(image, vertices[j], vertices[(j + 1) % 4], Scalar(255), 10);
}
int perimeter = arcLength(contours[iter->first], true);
int area = contourArea(contours[iter->first]);
if (area != 0) {
int squareness = perimeter * perimeter / area;
float diff = abs(squareness - square);
if (diff < min_diff) {
min_diff = diff;
index = iter->first;
}
}
iter++;
}
imshow("【通过验证】", image);
RotatedRect rect = _map[index];
Point2f vertices[4];
rect.points(vertices);
for (int i = 0; i < 4; i++) {
cout << " asdf" << endl;
line(image2, vertices[i], vertices[(i + 1) % 4], Scalar(0, 255, 0), 10);
}
imshow("【最接近的矩形】", image2);
Mat image_crop;
Size rect_size = rect.size;
if (rect_size.width < rect_size.height) {
swap(rect_size.width, rect_size.height);
}
getRectSubPix(image3, rect.size, rect.center, image_crop);
imshow("【切割后的车牌】", image_crop);
waitKey(0);
return 0;
}
运行效果