如何提高此 Matlab 代码可用性



我正在编写一个读取 12 个 rgb 图像的代码(图像是黑色背景上的彩色圆圈(,并对它们进行一些计算以计算圆圈的光斑大小。我将展示一个计算示例,该计算使:

% read images
image_1=readNPY('image_1.npy');
image_2=readNPY('image_2.npy');
...
image_12=readNPY('image_12.npy');
% change from type uint16 to double and calculate the maximum
image1=double(image_1);
image1MAX=max(max(image1));
...
image12=double(image_12);
image12MAX=max(max(image12));
% normalizes to the maximum
reference = exp(-1)
IMAGE1=fix(image1./image1MAX/reference);
...
IMAGE12=fix(image12./image12MAX/reference);
% calculate the spot size
spot_image1 = 2*sqrt(size(nonzeros(IMAGE1),1)/pi)/1000;
...
spot_image12 = 2*sqrt(size(nonzeros(IMAGE12),1)/pi)/1000;
% plot the spot size
spot = [spot_image1 spot_image2 ... spot_image12]
xvalue = [1 2 3 4 5 6 7 8 9 10 11 12]
plot(xvalue, spot)

代码运行良好,我的问题是:如果我有 52 张图像而不是 12 张图像,我是否必须为每个计算添加 40 行,或者有更智能的实现方法?(希望你能理解我的疑惑,谢谢!

假设您的图像文件名采用以下格式:

">image_1.npy", ">image_2.npy", ...">image_10.npy", ">image_11.npy"...

选项 1 - 使用单元格和数字数组:您可以在单元格数组

中生成文件名并在循环中读取它们,使用单元格和数字数组计算每个图像的数据:

% Number of image files
mumImages = 112;
% Generate image file names with desired format
imageNames = compose('image_%d.npy', 1:mumImages);
% Initialize cell arrays and numeric arrays (recommended, not required)
image_ = cell(size(imageNames));
image = cell(size(imageNames));
imageMAX = cell(size(imageNames));
IMAGE = cell(size(imageNames));
spot = zeros(size(imageNames));
% Populate the cell arrays and numeric arrays
for i = 1:mumImages
    image_{i} = readNPY(imageNames{i});
    image{i} = double(image_{i});
    imageMAX{i} = max(max(image{i}));
    % normalizes to the maximum
    reference = exp(-1);
    IMAGE{i} = fix(image{i}./imageMAX{i}/reference);
    % calculate the spot size
    spot(i) = 2*sqrt(size(nonzeros(IMAGE{i}),1)/pi)/1000;
end
% plot the spot size
plot(1:mumImages, spot)

选项 2 - 使用 stuct 数组:您可以对 stuct 数组执行与上述相同的操作

% Number of image files
mumImages = 112;
% Genrate image file names with desired format
imageNames = compose('image_%d.npy', 1:mumImages);
% Initialize a struct with desired fields (recommended, not required)
C = repmat(struct('image_',[], 'image', [], 'imageMAX', [], 'IMAGE', [], 'spot', []), mumImages, 1 );
% Populate the struct array fields
for i = 1:mumImages
    C(i).image_ = readNPY(imageNames{i});
    C(i).image = double(C(i).image_);
    C(i).imageMAX = max(max(C(i).image));
    % normalizes to the maximum
    reference = exp(-1);
    C(i).IMAGE = fix(C(i).image./C(i).imageMAX/reference);
    % calculate the spot size
    C(i).spot = 2*sqrt(size(nonzeros(C(i).IMAGE),1)/pi)/1000;
end
% plot the spot size
plot(1:mumImages, [C.spot])

最新更新