截取图中上方数码管中的数字

基本思路:

1、将图像转化为灰度图

2、截取ROI区域

3、二值化

4、循环遍历每一行和每一列,得到字符的坐标

5、截取并保存

OpenCV——字符提取并保存-LMLPHP

 #include <opencv2/opencv.hpp>
#include <iostream>
#include <math.h>
#include <stdio.h> using namespace cv;
using namespace std; int getColSum(Mat& src, int t);
int getRowSum(Mat& src, int t);
void cutLeft(Mat& src, Mat& leftImg, Mat& rightImg);
void cutTop(Mat& src, Mat& dstImg); int main()
{
Mat src = imread("数字.jpg", );
threshold(src, src, , , THRESH_BINARY|THRESH_OTSU);
imshow("origin", src); Mat roi = src(Rect(, , src.cols-, ));//截取ROI区域
imshow("ROI", roi);
//形态学操作去除干扰
Mat kernel = getStructuringElement(MORPH_RECT, Size(, ), Point(-, -));
morphologyEx(roi, roi, MORPH_OPEN, kernel); Mat kernel2 = getStructuringElement(MORPH_RECT, Size(,), Point(-, -));
dilate(roi, roi, kernel2);
imshow("ROI", roi); Mat leftImg, rightImg; rightImg = roi.clone();
string nameLeft[] = {"digital_1.jpg","digital_2.jpg" ,"digital_3.jpg" ,"digital_4.jpg" ,"digital_5.jpg" };
for (int i = ; i < ; i++) { cutLeft(rightImg, leftImg, rightImg);
imwrite(nameLeft[i], leftImg);//保存
} waitKey();
return ;
}
//函数作用:计算某一列的像素和
//输入为二值图像
int getColSum(Mat& src, int t) {
int rowNumber = src.rows;//行数
int colNumber = src.cols;//列数
uchar ColSum = ;
for (int i = ; i < rowNumber; i++)
{
for (int j = ; j < colNumber; j++)
{
if (j == t)
{ ColSum += src.at<uchar>(i, j);
} }
}
return ColSum;
} int getRowSum(Mat& src, int t) {
int rowNumber = src.rows;//行数
int colNumber = src.cols;//列数
uchar RowSum = ;
for (int i = ; i < rowNumber; i++)
{
if (i== t)
{ for (int j = ; j < colNumber; j++)
{ RowSum += src.at<uchar>(i, j); }
}
}
return RowSum;
}
void cutLeft(Mat& src, Mat& leftImg, Mat& rightImg)//左右切割
{
int left, right;
left = ;
right = src.cols; //循环遍历每一列,记录下左端的坐标
int i;
for (i = ; i < src.cols; i++)
{
int colValue = getColSum(src, i);
//cout <<i<<" th "<< colValue << endl;
if (colValue > )
{
left = i;
break;
}
} //接着循环遍历每一列,记录下右端的坐标
for (; i < src.cols; i++)
{
int colValue = getColSum(src, i);
//cout << i << " th " << colValue << endl;
if (colValue == )
{
right = i;
break;
}
} int width = right - left;//计算字符的宽度 Rect rect(left, , width, src.rows);
leftImg = src(rect);
Rect rectRight(right, , src.cols - right, src.rows);
rightImg = src(rectRight);
cutTop(leftImg, leftImg); } void cutTop(Mat& src, Mat& dstImg)//上下切割
{
int top, bottom;
top = ;
bottom = src.rows; int i;
for (i = ; i < src.rows; i++)
{
int colValue = getRowSum(src, i);
//cout <<i<<" th "<< colValue << endl;
if (colValue > )
{
top = i;
break;
}
}
for (; i < src.rows; i++)
{
int colValue = getRowSum(src, i);
//cout << i << " th " << colValue << endl;
if (colValue == )
{
bottom = i;
break;
}
} int height = bottom - top;
Rect rect(, top, src.cols, height);
dstImg = src(rect);
}
05-11 22:20