Advertisement
subasah

Closet-neighbor-image-filtering

Feb 9th, 2020
449
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 1.79 KB | None | 0 0
  1. %clearing command window, workspace and image windows
  2. clc;
  3. clear all;
  4. close all;
  5.  
  6. %loading image
  7. original_image = imread('grayscale_cat.jpg');
  8.  
  9. %adding noise, using gaussian noise equation
  10. %of mean 10 and variance 20
  11. mean = 10;
  12. sigma = sqrt(20);
  13. original_image= double(original_image);
  14. an = mean + (randn(size(original_image))*sigma);
  15. noisy_image = original_image + an;
  16.  
  17.  
  18. [m,n]=size(noisy_image);
  19.  
  20. %usng a mask of 3-by-3
  21.  
  22. mask_matrix = [1 2 1; 2 4 2; 1 2 1];
  23.  
  24. %z=ones(3);
  25.  
  26. [p,q] = size(mask_matrix);
  27.  
  28. w=1:p;
  29. x = round(median(w));
  30. %{
  31. below, we are making noisy matrix's corner's element all zero so that we
  32. can use 3-by-3 kernel with ease for corner elements
  33. %}
  34.  
  35. noisy_image_with_extra_zeros = zeros(m+2*(x-1),n+2*(x-1));
  36.  
  37. for i=x:(m+(x-1))
  38.  
  39.      for j=x:(n+(x-1))
  40.  
  41.         noisy_image_with_extra_zeros(i,j) = uint8(noisy_image(i-(x-1),j-(x-1)));
  42.  
  43.      end
  44.  
  45. end
  46.  
  47. figure, imshow(uint8(noisy_image_with_extra_zeros))
  48. title('noisy-image with extra zeros around');
  49.  
  50. x=0;
  51.  
  52. y=0;
  53. %these loops map the noisy_image with zeros to the kernel so that summation
  54. %can occur after multiplication between them
  55. for i=1:m
  56.  
  57.     for j=1:n
  58.  
  59.         for k=1:p
  60.  
  61.             for l=1:q
  62.                
  63.                 summation(k,l)= noisy_image_with_extra_zeros(i+x,j+y)*mask_matrix(k,l);
  64.                 y=y+1;
  65.             end
  66.  
  67.             y=0;
  68.  
  69.             x=x+1;
  70.         end
  71.  
  72.         x=0;
  73.        %here we are finding the closest pixel to consider for our outcome
  74.        %image
  75.         to_be_sorted= abs(summation - double(noisy_image(i,j)));
  76.  
  77.         sorted_vector = sort(to_be_sorted(:));
  78.  
  79.         filtered_image(i,j)=(sum(sorted_vector(1:5)));
  80.         summation=[];
  81.  
  82.     end
  83. end
  84.  
  85. figure, imshow(uint8(filtered_image))
  86. title('Filtered Image by taking 5 closest point');
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement