简体   繁体   中英

Converting for loops to parallel loops

I have written a code that calculates the focus value of an image. but it takes more than 5 seconds to be done.

 public double GetFValue(Image image)
        {
            Bitmap source = new Bitmap(image);
            int count = 0;
            double total = 0;
            double totalVariance = 0;
            double FM = 0;
             Bitmap bm = new Bitmap(source.Width, source.Height);
             Rectangle rect = new Rectangle(0,0,source.Width,source.Height);
              Bitmap targetRect = new Bitmap(rect.Width, rect.Height);

            // converting to grayscale
            for (int y = 0; y < source.Height; y++)
            {
                for (int x = 0; x < source.Width; x++)
                {
                    count++;
                    Color c = source.GetPixel(x, y);
                    int luma = (int)(c.R * 0.3 + c.G * 0.59 + c.B * 0.11);
                    source.SetPixel(x, y, Color.FromArgb(luma, luma, luma)); // the image is now gray scaled 
                    var pixelval = source.GetPixel(x, y);
                  //  targetRect.Save(@"C:\Users\payam\Desktop\frame-42-rectangle.png", System.Drawing.Imaging.ImageFormat.Png);
                    int pixelValue = pixelval.G;
                    total += pixelValue;
                    double avg = total / count;
                    totalVariance += Math.Pow(pixelValue - avg, 2);
                    double stDV = Math.Sqrt(totalVariance / count); // the standard deviation, which is also the focus value
                    FM = Math.Round(stDV, 2);
                }
            }
            return FM;
        }

I am trying to convert this code to a Parallel computation. I end up with bugs that I can not get my head around them. Any suggestion?

  public double CalculateFvalue (Image image)
    {
        Bitmap myimage = new Bitmap(image);
        int count = 0;
        int total = 0;
        double totalVariance = 0;
        double FM = 0;
        Parallel.For(0, image.Height, y =>
            {

            for (int x = 0; x < myimage.Width; x++)
                   {
                           count++;
                           Color c = myimage.GetPixel(x, y);
                           int luma = (int)(c.R * 0.3 + c.G * 0.59 + c.B * 0.11);
                           myimage.SetPixel(x, y, Color.FromArgb(luma, luma, luma)); // the image is now gray scaled 
                           var pixelval = myimage.GetPixel(x, y);
                           int pixelValue = pixelval.G;
                           total += pixelValue;
                           double avg = total / count;
                           totalVariance += Math.Pow(pixelValue - avg, 2);
                           double stDV = Math.Sqrt(totalVariance / count); // the standard deviation, which is also the focus value
                           FM = Math.Round(stDV, 2);
                   }


    });

        return Math.Round(FM,2);
    }

That happens because of the variables that you have declared outside of the scope of Parallel.For . Since their access (and writing) is non-deterministic, you might get values overwritten with the wrong data (Such as FM ).

I suggest you to make every iteration yield information about its result, then use the collected data to manipulate your variables outside in a thread-safe way. You could also get away with it by using a few lock statements, but I personally would avoid that.

To expand on my comment, dont try and run GetPixel in parallel, use lockBits instead.

Your code using lockbits:

    public double GetFValue(Image image)
    {
        Bitmap source = new Bitmap(image);
        int count = 0;
        double total = 0;
        double totalVariance = 0;
        double FM = 0;
        Bitmap bm = new Bitmap(source.Width, source.Height);
        Rectangle rect = new Rectangle(0, 0, source.Width, source.Height);
        //Bitmap targetRect = new Bitmap(rect.Width, rect.Height);

        //new
        ///*
        BitmapData bmd = source.LockBits(rect, ImageLockMode.ReadWrite, source.PixelFormat);
        int[] pixelData = new int[(rect.Height * rect.Width) -1];
        System.Runtime.InteropServices.Marshal.Copy(bmd.Scan0, pixelData, 0, pixelData.Length);

        for (int i = 0; i < pixelData.Length; i++)
        {
            count++;
            Color c = Color.FromArgb(pixelData[i]);
            int luma = (int)(c.R * 0.3 + c.G * 0.59 + c.B * 0.11);
            //Probably a formula for this
            pixelData[i] = Color.FromArgb(luma, luma, luma).ToArgb(); 
            total += luma;
            double avg = total / count;
            totalVariance += Math.Pow(luma - avg, 2);
            double stDV = Math.Sqrt(totalVariance / count);
            FM = Math.Round(stDV, 2);
        }
        source.UnlockBits(bmd);
        return FM;
     }

In a quick test using a 1024 x 768 jpg from win7 sample pictures (Chrysanthemum.jpg):

lockbits: 241 milliseconds

getPixel: 2208 milliseconds

Note when converting your code i noticed some odd things (like getpixel, setpixel, getpixel on the same pixel?) but i guess you know what you want to achieve, and this code is an exact equivalent of yours

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM