开发者

C#: Average From Series of Images

开发者 https://www.devze.com 2023-02-14 04:47 出处:网络
Suppose I have a series of black and white images, NOT grayscale.I\'m trying to calculate an average of all images.I have some sample code that should work but I\'m wondering if there is a better way?

Suppose I have a series of black and white images, NOT grayscale. I'm trying to calculate an average of all images. I have some sample code that should work but I'm wondering if there is a better way?

Bitmap[] Images = ReadAndScale(Width: 50, Height: 50);

int Width = 50;
int Height = 50;

double[,] Result = ne开发者_JAVA技巧w int[50,50]

for (int i = 0 i < Images.Count; i++)
{
  for (int j = 0; j < Width; j++)
  {
     for (int k = 0; k < Height; k++)
     {
         Result[j, k] += Images[i].GetPixel(j,k) == Color.White ? 0 
                         : 1.0 / (double)Images.Count;
     }
  }
}

At the end of these loops you have an array Result[] that contains the average value; > .5 is black otherwise the average is white.


Well, I think your general algorithm is fine, not really a way to make that "better".

The only way I see you could make it "better" would be to scrape more performance out of it, but do you need that?

The main perf issue I see is the use of GetPixel() as it is a relatively slow method. Here is an example using unsafe code that should run much faster: Unsafe Bitmap

Don't let the word "unsafe" scare you, it just is the keyword for enabling true pointers in C#.


Well, you could make the images the inner loop, and break out as soon as you've guaranteed the average will be less than or greater than .5. Not sure if that is really "better".

0

精彩评论

暂无评论...
验证码 换一张
取 消