How to apply custom filter to a grayscale image?

I need to have grayscale image and develop a program that applies the filters given below to that grayscale image. I implemented following code but not sure if it is ok or not?
grayImage = imread("cameramanImage.tiff");
h = [ 2 -1 -1
-1 2 -1
-1 -1 2 ];
im_outFirst = filter2(h, grayImage);

 Akzeptierte Antwort

Image Analyst
Image Analyst am 7 Jun. 2020
I'd do this, using imfilter():
grayImage = imread("cameraman.tif");
h = [ 2 -1 -1
-1 2 -1
-1 -1 2 ];
im_outFirst = imfilter(grayImage, h);
I'm not sure what filter2 does or how it differs from imfilter().

Weitere Antworten (1)

Ameer Hamza
Ameer Hamza am 7 Jun. 2020
Bearbeitet: Ameer Hamza am 8 Jun. 2020
For images, use conv2(): https://www.mathworks.com/help/releases/R2020a/matlab/ref/conv2.html. filter2 is similar to conv2 but applies a rotated filter. Also, I suggest using image as first input and filter as second
im_outFirst = conv2(grayImage, h);
In the general case, it does not matter, but if you specify 'same' or 'valid' option, then it makes a difference.

5 Kommentare

So you say the solution is right and also I can use conv2 method instead of filter2?
Sorry, I wanted to write conv2() in the line of code in my answer. If you use this syntax
im_outFirst = filter2(grayImage, h);
im_outFirst = conv2(grayImage, h);
Then the difference is that filter2 applies a rotated filter. In the context of image processing, conv2() is more appropriate, or use imfilter() as suggested by Image Analyst.
Is it possible to implement without using built-in functions like filter2 or conv2?
Something like this
im_gray = rgb2gray(im2double(imread('pears.png')));
h = [ 2 -1 -1
-1 2 -1
-1 -1 2];
im_filt = zeros(size(im_gray)-2);
for row=2:size(im_gray,1)-1
for col=2:size(im_gray,2)-1
im_filt(row-1, col-1) = sum(im_gray(row-1:row+1, col-1:col+1).*h, 'all');
end
end
Thanks its worked!

Melden Sie sich an, um zu kommentieren.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by