MATLAB help 2D convolution

7 次查看(过去 30 天)
Yigit Goktas
Yigit Goktas 2023-3-28
I have a task to make a 2D convolution function that I have an image and a filter will be applied that should give the output result of image filtering in spatial domain. Also, during the edge detection(to handle boundaries) I have to use sobel and prewitt operator. I wrote a convolution code but I didn't quite get what is sobel and how to apply it. I got confused a bit and my code also gave error didn't get the reason and how to fix it?
The error I get:
Error using padarray>ParseInputs
Function padarray expected A (argument 1) to be numeric, logical or categorical for constant padding.
Error in padarray (line 75)
[a, method, padSize, padVal, direction, catConverter] = ParseInputs(args{:});
Error in Q4>my_convolution (line 15)
padded_image = padarray(image, [pad_height, pad_width], 0, 'both');
Error in Q4 (line 2)
outpu_image1 = my_convolution('Figure4.jpg',filter_1);
THE CODE:
filter_1 = [-1 0 1; -1 0 1; -1 0 1];
outpu_image1 = my_convolution('Figure4.jpg',filter_1);
function output_image = my_convolution(image, filter)
[im_height, im_width] = size(image);
[filter_height, filter_width] = size(filter);
pad_height = floor(filter_height / 2);
pad_width = floor(filter_width / 2);
padded_image = padarray(image, [pad_height, pad_width], 0, 'both');
output_image = zeros(im_height, im_width);
% Perform convolution
for i = 1:im_height
for j = 1:im_width
% Extract the local region of the padded image
local_region = padded_image(i:i+filter_height-1, j:j+filter_width-1);
% Compute the dot product between the local region and the filter
output_pixel = sum(sum(local_region .* filter));
% Assign the output pixel value to the output image
output_image(i, j) = output_pixel;
end
end
end

回答(2 个)

Walter Roberson
Walter Roberson 2023-3-28
outpu_image1 = my_convolution('Figure4.jpg',filter_1);
You are passing in the character vector 'Figure4.jpg' not the content of the image.
function output_image = my_convolution(image, filter)
We recommend against naming a variable image as image is one of the important graphics functions; people are likely to get confused.
  2 个评论
Yigit Goktas
Yigit Goktas 2023-3-28
I changed it as
filter_1 = [-1 0 1; -1 0 1; -1 0 1];
image1 = imread("Figure4.jpg");
output_image1 = my_convolution(image1,filter_1);
Then another error occured:
Error using .*
Integers can only be combined with integers of the same class, or scalar doubles.
Error in Q4>my_convolution (line 27)
output_pixel = sum(sum(local_region .* filter));
Error in Q4 (line 3)
output_image1 = my_convolution(image1,filter_1);

请先登录,再进行评论。


Image Analyst
Image Analyst 2023-3-28
Try this:
function output_image = my_convolution(image1, filter)
[Gmag,Gdir] = imgradient(image1, 'sobel')
output_image = GMag;

产品

Community Treasure Hunt

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

Start Hunting!

Translated by