目錄
3)通過形態(tài)學(xué)腐蝕杨何,將分割出來的文字字符連接在一起
5)提取的文本行所在輪廓最小矩形框糕篇,并在原圖標(biāo)記檢測矩形框
運(yùn)行環(huán)境:Windows 10 64 位 + Opencv3.4.1 + Visual Studio 2015
1、理論依據(jù)
針對水平方向排列分布的印刷體文本它浅,因文本行中字符沿著近似水平直線分布译柏。所以,沿著水平方向提取文本行所在矩形框姐霍,即可將文本行檢測出來鄙麦。如下圖中的文本沿著紅色直線水平分布:2、程序?qū)崿F(xiàn)
1)圖像灰度化
將輸入圖像轉(zhuǎn)換成灰度圖像
//Color image to grayscale image
cvtColor(src, gray, CV_BGR2GRAY);
2)文本行分割
利用 OTSU 二值化方法镊折,將文本行與背景分割黔衡。
//Binary segmentation of text lines
threshold(gray, binary, 0, 255, THRESH_OTSU | THRESH_BINARY);
3)通過形態(tài)學(xué)腐蝕,將分割出來的文字字符連接在一起
//Define the erodent core
Mat rec = getStructuringElement(MORPH_RECT, Size(50, 3));
//Etch binary image along horizontal, join text line
Mat dilate0;
erode(binary, dilate0, rec);
Mat erode2;
//Image Reverse
bitwise_not(dilate0, erode2);
4)提取文本行所在的輪廓
vector<RotatedRect> rects;
vector<vector<Point>> counts;
vector<Vec4i> hierarchy;
//Extract the contour of the text line
findContours(erode2, counts, hierarchy, CV_RETR_LIST, CHAIN_APPROX_SIMPLE, Point(0, 0));
5)提取的文本行所在輪廓最小矩形框腌乡,并在原圖標(biāo)記檢測矩形框
//Mark the detection rectangles in the original image
for (int i = 0; i<counts.size(); i++)
{
//Culling of small contours
if (contourArea(counts[i])<500)
continue;
//Calculates the smallest rectangle with a vertical boundary for an contour
Rect rect1 = boundingRect(counts[i]);
char ch[256];
cout << "hierarchy num" << hierarchy[i] << endl << endl;
/* RotatedRect rect = minAreaRect(counts[i]);
int width = rect.boundingRect().width;
int heigh = rect.boundingRect().height;
Point2f P[4];
rect.points(P);
for (int j = 0; j <= 3; j++)
{
line(input, P[j], P[(j + 1) % 4], Scalar(255,0,0), 1);
}*/
//Drawing Rectangular box
rectangle(dst, rect1, Scalar(0, 0, 255), 1);
}
6)檢測結(jié)果
3、VS2015工程
VX公號“striveallen”回復(fù)“文本檢測”夜牡, 即可獲取文本檢測工程的VS2015工程与纽。內(nèi)附Opencv3.4.1開源庫侣签,可直接運(yùn)行工程,無需配置相關(guān)的庫路徑和環(huán)境變量急迂。