8

How can I efficiently calculate the sum of all pixels in an image, by using a HSLS pixel shader? I'm interested in Pixel Shader 2.0, that I could invoke as a WPF shader effect.

luvieere
  • 35,580
  • 18
  • 120
  • 178

3 Answers3

7

There is a much simpler solution that doesn't use shaders: load the image as a texture, create a mipmap chain and read back the value of the last mipmap (1x1 pixel). This trick is used in games extensively to calculate, for example, the average brigthness of a scene (in order to apply HDR tonemapping). It's a great trick if you value simplicity and efficiency over accuracy.

The Fiddler
  • 2,566
  • 18
  • 23
  • How exactly do you create a mipmap chain from an image in WPF, that's as fast as applying a pixel shader? – luvieere Jul 15 '10 at 15:38
  • By resizing the image using to 1x1 using a box filter. – The Fiddler Jul 15 '10 at 22:41
  • Thank you for this. My textures are somewhat degenerate (high precision numerical FFT's) and using the triangle filter instead gave very good results (plus or minus 1% of the desired result) which is good enough for me. The box filter was way off, though. – Thomas Oct 05 '13 at 12:09
3

Assuming that you want to sum r/g/b channel values in image (and assuming that you can destroy original pixels) - here is my partial solution:

  1. Each 10th pixel would calculate average color of 10 neighboring pixels and put this averaged color on image.
  2. Then in CPU side sum
    Pix_Value*10
    of each 10th pixel.

In this case we get about 10x speed-up compared to summing pixel values only in CPU side.

Agnius Vasiliauskas
  • 10,413
  • 5
  • 46
  • 66
  • No need to involve the CPU, everything can be done on the GPU. "inefficient" doesn't begin to describe this approach, it doesn't even consider the cost of CPU-GPU communication. -1 – Thomas Oct 08 '13 at 08:18
-1

Effects in WPF are much more suited to producing visual result. It sounds like you want to use them for a different type of calculation, to do this you would need to treat the image result as data this would need RenderTargetBitmap which would be done in software anyway. You might want to look at these projects designed for GPGPU.

Accelerator

Brahma

OpenTK I dont know the state of the OpenCL bindings in OpenTK. Other technologies such as DirectCompute and CUDA might be worth a look too.

Kris
  • 6,890
  • 2
  • 22
  • 26