Search code examples
matlabnoise

How to add impulsive and gamma noise to an image without using imnoise function in matlab?


I was wondering if you could give me some advice on how to add impulsive and Gamma noise to an image separately? It's so easy with imnoise function of matlab, but i'm not allowed to use imnoise, Our TA said you can just use rand function.

I came across this code but it seems it doesn't work as it should(for impulse noise):

    noisyimage=originalimage+255*rand(size(originalimage)); 

Solution

  • There's a few issues with that line of code:

    • 255*rand() generates double-valued numbers, whereas your image will probably be of type uint8 or so (check with class(originalimage)). To fix, use randi for instance:

      noisyimage = randi(255, size(originalimage), class(originalimage));
      

      (use intmax(class(originalimage)) to be completely generic)

    • you add noise of maximum magnitude 255 to all pixels. This might overflow many of your pixels (that is, get assigned values higher than 255). To avoid, use something like

      noisyimage = min(255, originalimage + randi(...) );
      
    • The noise direction is only positive. True noise also sometimes brings down the values of the pixels. So, use something like

      noisyimage = max(0, min(255, originalimage + randi(...)-127 );
      
    • the maximum amplitude of 255 is actually way too big; you'll likely destroy your whole image and only get noise. Try a few different amplitudes, A, like so:

      noisyimage = max(0, min(255, originalimage + randi(A, ...)-round(A/2) );
      
    • The uniform distribution which randi uses is not a really good source of noise; you'd want some other distribution. Use the normal distribution:

      uint8(A*randn(...)-round(A/2))
      

      or gamma:

      uint8(A*randg(...)-round(A/2))
      

      etc.

    Now, that should get you started :)