检索汽车牌照信息
第一次发文章,废话不多说,先来一个流程图。
原图
结果图
代码如下:
int main()
{
Mat src, gray_src, dst;
src = imread("car.jfif");
if (src.empty()) {
printf("could not load image...\n");
return -1;
}
namedWindow("input image", CV_WINDOW_AUTOSIZE);
imshow("input image", src);
GaussianBlur(src,gray_src,Size(5,5),0);
cvtColor(gray_src, gray_src, CV_BGR2GRAY);
imwrite("dst_blur_gray_.jpg", gray_src);
//Sobel边缘检测
Mat dst_x, dst_y;
Sobel(gray_src,dst_x,CV_8U,1,0);
Sobel(gray_src, dst_y, CV_8U, 0, 1);
addWeighted(dst_x, 0.5, dst_y, 0.5, 0, dst);
//二值化
threshold(dst, dst, 50, 255, THRESH_BINARY);
//形态学操作
//int a = 9;
//Mat kernel = getStructuringElement(MORPH_RECT, Size(a, a), Point(-1, -1));
//morphologyEx(dst,dst,MORPH_CLOSE,kernel);
//Mat kernel_1 = getStructuringElement(MORPH_RECT, Size(3, 3), Point(-1, -1));
//morphologyEx(dst, dst, MORPH_OPEN, kernel_1);
//Mat dilate_image, erode_image;
//自定义 核进行 x 方向的膨胀腐蚀
Mat elementX = getStructuringElement(MORPH_RECT, Size(25, 1));
Mat elementY = getStructuringElement(MORPH_RECT, Size(1, 19));
Point point(-1, -1);
dilate(dst, dst, elementX, point, 2);
erode(dst, dst, elementX, point, 4);
dilate(dst, dst, elementX, point, 2);
erode(dst, dst, elementY, point, 1);
dilate(dst, dst, elementY, point, 2);
//绘制轮廓
//矩形轮廓查找与筛选:
Mat contour_image;
//深拷贝 查找轮廓会改变源图像信息,需要重新 拷贝 图像
contour_image = dst.clone();
vector<vector<Point>> contours;
findContours(contour_image, contours, CV_RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
//画出轮廓
drawContours(contour_image, contours, -1, Scalar(255), 5);
//轮廓表示为一个矩形 车牌提取
Mat roi_image, roi_image_0, roi_image_1;
vector<Point> rectPoint;
for (int i = 0; i < contours.size(); i++)
{
Rect r = boundingRect(Mat(contours[i]));
//RotatedRect r = minAreaRect(Mat(contours[i]));
cout << "contours " << i << " height = " << r.height << " width = " << r.width << " rate = " << ((float)r.width / r.height) << endl;
if ((float)r.width / r.height >= 1.8 && (float)r.width / r.height <= 3.6)
{
cout << "r.x = " << r.x << " r.y = " << r.y << endl;
rectangle(contour_image, r, Scalar(0, 0, 255), 2);
rectangle(src, r, Scalar(0, 0, 255), 3);
roi_image = src(r);
}
}
//namedWindow(output_win, CV_WINDOW_AUTOSIZE);
//imshow("GRAY image", gray_src);
//namedWindow(roi_win, CV_WINDOW_AUTOSIZE);
//imshow("result", dst);
imshow("result1", roi_image);
waitKey(0);
}