我正在使用 this article解决验证码。它的工作原理是使用 AForge 从图像中移除背景,然后将 Tesseract OCR 应用于生成的清洁图像。
问题是,它目前依赖于黑色的字母,并且由于每个验证码都有不同的文本颜色,我需要将颜色传递给图像清洁器,或者将字母的颜色更改为黑色。要执行任一操作,我需要知道字母的现有颜色是什么。
我该如何识别字母的颜色?
最佳答案
使用 answer作者 @Robert Harvey ♦ 我使用 LockBits
开发了相同的代码和 unsafe
方法来提高它的速度。您必须在打开“允许不安全代码”标志的情况下进行编译。请注意,从图像返回的像素顺序是 bgr
而不是 rgb
格式,我使用 Format24bppRgb
格式锁定位图以强制它为每种颜色使用 3 个字节。
public unsafe Color GetTextColour(Bitmap bitmap)
{
BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
try
{
const int bytesPerPixel = 3;
const int red = 2;
const int green = 1;
int halfHeight = bitmap.Height / 2;
byte* row = (byte*)_bitmapData.Scan0 + (halfHeight * _bitmapData.Stride);
Color startingColour = Color.FromArgb(row[red], row[green], row[0]);
for (int wi = bytesPerPixel, wc = _bitmapData.Width * bytesPerPixel; wi < wc; wi += bytesPerPixel)
{
Color thisColour = Color.FromArgb(row[wi + red], row[wi + green], row[wi]);
if (thisColour != startingColour)
{
return thisColour;
}
}
return Color.Empty; //Or some other default value
}
finally
{
bitmap.UnlockBits(bitmapData);
}
}
关于c# - 如何识别这些图像中字母的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41731626/