title: how to remove salt and pepper noise from images using python?
body: <p>I have tried to implement the following algorithm but the resulting image looks the same.</p>
  
  <p><strong>Step 1</strong>: Read Noisy Image.</p>
  
  <p><strong>Step 2</strong>: Select 2D window of size 3x3 with centre element as 
  processing  pixel.  Assume  that  the  pixel  being 
  processed is P
  ij
  .</p>
  
  <p><strong>Step 3</strong>: If P
  ij
  is an uncorrupted pixel (that is, 0&lt; P
  ij
  &lt;255), then 
  its value is left unchanged.</p>
  
  <p><strong>Step 4</strong>: If P
  ij
  = 0 or P
  ij
  = 255, then P
  ij
  is a corrupted pixel.</p>
  
  <p><strong>Step 5</strong>: If 3/4
  th
  or more pixels in selected window are noisy 
  then increase window size to 5x5.
  Step 6: If all the elements in the selected window are 0‟s and 
  255‟s, then replace P
  ij
  with the mean of the elements 
  in the window else go to step 7.</p>
  
  <p><strong>Step 7</strong>: Eliminate 0‟s and 255‟s from the selected window 
  and find the median value of the remaining elements. 
  Replace Pij
  with the median value.</p>
  
  <p><strong>Step 8</strong>: Repeat steps 2 to 6 until all the pixels in the entire 
  image are processed.</p>
  
  <p>Here is my code. Please suggest improvements.</p>
  
  <pre><code>import Image
  
  im=Image.open("no.jpg")
  im = im.convert('L')
  
  for i in range(2,im.size[0]-2):
      for j in range(2,im.size[1]-2):
          b=[]
          if im.getpixel((i,j))&gt;0 and im.getpixel((i,j))&lt;255:
              pass
          elif im.getpixel((i,j))==0 or im.getpixel((i,j))==255:
              c=0
              for p in range(i-1,i+2):
                  for q in range(j-1,j+2):
                      if im.getpixel((p,q))==0 or im.getpixel((p,q))==255: 
                          c=c+1
              if c&gt;6:
                  c=0
                  for p in range(i-2,i+3):
                      for q in range(j-2,j+3):
                          b.append(im.getpixel((p,q)))
                          if im.getpixel((p,q))==0 or im.getpixel((p,q))==255:
                              c=c+1
                  if c==25:
                      a=sum(b)/25
                      print a
                      im.putpixel((i,j),a)
                  else:
                      p=[]
                      for t in b:
                          if t not in (0,255):
                              p.append(t)
                      p.sort()
                      im.putpixel((i,j),p[len(p)/2])
              else:
                  b1=[]
                  for p in range(i-1,i+2):
                      for q in range(j-1,j+2):
                          b1.append(im.getpixel((p,q)))
                  im.putpixel((i,j),sum(b1)/9)
  
  im.save("nonoise.jpg")   
  </code></pre>