【问题标题】:Sum of rectangles in MatlabMatlab中的矩形总和
【发布时间】:2019-02-05 15:13:46
【问题描述】:

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

我的代码:

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

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

【问题讨论】:

  • 这不是你在做的吗?据我所知,您正在遍历您的窗口并分别对Nh 和Nd 求和。您可能需要稍微澄清一下您的问题。
  • 对不起!我的意思是分开 Nh 和 Nd,因为我需要所有幻灯片的 sum Nh 和所有幻灯片的 sumNd。现在我只得到一张幻灯片的 Nh 和 Nd。
  • 我还是不明白你的意思。很高兴您添加了代码,但也许您可以添加伪代码或其他内容来显示您真正想要的内容。
  • 我编辑了我的问题。我不知道我怎么了,我无法解释这个简单的事情。

标签: matlab image-processing


【解决方案1】:

您只需要在第一个和第二个 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

【讨论】:

  • 谢谢!实际上,代码运行良好,它可以很好地计算非零值,但是对于一张幻灯片,我需要计算所有幻灯片的总和。
  • 我已经修改了答案,将某个目录中所有 jpg 图像的 Nh 和 Nd 相加。
  • 非常感谢!你是最棒的!
猜你喜欢
  • 1970-01-01
  • 2015-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-14
  • 1970-01-01
  • 2019-07-12
  • 1970-01-01
相关资源
最近更新 更多