demo:
游戏文字识别时,简单的预处理
首先准备一张图片用于文字识别
直接用OCR识别会识别出非常多垃圾信息,这个时候我们就需要对图像进行预处理操作
从上面的色阶图可以看出左边应该是背景板后面的垃圾信息,右边是我们所需要的的文字信息,只需要去掉背景信息即可获得需要处理的文字信息
对图像去饱和后再进行阈值操作
static Mat Preprocessing(string file)
{
var img = Cv2.ImRead(file,ImreadModes.AnyColor);
if (img.Empty())
return null;
Mat result = Mat.Zeros(img.Size(), img.Type());
img.Desaturation(result);
// 阈值
Cv2.Threshold(result, result, 100, 255, ThresholdTypes.Binary);
return result;
}
获得的图像,把背景信息丢弃后得到的前背景看上去效果不错
使用大漠对该图像OCR操作,识别还可以,只需要对识别范围限制一下得到的结果应该就是正确的了,在字库字少的时候非常快
看看在线文字识别结果,慢
百度API高精度版本,比较慢,标准版返回是空的我的天
去饱和
公式:
Gray = ( Math.max(Red, Green, Blue) + Math.min(Red, Green, Blue) ) / 2
public static class ImageHelper
{
/// <summary>
/// 图像去饱和
/// </summary>
/// <param name="src"></param>
/// <param name="dst"></param>
public static unsafe void Desaturation(this Mat src, Mat dst)
{
System.Diagnostics.Debug.Assert(dst != null, "dst not set to an instance of an object.");
System.Diagnostics.Debug.Assert(src.Channels() >= 3, "src.Channels < 3");
System.Diagnostics.Debug.Assert(src.Type() == dst.Type(), "src.Type != des.Type");
System.Diagnostics.Debug.Assert(src.Size() == dst.Size(), "src.Size != des.Size");
int height = src.Rows;
int width = src.Cols;
var channels = src.Channels();
Parallel.For(0, height, i =>
{
var ptr = (byte*)src.Ptr(i).ToPointer();
var dstPtr = (byte*)dst.Ptr(i).ToPointer();
for (var j = 0; j < width; j++)
{
var ptrOffset = j * channels;
var max = Math.Max(Math.Max(ptr[ptrOffset], ptr[ptrOffset + 1]), ptr[ptrOffset + 2]);
var min = Math.Min(Math.Min(ptr[ptrOffset], ptr[ptrOffset + 1]), ptr[ptrOffset + 2]);
var color = (byte)((max + min) * 0.5f);
dstPtr[ptrOffset] = color;
dstPtr[ptrOffset + 1] = color;
dstPtr[ptrOffset + 2] = color;
}
});
}
}