Matlab 代码错误:未定义函数 'zernike_moments' 和 'subpixel_edge_detection'

这段 Matlab 代码试图实现使用 Zernike 矩进行亚像素边缘检测,但它包含一个错误:未定义函数 'zernike_moments' 和 'subpixel_edge_detection'

代码:

% 读取图像
image = imread('image.jpg');
image = rgb2gray(image);

% 使用Canny边缘检测算法获取二值化图像
bw_image = edge(image, 'canny');

% 计算图像的Zernike矩
order = 10; % Zernike矩的阶数
moments = zernike_moments(bw_image, order);

% 亚像素边缘检测
subpixel_image = subpixel_edge_detection(image, moments);

% 显示结果
figure;
subplot(1, 2, 1);
imshow(bw_image);
title('Binary Edge Image');
subplot(1, 2, 2);
imshow(subpixel_image);
title('Subpixel Edge Detection');

% Zernike矩计算函数
function moments = zernike_moments(image, order)
    [rows, cols] = size(image);
    moments = zeros(order+1, order+1);
    
    % 计算图像的归一化矩
    for p = 0:order
        for q = 0:order
            if mod(p+q, 2) == 0
                for x = 1:rows
                    for y = 1:cols
                        if image(x, y) > 0
                            rho = sqrt((2*x-rows-1)^2 + (2*y-cols-1)^2) / sqrt(rows^2 + cols^2);
                            theta = atan2((2*y-cols-1), (2*x-rows-1));
                            moments(p+1, q+1) = moments(p+1, q+1) + image(x, y) * zernike_polynomial(p, q, rho, theta);
                        end
                    end
                end
                moments(p+1, q+1) = moments(p+1, q+1) * ((p+1)/(pi*(rows*cols)));
            end
        end
    end
end

% Zernike多项式计算函数
function value = zernike_polynomial(p, q, rho, theta)
    value = 0;
    for s = 0:(p-q)/2
        value = value + (-1)^s * factorial(p-s) / (factorial(s) * factorial((p+q)/2-s) * factorial((p-q)/2-s)) * rho^(p-2*s);
    end
    value = value * sqrt((p+1)/pi) * cos(q*theta);
end

% 亚像素边缘检测函数
function subpixel_image = subpixel_edge_detection(image, moments)
    [rows, cols] = size(image);
    subpixel_image = zeros(rows, cols);
    
    for x = 1:rows
        for y = 1:cols
            if image(x, y) > 0
                rho = sqrt((2*x-rows-1)^2 + (2*y-cols-1)^2) / sqrt(rows^2 + cols^2);
                theta = atan2((2*y-cols-1), (2*x-rows-1));
                
                % 计算亚像素边缘位置
                subpixel_x = (rows+1)/2 + rho * cos(theta);
                subpixel_y = (cols+1)/2 + rho * sin(theta);
                
                % 判断亚像素边缘位置是否在图像范围内
                if subpixel_x >= 1 && subpixel_x <= rows && subpixel_y >= 1 && subpixel_y <= cols
                    subpixel_image(round(subpixel_x), round(subpixel_y)) = 255;
                end
            end
        end
    end
end

错误分析:

在代码中,zernike_momentssubpixel_edge_detection 函数的定义位于主脚本的末尾。然而,Matlab 要求在调用函数之前先定义函数。

解决方案:

zernike_momentssubpixel_edge_detection 函数的定义移至主脚本之前,或者将它们保存为独立的 .m 文件,并在主脚本中调用它们。

改进建议:

  • 使用更有意义的变量名,例如 zernikeMomentssubpixelEdgeImage
  • 添加注释以解释代码的功能。
  • 将代码分解为更小的、可重用的函数,以提高可读性和可维护性。

希望这些信息能帮助你解决代码错误!

Matlab 代码错误:未定义函数 zernike_moments 和 subpixel_edge_detection

原文地址: https://www.cveoy.top/t/topic/fv3P 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录