user4652027
user4652027

Reputation:

Wrong output for 2d convolution function

As the title says, the output I’m getting out of this function is incorrect. By incorrect I mean that the data are overflowing. How do I normalise the matrix correctly? Currently almost all of the pictures I get are white.

I called the function from another MATLAB file like this:

mask = [3,10,3;0,0,0;-3,-10,-3];
A = imread(“football.jpg”);
B = ConvFun(A,mask);

function [ image ] = ConvFun( img,matrix )
  [rows,cols] = size(img); %// Change

  %// New - Create a padded matrix that is the same class as the input
  new_img = zeros(rows+2,cols+2);
  new_img = cast(new_img, class(img));

  %// New -  Place original image in padded result
  new_img(2:end-1,2:end-1) = img;

  %// Also create new output image the same size as the padded result
  image = zeros(size(new_img));
  image = cast(image, class(img));

  for i=2:1:rows+1 %// Change
      for j=2:1:cols+1 %// Change
          value=0;
          for g=-1:1:1
              for l=-1:1:1
                  value=value+new_img(i+g,j+l)*matrix(g+2,l+2); %// Change
              end
          end
          image(i,j)=value;
      end
  end

  %// Change
  %// Crop the image and remove the extra border pixels
  image = image(2:end-1,2:end-1);
  imshow(image)
end

Upvotes: 0

Views: 131

Answers (1)

Ander Biguri
Ander Biguri

Reputation: 35525

In a convolution, if you want the pixel value to stay in the same range , you need to make the mask add up to 1. Just divide the mask by sum(mask(:)) after defining it. This is however, not the case you are dealing with.

Sometimes that is not the needed. For example if you are doing edge detection (like the kernel you show), you don't really care about maintaining the pixel values. In those cases, the plotting of unnormalized images is more the problem. You can always set the imshow function to auto select display range: imshow(image,[]).

Also, I hope this is homework, as this is the absolutely worst way to code convolution. FFT based convolution is about 100 times faster generally, and MATLAB has an inbuilt for it.

Upvotes: 1

Related Questions