3

I have a function to check if an image is just one color.

bool r = true;
Color checkColor = image.GetPixel(0, 0);

for (int x = 0; x < image.Width; x++)
  {
   for (int y = 0; y < image.Height; y++)
     {
      if (image.GetPixel(x, y) != checkColor) { r = false; }
     }
   }
// image color
clrOut = checkColor;
return r;

But this algorithm is slow for big images. Does anyone knows a way to do this using Pixel Shaders and GPU?

Matej Kormuth
  • 2,139
  • 3
  • 35
  • 52

4 Answers4

6

You don't need pixel shaders and a GPU to speed this up. Use LockBits. Bob Powell has a good tutorial on doing exactly what you want.

Andrew Morton
  • 24,203
  • 9
  • 60
  • 84
Kris Erickson
  • 33,454
  • 26
  • 120
  • 175
2

Also looking at your code, try reversing the for loops it gives better memory access

for( y... ... for ( x...

The next step is to unroll some of the pixels access. Try fetching 4 or 8 pixels in the inter loop

for( y... ... for ( x = 0; x < image.Width ; x +=4 )

  pixel0 = image.getpixel(x,Y)
  pixel1 = image.getpixel(x +1,Y)
  pixel2 = image.getpixel(x +2,Y)
  pixel3 = image.getpixel(x +3,Y)

  if ( pixel0 ....

As stated earlier using Bitmap Unlock allows you access pixels via pointers, which is the fastest you can get on a CPU. You can apply loop ordering and pixel unrolling to that technique too.
If this isn't fast enough then there is choice between; C# multi-threading or GPU with OpenCL and its C# binding.

Tim Child
  • 2,994
  • 1
  • 26
  • 25
1

This code is slow, because you use GetPixel. You can make it much faster by using direct pointer access. Only if that's not enough, I'd look into pixel shaders.

I've written some helper libraries: https://github.com/CodesInChaos/ChaosUtil/tree/master/Chaos.Image

In particular the Pixels and the RawColor types should be useful.

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
0

If you're only looking for an image with large areas of variation versus one with the same color, you could shrink it down to a 1x1 pixel using Bilinear filtering and read pixel 0,0. If the the pixel is VERY different from what you expect (RGB distance versus a tolerance), you can be sure that there was some variation in the original image.

Of course, this depends on what you really want to do with this info so YMMV.

Ani
  • 10,826
  • 3
  • 27
  • 46