我如何改善Matlab代码的可用性

时间:2019-06-02 17:47:13

标签: image 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行,或者有一种更智能的实现方法? (希望您能理解我的疑虑,谢谢!)

1 个答案:

答案 0 :(得分:0)

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

' image_1.npy ',' image_2.npy ',...' image_10.npy ',' image_11 .npy '...

选项1-使用单元格和数字数组:您可以在单元格数组中生成文件名并循环读取它们,使用单元格和数字数组计算每个图像的数据:< / p>

% 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-使用结构数组:您可以对结构数组执行与上述相同的操作

% 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])