获取车牌轮廓 c++ opencv
时间: 2023-10-13 21:05:45 浏览: 94
获取车牌轮廓的步骤如下:
1. 读取车牌图像
```c++
Mat img = imread("car_plate.jpg");
```
2. 灰度化
```c++
Mat gray_img;
cvtColor(img, gray_img, COLOR_BGR2GRAY);
```
3. 高斯模糊
```c++
Mat blur_img;
GaussianBlur(gray_img, blur_img, Size(3, 3), 0);
```
4. 边缘检测
```c++
Mat edges;
Canny(blur_img, edges, 80, 160);
```
5. 轮廓检测
```c++
vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
findContours(edges, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE);
```
6. 遍历轮廓,找到最大的矩形轮廓
```c++
double max_area = 0;
Rect max_rect;
for (int i = 0; i < contours.size(); i++) {
double area = contourArea(contours[i]);
if (area > max_area) {
max_area = area;
max_rect = boundingRect(contours[i]);
}
}
```
最终,`max_rect` 就是车牌的轮廓矩形。可以通过以下代码将其绘制在原图上:
```c++
rectangle(img, max_rect, Scalar(0, 0, 255), 2);
imshow("car plate", img);
waitKey(0);
```
完整代码如下:
```c++
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;
int main() {
Mat img = imread("car_plate.jpg");
Mat gray_img;
cvtColor(img, gray_img, COLOR_BGR2GRAY);
Mat blur_img;
GaussianBlur(gray_img, blur_img, Size(3, 3), 0);
Mat edges;
Canny(blur_img, edges, 80, 160);
vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
findContours(edges, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE);
double max_area = 0;
Rect max_rect;
for (int i = 0; i < contours.size(); i++) {
double area = contourArea(contours[i]);
if (area > max_area) {
max_area = area;
max_rect = boundingRect(contours[i]);
}
}
rectangle(img, max_rect, Scalar(0, 0, 255), 2);
imshow("car plate", img);
waitKey(0);
return 0;
}
```
阅读全文