代码是我在学习赵春江老师的C#数字图像处理算法典型实例中搬到VS2017上的,
由于随书附带的源代码,年份久远,不能直接在VS2017上运行,所以text文档打开,搬到VS上试图运行的,使用的图片已经是8位深度灰度处理过的图片,但是却无法解释溢出错误
,本人纯属菜鸟,希望各位有经验的同学指点一番。
代码如下:
namespace WindowsFormsPictureToMatrix
{
public partial class histForm : Form
{
//图像数据
private System.Drawing.Bitmap bmpHist;
private int[] countPixel;
//记录最大的灰度个数
private int maxPixel;
public histForm(Bitmap bmp)
{
InitializeComponent();
//将主窗体的数据传递给子窗体
bmpHist =bmp;
countPixel = new int[256];
}
private void histForm_Load(object sender, EventArgs e)
{
//锁定8位灰度位图
Rectangle rect = new Rectangle(0, 0, bmpHist.Width, bmpHist.Height);
System.Drawing.Imaging.BitmapData bmpData =
bmpHist.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, bmpHist.PixelFormat);
IntPtr ptr = bmpData.Scan0;
int bytes = bmpHist.Width * bmpHist.Height;
//int bytes = bmpData.Stride * bmpData.Height;
byte[] grayValues = new byte[bytes];
System.Runtime.InteropServices.Marshal.Copy(ptr, grayValues, 0, bytes);
byte temp = 0;
maxPixel = 0;
Array.Clear(countPixel, 0, 256);
for (int i = 0; i < bytes; i++)
{
temp = grayValues[i];
countPixel[temp]++;
if (countPixel[temp] > maxPixel)
{
maxPixel = countPixel[temp];
}
System.Runtime.InteropServices.Marshal.Copy(grayValues, 0, ptr, bytes);
bmpHist.UnlockBits(bmpData);
}
}
private void histForm_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
Pen curPen = new Pen(Brushes.Black, 1);
//绘制横纵坐标
g.DrawLine(curPen, 50, 240, 320, 240);
g.DrawLine(curPen, 50, 240, 50, 30);
g.DrawLine(curPen, 100, 240, 100, 242);
g.DrawLine(curPen, 150, 240, 150, 242);
g.DrawLine(curPen, 200, 240, 200, 242);
g.DrawLine(curPen, 250, 240, 250, 242);
g.DrawLine(curPen, 300, 240, 300, 242);
//横坐标刻度
g.DrawString("0", new Font("New Timer", 8), Brushes.Black, new PointF(46, 242));
g.DrawString("50", new Font("New Timer", 8), Brushes.Black, new PointF(92, 242));
g.DrawString("100", new Font("New Timer", 8), Brushes.Black, new PointF(139, 242));
g.DrawString("150", new Font("New Timer", 8), Brushes.Black, new PointF(189, 242));
g.DrawString("200", new Font("New Timer", 8), Brushes.Black, new PointF(239, 242));
g.DrawString("250", new Font("New Timer", 8), Brushes.Black, new PointF(289, 242));
g.DrawLine(curPen, 48, 40, 50, 40);
g.DrawString("0", new Font("New Timer", 8), Brushes.Black, new PointF(34, 234));
g.DrawString(maxPixel.ToString(), new Font("New Timer", 8), Brushes.Black, new PointF(18, 34));
//绘制直方图纵坐标
double temp = 0;
for (int i = 0; i < 256; i++)
{
temp = 200.0 * countPixel[i] / maxPixel;
g.DrawLine(curPen, 50 + i, 240, 50 + i, 240 - (int)temp);//溢出错误!!!
}
curPen.Dispose();
}
}
}
测试用图:
说明:csdn在编辑上传图片的时候不允许使用.bmp格式,我就改成了.jpg格式,不知道格式会不会对程序有所影响,如果有必要,还请各位帮我查看问题的时候修改为.bmp,谢谢各位。
![图片说明](https://img-ask.csdn.net/upload/201710/23/1508769669_814570.jpg)