Home > front end >  Sobel Operator in Julia
Sobel Operator in Julia

Time:12-22

I am beginner regarding Julia programming and I want to implement Sobel operator. Unfortunately the output of the following code is just a black image.

using Images, Colors, FileIO, Plots;
img = load("Lenna.png");
img_gray = Gray.(img);
sobel_image = convert(Array{Float64}, img_gray);
kernel_x =  Array{Float64}([1 0 -1; 2 0 -2; 1 0 -1]);
kernel_y =  Array{Float64}([1 2 1; 0 0 0; -1 -2 -1]);

#plot(img_gray)
function sobel(img)
    edge_img = zeros(Gray{Float64}, size(img, 1), size(img, 2));
    for x in 1:size(edge_img, 1) - size(kernel_x,1)
        for y in 1:size(edge_img, 2) - size(kernel_y,2)
            gx = sum(Gray{Float64}.(
                @view edge_img[x:x size(kernel_x,1)-1, y:y size(kernel_y,2)-1]) .* kernel_x)
            gy = sum(Gray{Float64}.(
                    @view edge_img[x:x size(kernel_x,1)-1, y:y size(kernel_y,2)-1]) .* kernel_y)
            edge_img[x 1, y 1] = hypot(gx, gy)
        end
    end
    return edge_img;
end

last_image = sobel(sobel_image)
plot(last_image)

I converted kernel_x and kernel_y to Array64. The basic idea was to convert code from python to Julia since i do not know the syntax. Could you help me with some tips? Thanks!

CodePudding user response:

Your code could use some editing (unnecessary type calls, global variables, etc), but I don't think much of it is responsible for the erroneous result.

It looks like your sobel function takes in an img, but it only uses it in the first line to create a black (all 0s) edge_img, then only works on edge_img for the rest of the function. I think that's why you end up with a black image. Perhaps you meant to index values from img in the gx = ... and gy = ... lines?

CodePudding user response:

You could try using ImageFiltering:

using ImageFiltering, TestImages, Plots
im = testimage("cameraman")
kernel = [1 0 -1; 2 0 -2;1 0 -1]
ims = imfilter(im, kernel)

Plots.plot(hcat(im, ims))

enter image description here

  • Related