I wish to calculate an average image from 3 different images of the same size that I have. I know this can be done with ease in matlab..but how do I go about this in c#? Also is there an Aforge.net tool I can use directly for this purpose?
Asked
Active
Viewed 1,339 times
0
-
1Could you please explain what does image average mean? Is it pixel RGB average of the three images? – Robert J. Jun 12 '14 at 07:15
-
1Yeah @RobertJ. RGB averaging is what I mean – Kapil Jun 12 '14 at 07:18
-
Do you want the process to be fast or easy? – Robert J. Jun 12 '14 at 07:20
-
Fast!..I've tried locking the bitmaps and taking the average of the RGB values and assigning it to the result image but I'm getting absurd results... – Kapil Jun 12 '14 at 07:24
-
Well, LockBits would be the way to go imho. Maybe the problem was in your calculations? How did you get the average of RGB values? did you try to average values of each R | G | B for three images or you simply multiplied value of R*G*B for each image and average the values? – Robert J. Jun 12 '14 at 07:27
-
Please post your code that gives absurd results, you may only have a single character/digit wrong in there that someone can spot easily rather than rewriting everything. – Mark Setchell Jun 12 '14 at 08:29
2 Answers
1
I have found an article on SO which might point you in the right direction. Here is the code (unsafe)
BitmapData srcData = bm.LockBits(
new Rectangle(0, 0, bm.Width, bm.Height),
ImageLockMode.ReadOnly,
PixelFormat.Format32bppArgb);
int stride = srcData.Stride;
IntPtr Scan0 = srcData.Scan0;
long[] totals = new long[] {0,0,0};
int width = bm.Width;
int height = bm.Height;
unsafe
{
byte* p = (byte*) (void*) Scan0;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
for (int color = 0; color < 3; color++)
{
int idx = (y*stride) + x*4 + color;
totals[color] += p[idx];
}
}
}
}
int avgB = totals[0] / (width*height);
int avgG = totals[1] / (width*height);
int avgR = totals[2] / (width*height);
Here is the link to the article: How to calculate the average rgb color values of a bitmap
0
ImageMagick can do this for you very simply - at the command-line you could type this:
convert *.bmp -evaluate-sequence mean output.jpg
You could equally calculate the median (instead of the mean) of a bunch of TIFF files and save in a PNG output file like this:
convert *.tif -evaluate-sequence median output.png
Easy, eh?
There are bindings for C/C++, Perl, PHP and all sorts of other janguage interfaces, including (as kindly pointed out by @dlemstra) the Magick.Net binding available here.
ImageMagick is powerful, free and available here.

Mark Setchell
- 191,897
- 31
- 273
- 432
-
1There is a binding for C# called Magick.NET (http://imagemagick.org/script/api.php#dot-net) – dlemstra Jun 12 '14 at 08:43
-
@dlemstra +1 Thank you for that insight - it's good to learn new stuff :-) – Mark Setchell Jun 12 '14 at 08:46
-