MATLAB图像处理:条纹长度测量与代码优化

本文将介绍使用MATLAB对图像进行条纹长度测量的完整流程,并提供代码示例和详细解释。

1. 代码示例

% 读取原始图像
img = imread('7-1.tif');

% 将图像二值化
bw_img = imbinarize(img);

% 进行骨架化操作
skel_img = bwmorph(bw_img, 'skel', Inf);

% 消除分支条纹
branchpoints = bwmorph(skel_img, 'branchpoints');
endpoints = bwmorph(skel_img, 'endpoints');
skel_img = skel_img & ~(branchpoints | endpoints);
skel_img = bwareaopen(skel_img, 3);

% 计算条纹长度
pixel_size = 0.0595; % 纳米/像素
skel_props = regionprops(skel_img, 'PixelList');
stripe_lengths = [];
for i = 1:length(skel_props)
    stripe_pixels = skel_props(i).PixelList;
    if size(stripe_pixels, 1) >= 3
        stripe_length = 0;
        for j = 1:size(stripe_pixels, 1)
            if j < size(stripe_pixels, 1) && abs(stripe_pixels(j, 1) - stripe_pixels(j+1, 1)) == 1 && abs(stripe_pixels(j, 2) - stripe_pixels(j+1, 2)) == 1 % 对角线像素长度为2倍像素大小
                stripe_length = stripe_length + 2 * pixel_size;
            else
                stripe_length = stripe_length + pixel_size;
            end
        end
        if stripe_length >= 0.483 % 剔除长度小于0.483 nm的条纹
            stripe_lengths(end+1) = stripe_length;
        end
    end
end

% 统计数据和图像展示
mean_length = mean(stripe_lengths);
max_length = max(stripe_lengths);
min_length = min(stripe_lengths);
num_stripes = length(stripe_lengths);

figure;
subplot(1, 2, 1); imshow(img);
title('Original Image');
subplot(1, 2, 2); imshow(skel_img);
title(sprintf('Skeletonized Image
%d stripes found', num_stripes));

fprintf('Mean length: %.3f nm
', mean_length);
fprintf('Maximum length: %.3f nm
', max_length);
fprintf('Minimum length: %.3f nm
', min_length);

2. 代码解释

  • 读取原始图像: img = imread('7-1.tif'); 使用 imread 函数读取名为 7-1.tif 的图像文件。
  • 二值化图像: bw_img = imbinarize(img); 使用 imbinarize 函数将原始图像转换为二值图像。
  • 进行骨架化操作: skel_img = bwmorph(bw_img, 'skel', Inf); 使用 bwmorph 函数对二值图像进行骨架化操作,将图像转换为单像素宽度的线条。
  • 消除分支条纹: 使用 bwmorph 函数的 'branchpoints''endpoints' 属性找到分支点和端点,并将其从骨架图像中移除。
  • 计算条纹长度: 使用 regionprops 函数提取骨架图像中每个条纹的像素列表,然后计算每个条纹的长度。
  • 统计数据和图像展示: 使用 meanmaxmin 函数计算条纹长度的平均值、最大值、最小值,并使用 figuresubplotimshow 函数显示原始图像和骨架化图像。

3. 错误解决

在原始代码中,出现错误 错误使用 bwmorph 第 1 个输入, BW, 应为 二维。 这是因为在进行骨架化操作之前,二值化的图像没有正确生成。修改后的代码如下:

img = imread('7-1.tif');
bw_img = imbinarize(img);
skel_img = bwmorph(bw_img, 'skel', Inf);
branchpoints = bwmorph(skel_img, 'branchpoints');
endpoints = bwmorph(skel_img, 'endpoints');
skel_img = skel_img & ~(branchpoints | endpoints);
skel_img = bwareaopen(skel_img, 3);

4. 总结

本示例展示了使用MATLAB进行图像处理的基本流程,包括图像读取、二值化、骨架化、条纹长度计算和统计分析。需要注意的是,在进行代码优化时,要确保代码的正确性,并针对具体问题进行调整。

5. 代码优化建议

  • 使用 bwconncomp 函数代替 regionprops 函数,可以提高代码效率。
  • 使用向量化操作代替循环,可以进一步提高代码效率。
  • 使用 improfile 函数可以更加方便地测量条纹的长度。
MATLAB图像处理:条纹长度测量与代码优化

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

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