基于多核的误差扩散算法的研究和实现
//灰度图像颜色扩散后形成黑白图像
private void btnColorExpand_Click(object sender, EventArgs e)
{
cpuCount = System.Environment.ProcessorCount;//获取CUP的核数
width = image1.Width;
height = image1.Height;
this.PictureToArray();
if (cpuCount == 1)
{
threadLength=2;
}
else
{
threadLength=cpuCount;
}
thread = new Thread[threadLength];
rows = 0;
for (int i = 0; i < thread.Length; i++)//多线程实现
{
thread[i] = new Thread(new ParameterizedThreadStart(ColorExpand));
object n = rows;
thread[i].Start(n);
rows++;
}
}
//ColorArray类型的数组colorArray初始化
public void PictureToArray()
{
colorArray = new ColorArray[image1.Height];
for (int i = 0; i < height; i++) //图像的列
{
colorArray[i].pixelValue = new int[width];
for (int j = 0; j < width; j++)//图像的行
{
pixelColor = new Color();
pixelColor = image1.GetPixel(j, i);//图像像素坐标值
int temp = (pixelColor.R + pixelColor.G + pixelColor.B) / 3;
colorArray[i].pixelValue[j] = temp;
}
colorArray[i].index = 0;
}
}
//实现图像像素颜色的扩散的方法
#region
public void ColorExpand(object n)
{
int y = Convert.ToInt32(n);
while (y < height)
{
for (int x = 0; x < width; x++)
{
colorArray[y].index = x;
#region
int red = colorArray[y].pixelValue[x];
int value2;
if (red >= 128) //如果red大于等于128将其设为白色 255
value2 = 255;
else
value2 = 0;
#endregion
//误差扩散
int err = colorArray[y].pixelValue[x] - value2;
if (y > 0 && colorArray[y].index >= colorArray[y - 1].index - 1)
{
Thread.Sleep(50);
}
if (y >= 0 && y < height - 1)
{
if (x == 0)
{
colorArray[y].pixelValue[x + 1] += err * 7 / 16;
colorArray[y + 1].pixelValue[x] += err * 5 / 16;
colorArray[y + 1].pixelValue[x + 1] += err * 1 / 16;
}
if (x == width - 1)
{
colorArray[y + 1].pixelValue[x] += err * 5 / 16;
colorArray[y + 1].pixelValue[x - 1] += err * 3 / 16;
}
if (x > 0 && x<width-1)
{
colorArray[y].pixelValue[x + 1] += err * 7 / 16;
colorArray[y + 1].pixelValue[x] += err * 5 / 16;
colorArray[y + 1].pixelValue[x + 1] += err * 1 / 16;
colorArray[y + 1].pixelValue[x - 1] += err * 3 / 16;
}
}
if (y == height - 1)
{
if (x >= 0 && x < width - 1)
{
colorArray[y].pixelValue[x + 1] += err * 7 / 16;
}
}
colorArray[y].pixelValue[x] = value2;
if (y==0 && cpuCount == 1)
{
Thread.Sleep(50);
}
}
y = rows++;
}
MessageBox.Show("OK");
}
执行时,有的图像像素值会大于255或者小于0 ,不知道为什么,是不是有的行没有执行,希望有研究过这个问题的大侠帮帮忙!小弟跪求各位了!