Thursday 14 August 2014

Getting the shape drawn by pen by image processing in matlab

I recently got a small project of filtering out the image drawn by pen on white paper to just black and white.





Although the code seems huge, actually it is quite simple. It is divided into two parts.

First part is to convert from rgb to black and white. Each time the threshold frequency may change, so i chose to take the maximum index across all rows and columns and then took mean of it, and by experiment, I found that adding 40 to the value thus found gives the maximum result.

The next part was to remove the black part of un-illuminated area that comes in BnW image. For that, i have tried to find out 'lrange', and the 'hrange'. lrange is the lower value of column from which the cropped image will begin and hrange is the highest value of column for cropped image.

Here is the code:



%first convert to grayscale image and then to binary.
clc;
clear;
clear all;
ima = 'C:\Users\Admin\pen2.jpg';
 im1 = imread(ima);
im1 = imresize(im1,.5);
imshow(im1)
title('original image')
pause(1);
im1 = rgb2gray(im1);

[a,b] = size(im1);
min1 = (zeros(a,1))+100;
for i = 1:a                 %automatic threshold
    for j = 1:b
        if(im1(i,j)<min1(i,1))
            min1(i,1) = im1(i,j);
        end
    end
end
    th = mean(min1);
 im3 = im1 > th+40;
 %figure; imshow(im3);
 title('b n w')
 im4 = im3;
 im4 = bwareaopen(im4,16,8);

 %%the following code is to crop the black portion that has came due to
 %low intensity at the bottom of the image.
 lrange = 0;  
 hrange = b;  
 var1 = 0;
 for lc = 1 : abs(b/10);      
     for lr = a : -1 : a-250
     var1 = var1 | im4(lr,b);
      end
      if var1 == 0
          lrange = lrange + 1;
      end
 end
  for hc = b : -1 : (b-abs((b/3)))
      for hr = a : -1 : a-250
      var1 = 0 | im4(hr,b);
      end
      if var1 == 0
          hrange = hrange - 1;
      end
  end
  im5 = imcrop(im4,[lrange,0,hrange,a]);
  %% This code crops the image due to low intensity at the top of the image
  lrange1 = 0; hrange1 = b;
  for lc1 = 1 : abs(b/10);
     for lr1 = 1 : 250
      var1 = var1 | im4(lr1,b);
      end
      if var1 == 0
          lrange1 = lrange1 + 1;
      end
  end
 %figure; imshow(im5)
  for hc1 = b : -1 : (b-abs((b/3)))
      for hr1 = 1 : 250
      var1 = 0 | im4(hr1,b);
      end
      if var1 == 0
          hrange1 = hrange1 - 1;
      end
  end
  im6 = imcrop(im5,[lrange1,0,hrange1,a]);
  imcomp = imcomplement(im6);
 w = ones(7,7);
 im7 = imfilter(imcomp,w,'replicate');
figure; imshow(imcomplement(im7))
title('final image')


You can view the same on Github

No comments:

Post a Comment

Powered by Blogger.