基於OpenCV進行文本分塊切割

假設有以下一張圖,如何把其中的文本分塊切割出來,好比「華普超市朝陽門店」、「2015-07-26」就是兩個文本塊。算法

wKiom1W4ivayh50VAAKNdHomsEA740.jpg


作圖像切割有不少種方法,本文描述一種最直觀的投影檢測法。先來看看什麼是投影,簡單來講,投影就是在必定方向上有效像素的數量。來看個直觀的圖像:c#

wKiom1W4iwvQfJiCAAGye-xnAXA489.jpg


這是一張水平投影圖與原圖的對比,從投影圖上能看到多個波峯,文字多的地方,投影就長,行間的空白處,投影爲0。 上個示例代碼:數組

public void HorizontalProjection()
{
    //以灰度圖方式讀入源文件
    string filename = "source.jpg";
    var src = IplImage.FromFile(filename, LoadMode.GrayScale);

    //二值化,採用閾值分割法
    Cv.Threshold(src, src, 0, 255, ThresholdType.BinaryInv | ThresholdType.Otsu);

    //存儲投影值的數組
    var h = new int[src.Height];

    //對每一行計算投影值
    for(int y = 0;y < src.Height;++y)
    {
        //遍歷這一行的每個像素,若是是有效的,累加投影值
        for(int x = 0;x < src.Width;++x)
        {
            var s = Cv.Get2D(src, y, x);
            if(s.Val0 == 255)
                h[y]++;
        }
    }

    //準備一個圖像用於畫投影圖
    var paintY = Cv.CreateImage(src.Size, BitDepth.U8, 1);
    Cv.Zero(paintY);

    //畫圖
    var t = new CvScalar(255);
    for(int y = 0;y < src.Height;++y)
    {
        for(int x = 0;x < h[y];++x)
            Cv.Set2D(paintY, y, x, t);
    }

    //顯示
    using(var window = new CvWindow("Source"))
    {
        window.Image = src;
        using(var win2 = new CvWindow("Projection"))
        {
            win2.Image = paintY;
            Cv.WaitKey();
        }
    }
}


顯然找出波峯對應的y值,就能把行切割開了。 獲得一行之後,能夠採用相似的思想進行垂直投影,挑了一行測試一下,效果以下:
ide

wKioL1W4jXKBQ6VqAACvzlb6mf4672.jpg


能夠看到效果不是特別好,左右結構的漢字有可能被切開,一個完整的數值也有可能分紅多個數字,這種狀況須要作一下處理,好比識別的時候要判斷若是間距較小就認爲還是同一文本塊,或者對圖像進行一下橫向膨脹處理:測試

var kernal = Cv.CreateStructuringElementEx(3, 1, 1, 0, ElementShape.Rect);
Cv.Dilate(src, src, kernal, 4);


再計算投影,獲得的效果就好多了:優化

wKiom1W4i6CDXumUAACmtHnl-xI012.jpg



最後上完整代碼以及切割效果展現:spa

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

using OpenCvSharp;
using OpenCvSharp.Extensions;
using OpenCvSharp.Utilities;

namespace OpenCvTest
{
    class Program
    {
        static void Main(string[] args)
        {
            //打開源文件
            string filename = "source.jpg";
            var src = IplImage.FromFile(filename);

            //轉成灰度圖
            var gray = Cv.CreateImage(src.Size, BitDepth.U8, 1);
            Cv.CvtColor(src, gray, ColorConversion.BgrToGray);

            //二值化,閾值分割算法
            Cv.Threshold(gray, gray, 0, 255, ThresholdType.BinaryInv | ThresholdType.Otsu);

            //分行
            var rows = GetRowRects(gray);

            //針對每一行再分塊
            var items = new List<CvRect>();
            foreach (var row in rows)
            {
                var cols = GetBlockRects(gray.Clone(row), row.Y);
                items.AddRange(cols);
            }

            //把識別出的每一塊畫到原圖上去
            var color = new CvScalar(255, 0, 0);
            foreach (var rect in items)
            {
                Cv.DrawRect(src, rect, color, 1);
            }

            //顯示
            using (var window = new CvWindow("Image"))
            {
                window.Image = src;
                Cv.WaitKey();
            }
        }

        /// <summary>
        /// 識別行
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        private static List<CvRect> GetRowRects(IplImage source)
        {
            var rows = new List<CvRect>();

            //用於存儲投影值
            var projection = new int[source.Height];

            //遍歷每一行計算投影值
            for (int y = 0; y < source.Height; ++y)
            {
                for (int x = 0; x < source.Width; ++x)
                {
                    var s = Cv.Get2D(source, y, x);
                    if (s.Val0 == 255)
                        projection[y]++;
                }
            }

            bool inLine = false;
            int start = 0;

            //開始根據投影值識別分割點
            for (int i = 0; i < projection.Length; ++i)
            {
                if (!inLine && projection[i] > 10)
                {
                    //由空白進入字符區域了,記錄標記
                    inLine = true;
                    start = i;
                }
                else if ((i - start > 5) && projection[i] < 10 && inLine)
                {
                    //由字符區域進入空白區域了
                    inLine = false;

                    //忽略高度過小的行,好比分隔線
                    if (i - start > 10)
                    {
                        //記錄下位置
                        var rect = new CvRect(0, start - 1 , source.Width, i - start + 2);
                        rows.Add(rect);
                    }
                }
            }
            
            return rows;
        }

        /// <summary>
        /// 識別塊
        /// </summary>
        /// <param name="source"></param>
        /// <param name="rowY"></param>
        /// <returns></returns>
        private static List<CvRect> GetBlockRects(IplImage source, int rowY)
        {
            var blocks = new List<CvRect>();

            //用於存儲投影值
            var projection = new int[source.Width];
            
            //先進行橫向膨脹
            var kernal = Cv.CreateStructuringElementEx(3, 1, 1, 0, ElementShape.Rect);
            Cv.Dilate(source, source, kernal, 4);

            //遍歷每一列計算投影值
            for (int x = 0; x < source.Width; ++x)
            {
                for (int y = 0; y < source.Height; ++y)
                {
                    var s = Cv.Get2D(source, y, x);
                    if (s.Val0 == 255)
                        projection[x]++;
                }
            }

            bool inBlock = false;
            int start = 0;

            //開始根據投影值識別分割點
            for (int i = 0; i < projection.Length; ++i)
            {
                if (!inBlock && projection[i] >= 2)
                {
                    //由空白區域進入字符區域了
                    inBlock = true;
                    start = i;
                }
                else if ((i - start > 10) && inBlock && projection[i] < 2)
                {
					//由字符區域進入空白區域了
					inBlock = false;

					//記錄位置,注意因爲傳入的是source只是一行,所以最終的位置信息要+rowY
					if(blocks.Count > 0)
					{
						//跟上一個比一下,若是距離過近,認爲是同一個文本塊,合併
						var last = blocks[blocks.Count - 1];

						if (start - last.X - last.Width <= 5)
						{
							blocks.RemoveAt(blocks.Count - 1);
							var rect = new CvRect(last.X, rowY, i - last.X, source.Height);
							blocks.Add(rect);
						}
						else
						{
							var rect = new CvRect(start, rowY, i - start, source.Height);
							blocks.Add(rect);
						}
					}
					else
					{
						var rect = new CvRect(start, rowY, i - start, source.Height);
						blocks.Add(rect);
					}                }
            }

            return blocks;
        }
    }
}


獲得的圖像以下,效果還行,未來繼續優化吧:blog

wKiom1W5dVnR4GwmAAQPWZBFAFU031.jpg



未經許可嚴禁轉載。get

相關文章
相關標籤/搜索