本文实现了一个基于Sobel算子的图像边缘检测算法。算法首先读取灰度图像,定义水平和垂直方向的Sobel卷积核,然后对图像进行卷积运算计算梯度幅值。通过设定阈值(默认220)将梯度幅值二值化,大于阈值的像素点标记为边缘(1),否则为背景(0)。处理过程中考虑了图像边界问题,最终输出二值化的边缘检测结果图。该算法能有效提取图像中的边缘特征,通过调整阈值可以控制边缘检测的灵敏度。
Matlab
% function Q = soble_detector(IMG,thresh)
clear all; close all; clc;
IMG = rgb2gray(imread('../素材/0_images/Scart.jpg')); % 读取jpg图像
imshow(IMG);
thresh = 220;
[h,w] = size(IMG);
Q = ones(h,w);
% ----------------------------------------------------
% Gx Gy Pixel
% [-1 0 1] [-1 -2 -1] [p1 p2 p3]
% [-2 0 2] [ 0 0 0] [p4 p5 p6]
% [-1 0 2] [ 1 2 1] [p7 p8 p9]
sobel_x = [-1,0,1,-2,0,2,-1,0,1];
sobel_y = [-1,-2,-1,0,0,0,1,2,1];
img_gray = double(IMG);
img_sobel = ones(h,w);
n = 3;
for i = 1 : h
for j = 1 : w
if(i<(n-1)/2+1 || i>h-(n-1)/2 || j<(n-1)/2+1 || j>w-(n-1)/2)
img_sobel(i,j) = 0;
else
temp1 = sobel_x(1)*img_gray(i-1,j-1) + sobel_x(2)*img_gray(i-1,j) + sobel_x(3)*img_gray(i-1,j+1) +...
sobel_x(4)*img_gray(i,j-1) + sobel_x(5)*img_gray(i,j) + sobel_x(6)*img_gray(i,j+1) +...
sobel_x(7)*img_gray(i+1,j-1) + sobel_x(8)*img_gray(i+1,j) + sobel_x(9)*img_gray(i+1,j+1);
temp2 = sobel_y(1)*img_gray(i-1,j-1) + sobel_y(2)*img_gray(i-1,j) + sobel_y(3)*img_gray(i-1,j+1) +...
sobel_y(4)*img_gray(i,j-1) + sobel_y(5)*img_gray(i,j) + sobel_y(6)*img_gray(i,j+1) +...
sobel_y(7)*img_gray(i+1,j-1) + sobel_y(8)*img_gray(i+1,j) + sobel_y(9)*img_gray(i+1,j+1);
temp3 = sqrt(temp1^2 + temp2^2);
if (uint8(temp3) > thresh)
img_sobel(i,j) = 1;
% img_sobel(i,j) = uint8(temp3);
else
img_sobel(i,j) = 0;
end
end
end
end
Q = img_sobel;
figure;
imshow(img_sobel);