基于c++,使用opencv将123.png图中车牌区域的字符分割出来(每个字符分割成一个独立的图像,并分别显示出来)。
时间: 2023-06-13 19:07:16 浏览: 121
以下是基于C++和OpenCV的代码实现,实现车牌字符分割:
```cpp
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
int main()
{
// 读入原始图片
Mat src = imread("123.png");
// 车牌定位
Mat gray, hsv, binary;
cvtColor(src, gray, COLOR_BGR2GRAY);
cvtColor(src, hsv, COLOR_BGR2HSV);
inRange(hsv, Scalar(100, 60, 60), Scalar(124, 255, 255), binary);
Mat element1 = getStructuringElement(MORPH_RECT, Size(5, 5));
Mat element2 = getStructuringElement(MORPH_RECT, Size(15, 15));
morphologyEx(binary, binary, MORPH_CLOSE, element1);
morphologyEx(binary, binary, MORPH_OPEN, element2);
vector<vector<Point> > contours;
findContours(binary, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
vector<Rect> plates;
for (size_t i = 0; i < contours.size(); i++)
{
Rect rect = boundingRect(contours[i]);
float rate = float(rect.width) / float(rect.height);
if (rate > 2.5 && rate < 5 && rect.height > 50)
{
plates.push_back(rect);
}
}
if (plates.size() == 0)
{
cout << "未检测到车牌!" << endl;
return -1;
}
// 车牌字符分割
Mat plate, plate_gray, plate_binary;
plate = src(plates[0]);
cvtColor(plate, plate_gray, COLOR_BGR2GRAY);
threshold(plate_gray, plate_binary, 0, 255, THRESH_BINARY_INV | THRESH_OTSU);
vector<vector<Point> > contours_plate;
findContours(plate_binary, contours_plate, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
vector<Rect> chars;
for (size_t i = 0; i < contours_plate.size(); i++)
{
Rect rect = boundingRect(contours_plate[i]);
float rate = float(rect.width) / float(rect.height);
if (rate > 0.2 && rate < 1.5 && rect.height > 10 && rect.height < 50)
{
chars.push_back(rect);
}
}
// 显示分割结果
for (size_t i = 0; i < chars.size(); i++)
{
Mat char_image = plate_binary(chars[i]);
resize(char_image, char_image, Size(20, 40));
imshow("字符分割结果", char_image);
waitKey(0);
}
return 0;
}
```
运行后,可以得到字符分割的结果,每个字符分割成一个独立的图像,并分别显示出来。
阅读全文