7

I'm trying to filter an image in the space domain so i'm using the conv2 function.

here's my code.

cd /home/samuelpedro/Desktop/APIProject/

close all
clear all
clc

img = imread('coimbra_aerea.jpg');
%figure, imshow(img);

size_img = size(img);

gauss = fspecial('gaussian', [size_img(1) size_img(2)], 50);

%figure, surf(gauss), shading interp

img_double = im2double(img);

filter_g = conv2(gauss,img_double);

I got the error:

Undefined function 'conv2' for input arguments of type 'double' and attributes 'full 3d
real'.

Error in test (line 18)
filter_g = conv2(gauss,img_double);

now i'm wondering, can't I use a 3 channel image, meaning color image.

3 Answers 3

11

Color images are 3 dimensional arrays (x,y,color). conv2 is only defined for 2-dimensions, so it won't work directly on a 3-dimensional array.

Three options:

  • Use an n-dimensional convolution, convn()

  • Convert to a grayscale image using rgb2gray(), and filter in 2D:

    filter_g = conv2(gauss,rgb2gray(img_double));

  • Filter each color (RGB) separately in 2D:

    filter_g = zeros(size(im_double));
    for i = 1:3
      filter_g(:,:,i) = conv2(gauss, im_double(:,:,i);
    end
    
Sign up to request clarification or add additional context in comments.

2 Comments

Filtering each color separately is a great idea. i didn't have thought of that. :)
If you want to do this faster, passing a multi-plane image to imfilter or since this question is doing gaussian filtering, to imgaussfilt, will be faster. Both of these functions know how to operate on multi-plane data without the use of a for loop. See my answer below for more info.
1

For n-D input, you need to use convn.

2 Comments

well, i was afraid that would be the only chance. but convn turns matlab really slow.
@SamuelNLP: You can use convn, but with two 1-D Gaussian filters (one along X, the other along Y). That will speed up your code a lot.
1

If you have R2015a or newer, the IPT function imgaussfilt handles multi-plane 2-d convolution problems like this, just pass in your RGB image.

http://www.mathworks.com/help/images/ref/imgaussfilt.html

If you don't, imfilter also performs multiplane 2-d convolution.

Both will be faster for a Gaussian filter, they both know how to do the separable trick for you.

1 Comment

Also remove the im2double when using imgaussfilt/imfilter, both apply SIMD optimizations for integer inputs, so they'll be faster without the cast.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.