In my image in grayscale, I need to find a certain value and replace it with some color, for example, yellow. Here is the code that I have now, but it is not as fast as I need. Is there a more efficient way to achieve this? I was red in the ColorMatrix class , but could not find a way to replace a single value without affecting the entire image.
unsafe
{
byte stlThres = 115;
int bytePerPixel = Image.GetPixelFormatSize(kpImageViewer1.Image.PixelFormat) / 8;
var data = kpImageViewer1.Image.LockBits(new Rectangle(0, 0, kpImageViewer1.Image.Width, kpImageViewer1.Image.Height), ImageLockMode.WriteOnly, kpImageViewer1.Image.PixelFormat);
for (int y = 0; y < data.Height; y++)
{
byte* row = (byte*)data.Scan0 + (y * data.Stride);
for (int x = 0; x < data.Width; x++, row += bytePerPixel)
{
if (row[0] == stlThres)
{
row[0] = 0;
row[1] = 255;
row[2] = 255;
if (bytePerPixel == 4)
{
row[3] = 255;
}
}
}
}
kpImageViewer1.Image.UnlockBits(data);
}
VladL source
share