首页 > 解决方案 > Matlab中的矩形总和

问题描述

我有一个无法按我想要的方式工作的代码。问题是我需要一张图片中所有矩形的总和,如下所示。

我的代码:

imH = size(I, 1);
imW = size(I, 2);


windowWidth = 30;
windowHeight = 30;

step = 1;
for r = 1:step:imH - windowHeight + 1
    for c = 1:step:imW - windowWidth + 1


        Win = I(r:r + windowHeight - 1, c:c + windowWidth - 1, :);

        post =[c r windowHeight windowWidth];

我想我在这里缺少总和

    %stop = waitforbuttonpress; 


    subplot(121); imshow(I); title 'Image';
    hold on;  

    rectangle('Position', pos, 'EdgeColor', 'r');

    hold off;

    subplot (122); imshow(W); title 'ooo';
    drawnow;
    pause(0.0000001);



    end 

end

一切都很好,但我需要分别对每个矩形值求和

标签: matlabimage-processing

解决方案


您只需要添加&第一个和第二个 rgb 间隔,如下所示:

matchNh = (R > 45 & R < 180) & (G > 50 & G < 185) & (B > 160 & B < 215);  
matchNd = (R > 40 & R < 115) & (G > 6 & G < 80) & (B > 10 & B < 75);

然后你正在做正确的计算非零像素,即

Nh = nnz(matchNh);
Nd = nnz(matchNd);

如果您想用于多个图像,那么您可以在两个 for 循环之外使用另一个 for 循环,例如

imgnames = dir('*.jpg');    % get list of jpg images in current directory
NN = length(imgnames)
%sliding window size
windowWidth = 64;
windowHeight = 64;

%step
step = 64;

Nh = 0;
Nd = 0;

for ii = 1 : NN
    I = imread(imgnames(ii).name);
    % your code i.e. two for loops as you have written above
    imH = size(I, 1);
    imW = size(I, 2);


    for r = 1:step:imH - windowHeight + 1
        for c = 1:step:imW - windowWidth + 1

        %sliding window value
        W = I(r:r + windowHeight - 1, c:c + windowWidth - 1, :);

        pos =[c r windowHeight windowWidth];

        R = W(:,:,1);
        G = W(:,:,2);
        B = W(:,:,3);

        % RGB intervals for every sliding window
        matchNh = (R > 45 & R < 180) & ...
                  (G > 50 & G < 185) & ...        
                 (B > 160 & B < 215);  

        matchNd = (R > 40 & R < 115) & ...
                  (G > 6 & G < 80) & ...
                  (B > 10 & B < 75);
        Nh = Nh + nnz(matchNh);
        Nd = Nd + nnz(matchNd);


        end
    end
    PIc = Nd / (Nh + Nd)
end

推荐阅读