验证码识别
1:灰度化
public void TOGray(Bitmap bmp)
{
for (int i = 0; i < bmp.Height; i++)
{
for (int j = 0; j < bmp.Width; j++)
{
Color pixel = bmp.GetPixel(j, i);
int tmpValue = (pixel.R * 19595 + pixel.G * 38469 + pixel.B * 7472) >> 16;
bmp.SetPixel(j, i, Color.FromArgb(tmpValue, tmpValue, tmpValue));
}
}
}
2:?片固定切割
public Bitmap[] ToSplit(Bitmap bmp,int splitNum)
{
Bitmap[] bmpSplits = new Bitmap[splitNum];
for(int i=0;i<splitNum;i++)
{
Rectangle[] cloneRect = new Rectangle(i*bmp.Width/splitNum,0,bmp.Width/splitNum ,bmp.Height);
bmpSplits[i] = bmp.Clone(cloneRect, bmp.PixelFormat);
}
return bmpSplits;
}
3:二?化
public string ToCode(Bitmap bmp,int dgGrayValue)
{
Color piexl;
string code = "";
for(int y=0;y<bmp.Height;y++)
{
int codeValue = 0;
for(int x=0;x<bmp.Width;x++)
{
piexl = single.GetPixel(x,y);
if(piexl.R<dgGrayValue)
{
codeValue ++;
}
}
code +=codeValue.ToString()+",";
}
return code.SubString(0,code.Lenght-1);
}
4:??
public string ToOCR(Bitmap bmp,int splitNum,int dgGrayValue)
{
string codeValues = "";
bmp = TOGray(bmp);
Bitmap[] bmpSplits = ToSplit(bmp,plitNum);
string [] codes = new string[splitNum];
for(int i=0;i<splitNum;i++)
{
codes[i] = ToCode(bmpSplits,dgGrayValue);
codeValues += CodeMatch(codes[i],bmpCodes);
}
}
5:?取?片
public Bitmap GetBmp(string cookie,string url)
{
HttpWebRequest req = HttpWebRequest.Create(url) as HttpWebRequest;
return new Bitmap(req.GetResponse().GetResponseStream());
}
6:Code匹配
public string CodeMatch(string code,string[] bmpCodes)
{
int matchValue = 1000000;
string matchCode = "";
string [] codeSplit = code.split(',');
for(int i=0;i<bmpCodes.Lenght;i++)
{
string bmpNum = bmpCodes[i].split('|')[0];
string[] bmpCode = bmpCodes[i].split('|')[1].split(',');
int value = 0;
for(int j=0;j<bmpCode.Length;j++)
{
value+=Math.Abs(Convert.ToInt32(codeSplit[j])-Convert.ToInt32(bmpCodes[j]));
}
if(value<matchValue )
{
matchValue = value;
matchCode = bmpNum;
}
}
return matchCode;
}
7:学?(建立特征?)
public string [] ToStudy(Bitmap bmp,string nums,int dgGrayValue)
{
string [] codes = new string[nums.Length];
bmp = TOGray(bmp);
Bitmap[] bmpSplits = ToSplit(bmp,nums.Length);
for(int i=0;i<nums.Length;i++)
{
codes[i] = nums[i]+"|" + ToCode(bmpSplits[i],dgGrayValue);
}
return codes;
}