Hi,
I think your code is not far from being correct,
I made a few changes and it works fine ;)
A few remarks:
- minq and maxq are hardcoded, maybe they should be calculated values.
- when you increment your variable p you add an offset of 3 on each line, resulting in the wrong areas being marked
- you only need one unsafe block.
- as previously mentioned
if (rc1 + rc2 + rc3 + rc4 + rc5 + rc6 + rc7 + rc8 < 8)
is not nice...
I tried the following code with various pictures and it worked fine.
byte minq = 50;
byte maxq = 100;
EditImage = (Bitmap)this.pictureBox1.Image;
BitmapData bmData = EditImage.LockBits(new Rectangle(0, 0, EditImage.Width, EditImage.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
int stride = bmData.Stride;
System.IntPtr Scan0 = bmData.Scan0;
int bitsPerPixels = stride / EditImage.Width;
int[,] arraynilai = new int[EditImage.Width+1, EditImage.Height+1];
unsafe
{
byte* pos;
byte* scan0 = (byte*)(bmData.Scan0.ToPointer());
for (int j = 0; j < bmData.Height; j++)
{
pos = scan0 + stride * j;
for (int i = 0; i < bmData.Width; i++)
{
*pos = (byte)(255 - *pos);
if ((pos[i] <= maxq && pos[i] >= minq))
arraynilai[i, j] = 1;
else
arraynilai[i, j] = 0;
pos += bitsPerPixels;
}
}
for (int j = 1; j < bmData.Height; j++)
{
pos = scan0 + stride * j;
for (int i = 1; i < bmData.Width; i++)
{
*pos = (byte)(255 - *pos);
int rc1 = arraynilai[i - 1, j - 1];
int rc2 = arraynilai[i, j - 1];
int rc3 = arraynilai[i + 1, j - 1];
int rc4 = arraynilai[i + 1, j];
int rc5 = arraynilai[i + 1, j + 1];
int rc6 = arraynilai[i, j + 1];
int rc7 = arraynilai[i - 1, j + 1];
int rc8 = arraynilai[i - 1, j];
int tot = rc1 + rc2 + rc3 + rc4 + rc5 + rc6 + rc7 + rc8;
if (tot < 8 && tot > 0)
{
pos[i] = pos[i + 1] = pos[i + 2] = 255;
}
pos += bitsPerPixels;
}
}
}
EditImage.UnlockBits(bmData);
also what you could do to calculate minq and maxq is look at the average pixel. but it is a bit crude, and maybe some matrix calculations would be a lot more efficient.
for (int j = 0; j < bmData.Height; j++)
{
pos = scan0 + stride * j;
for (int i = 0; i < bmData.Width; i++)
{
*pos = (byte)(255 - *pos);
if ((pos[i] <= maxq && pos[i] >= minq))
arraynilai[i, j] = 1;
else
arraynilai[i, j] = 0;
totalValue += pos[i];
numberPixels += 1;
pos += bitsPerPixels;
}
}
minq = Convert.ToByte(totalValue / numberPixels * 0.9);
maxq = Convert.ToByte(totalValue / numberPixels * 1.1);
Hope it helps.
Valery.