|
楼主 |
发表于 2009-5-22 09:38
|
显示全部楼层
//图形
Bitmap bmp = null;
//保存深浅2种颜色
Color[] cc = new Color[2];
int[] left = new int[5];//左边的点
int[] right = new int[5];//右边的点
int[] top = new int[5];//顶点
int[] bottom = new int[5];//底点
try
{
//获取图片源
bmp = (Bitmap)Bitmap.FromFile(@"C:\Documents and Settings\bzhang\Desktop\图片辨析\test.jpg");
#region 转换灰度的算法
//转换灰度的算法
Color c1;
int luma;
for (int w1 = 0; w1 <= bmp.Width - 1; w1++)
{
for (int h1 = 0; h1 <= bmp.Height - 1; h1++)
{
c1 = bmp.GetPixel(w1, h1);
luma = (int)(c1.R * 0.3 + c1.G * 0.59 + c1.B * 0.11);//转换灰度的算法
bmp.SetPixel(w1, h1, Color.FromArgb(luma, luma, luma));
}
}
#endregion
#region 取色
cc = GetDeepColor(bmp);
#endregion
#region 去杂色,转换为黑白图片
for (int w2 = 0; w2 <= bmp.Width - 1; w2++)
{
for (int h2 = 0; h2 < bmp.Height - 1; h2++)
{
Color c2 = bmp.GetPixel(w2, h2);
if (c2.R > cc[0].R)
{
bmp.SetPixel(w2, h2, Color.FromArgb(255, 255, 255));
}
else
{
bmp.SetPixel(w2, h2, Color.FromArgb(0, 0, 0));
}
}
}
#endregion
#region 处理干扰点
this.RemoveMacula(bmp);
#endregion
#region 动态得到每个数字的边界
bool myColumn; //标示该列是否出现黑点
bool charStart = false; //标示首次取到黑点
int[] widthStartX = new int[10];
int[] heightStartY = new int[10];
int[] widthEndX = new int[10];
int[] heightEndY = new int[10];
int charNum = 0;
for (int x = 0; x < bmp.Width; x++)
{
myColumn = true;
for (int y = 0; y < bmp.Height; y++)
{
Color c = bmp.GetPixel(x, y);
if (c.R == 0 && charStart == false)//第一次出现黑点
{
widthStartX[charNum] = x;
charStart = true;
break;
}
if (c.R == 0 && charStart == true)//后续出现黑点
{
myColumn = false;
break;
}
}
if (myColumn == true && charStart == true && widthStartX[charNum] < x)//如果当列没有黑点并且前面出现过黑点还没结束
{
widthEndX[charNum] = x - 1;
charStart = false;
charNum++;
}
if (charStart == true && myColumn == false && x == (bmp.Width - 1))//如果开始出现黑点了,并且最后一列也有黑点
{
widthEndX[charNum] = x;
charStart = false;
charNum++;
}
}
#endregion
#region 得到每个字符的特征码
string str1= string.Empty;
string str2 = string.Empty;
string str3 = string.Empty;
string str4 = string.Empty;
for (int x1 = 0; x1 < bmp.Width; x1++)
{
for (int y1 = 0; y1 < bmp.Height; y1++)
{
if (widthStartX[0] < x1 && x1 < widthEndX[0])
{
Color cnum1 = bmp.GetPixel(x1, y1);
if (cnum1.R == 0)
{
str1 = str1 + "1";
}
else
{
str1 = str1 + "0";
}
}
else if (widthStartX[1] < x1 && x1 < widthEndX[1])
{
Color cnum2 = bmp.GetPixel(x1, y1);
if (cnum2.R == 0)
{
str2 = str2 + "1";
}
else
{
str2 = str2 + "0";
}
}
else if (widthStartX[2] < x1 && x1 < widthEndX[2])
{
Color cnum3 = bmp.GetPixel(x1, y1);
if (cnum3.R == 0)
{
str3 = str3 + "1";
}
else
{
str3 = str3 + "0";
}
}
else if (widthStartX[3] < x1 && x1 < widthEndX[3])
{
Color cnum4 = bmp.GetPixel(x1, y1);
if (cnum4.R == 0)
{
str4 = str4 + "1";
}
else
{
str4 = str4 + "0";
}
}
}
}
//MessageBox.Show("8: " + str1 + "\n"+ "9: "+ str2+"\n"+"1: "+ str3+"\n"+"5: "+ str4);
#endregion
bmp.Save(@"c:\1.bmp");
//这里分析单个字符的上下左右点,这样就可以确定范围了
//识别出来
//释放资源
bmp.Dispose();
}
catch (Exception err)
{
MessageBox.Show(err.ToString());
}
finally
{
} |
|