I'm trying to find the needle from these or similar pictures:
My solution is take average brightness of picture and set black and white pixels depends on it. The result is something like this:
I dont need to see numbers and staf there.. only needle but its not big problem when its there. But im using set, get pixel functions and its realy slow i reed something about LockBits metod, i use it for get brightness but i dont know how to use it correct for setpixel. Can anyone help me with my code?..thnx
BitmapData imageData = imgPristroj.LockBits(new Rectangle(0, 0, imgPristroj.Width, imgPristroj.Height), ImageLockMode.ReadOnly, imgPristroj.PixelFormat);
float brightness = 0;
float average;
unsafe
{
try
{
UnmanagedImage Unimg = new UnmanagedImage(imageData);
int pixelSize = (Unimg.PixelFormat == PixelFormat.Format24bppRgb) ? 3 : 4;
byte* p = (byte*)Unimg.ImageData.ToPointer();
for (int y = 0; y < Unimg.Height; y++)
{
for (int x = 0; x < Unimg.Width; x++, p += pixelSize)
{
brightness += Unimg.GetPixel(x, y).GetBrightness();
}
}
average = brightness / (Unimg.Width * Unimg.Height);
}
finally
{
imgPristroj.UnlockBits(imageData); //Unlock
}
}
img19 = (Bitmap)imgPristroj.Clone();
for (int y = 0; y < img19.Height; y++)
{
for (int x = 0; x < img19.Width; x++)
{
if (img19.GetPixel(x, y).GetBrightness() > average)
{
img19.SetPixel(x, y, Color.White);
}
else
{
img19.SetPixel(x, y, Color.Black);
}
}
}
Edit2: This is my whole code..
float brightness = 0;
float average = 0;
PixelUtil pixelUtil2 = new PixelUtil((Bitmap)imgPristroj.Clone());
pixelUtil2.LockBits();
for (int y = 0; y < imgPristroj.Height; y++)
{
// for each pixel
for (int x = 0; x < imgPristroj.Width; x++)
{
brightness += pixelUtil2.GetPixel(x, y).GetBrightness();
}
}
average = brightness / (imgPristroj.Width * imgPristroj.Height);
pixelUtil2.UnlockBits();
img19 = (Bitmap)imgPristroj.Clone();
Crop cfilter1 = new Crop(new Rectangle(0, (int)(pix * 1.6), img19.Width, (int)(pix * 3)));
img19 = cfilter1.Apply(img19);
PixelUtil pixelUtil = new PixelUtil(img19);
pixelUtil.LockBits();
for (int y = 0; y < img19.Height; y++)
{
for (int x = 0; x < img19.Width; x++)
{
if (pixelUtil.GetPixel(x, y).GetBrightness() >= average)
{
pixelUtil.SetPixel(x, y, Color.White);
}
else
{
pixelUtil.SetPixel(x, y, Color.Black);
}
}
}
pixelUtil.UnlockBits();
string filepath = Environment.CurrentDirectory;
string fileName = System.IO.Path.Combine(filepath, @"img" + ".bmp");
img19.Save(fileName);
I get this bitmap with color pixels, can you tell me why?
And when i use red color.. not black... (pixelUtil.SetPixel(x, y, Color.Red);) i have got this funny pic. (differnt size is OK..)