0
votes

I am working on image processing project in C#. I'm using OTSU thresholding method. I am getting this exception "Attempted to read or write protected memory. This is often an indication that other memory is corrupt." I googled and searched stack-overflow for more than 2 days, but I didn't get the correct solution. I am getting this error only for few images, with other images its working fine...

  public void Convert2GrayScaleFast(Bitmap bmp)
        {
            BitmapData bmData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height),
                    ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
            unsafe
            {
                byte* p = (byte*)(void*)bmData.Scan0.ToPointer();
                int stopAddress = (int)p + bmData.Stride * bmData.Height;
                while ((int)p != stopAddress)
                {
                    p[0] = (byte)(.299 * p[2] + .587 * p[1] + .114 * p[0]);
                    p[1] = p[0];
                    p[2] = p[0];
                    p += 3;
                }
            }
            bmp.UnlockBits(bmData);
        }

I'm getting the exception in this line

p[0] = (byte)(.299 * p[2] + .587 * p[1] + .114 * p[0]);

dont tell to bypass exception using Tools menu ->Options -> Debugging -> General -> Uncheck this option "Suppress JIT optimization on module load". I have tried all the methods but nothing worked for me..

Here is the image which throws the exception Thanks a lot if u help me to solve the problem.

2
Airtel 4G run too fast . I am sure Windows can't handle that file because of 4G speed and latency. Did you tried other photo which don't have airtel 4G in it.Anirudha Gupta
@Anirugu wow what a sense of humor! Any how i find a way for otsu thresholding using EMGU... But I didnt fix this problem... thanks for the comment...Gokulakannan
I got my problem solved using EMGU CV for finding threshold.. But i cant fix this.. If any one fix this it may help any one...Gokulakannan
Side note: instead of "I googled and searched stack-overflow for more than 2 days" you should just get safe code working first and than convert it to unsafe...Alexei Levenkov

2 Answers

4
votes

Change condition to:

while ((int)p < stopAddress)
2
votes

You should also consider that the stride is rounded up to a four-byte boundary and can be negative (the bitmap is bottom-up) https://msdn.microsoft.com/en-us/library/system.drawing.imaging.bitmapdata.stride(v=vs.110).aspx I suggest:

            int numberOfBytesPerPixel = Image.GetPixelFormatSize(bmp.PixelFormat) / 8;
            int stopAddress = (int)p + (bmData.Width * numberOfBytesPerPixel) * bmData.Height;
            while ((int)p < stopAddress)
            {
                // add pixel manipulation here
                p += numberOfBytesPerPixel;
            }