이미지의 포커스 값을 계산하는 코드를 작성했습니다. 하지만 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은 매우 느리며, 대신 lockbits를 조사합니다. – Steve
다른 스레드에서'count','total' 및'FM'을 동시에 업데이트하고 있습니다. 각 루프 반복에서 이들에 대한 지역 값을 계산 한 다음 끝에 결합해야합니다. – Lee