我寫了一個計算圖像焦點值的代碼。但要花5秒以上才能完成。將循環轉換爲並行循環
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;
}
我想將此代碼轉換爲並行計算。我最終得到的錯誤是我無法將他們的頭圍繞在他們身上。任何建議?
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);
}
你看到的錯誤是什麼? –
是的,你有一個線程安全問題的整個負載。但無論如何,getpixel是非常緩慢的,而不是鎖定位而不是 – Steve
你在不同的線程上同時更新'count','total'和'FM'。您應該讓每個循環迭代計算這些值的本地值,然後在最後將它們組合在一起。 – Lee