繁体   English   中英

仅限Matlab代码如果像素值超过给定的阈值,则计算像素数而不是它们的总和

[英]Matlab Code only Calculating number of pixels and not their sum, if pixel value falls above given Threshold value

K = imread('test.jpg');                               // read image 
countif=0;countelse=0;                                // declare variables
addif=0;addelse=0;
counttotal=0; temp=0;        
[M N] = size(K);                                      // calculate the size of the image
for x=1:M                                             // X-Axis
    for y=1:N                                         // Y-Axis

                temp=K(x,y);                          // Pixel Value at location(x,y)

                if (temp<50)                          // If value of pixel is below threshold value 50 
                    addif =  addif + temp;            // Add to get sum of all these pixels
                    countif = countif + 1;            // Counter to get total number of such pixels 


                else                                  // If pixel value is above threshold limit i.e 50
                 countelse = countelse + 1;           // Add to get sum of all these pixels
                 addelse=   addelse + temp;           // Counter to get total number of such pixels 
                end

        counttotal=counttotal+1;                     // Total rotation counter
    end
end

在上面给出的代码中,名为'countif'和'countelse'的计数器正常工作,但变量'addif'和'addelse'中的值不是应该的。

您可以为此使用逻辑索引

tresholdMask = (K < 50); %array of the same size as k with 1s where K<50 and 0s elsewhere
numOfPixels = sum(thresholdMask(:)); %number of 1s in the mask
sumOfPixels = sum(K(:).*thresholdMask(:)); %sum of all the pixels where the mask is 1

解:-

替换它: K = imread('test.jpg'); 用这个: K = double(imread('test.jpg'))

或者,如果要保留unit8类的Ktemp ,而不是上面的修复,请执行以下操作:替换此addif = addif + temp; 用这个: addif = addif + double(temp); 这个addelse= addelse + temp; 用这个: addelse= addelse + double(temp);

说明:-

temp类是uint8 ,因为K类是uint8因此你得到的addifaddelse也变成了unit8 ,它不能存储超过255值。 通过将K转换为double ,您使用它的所有下一个变量将变为我在第一个提出的解决方案中所做的double 或者,如果您想保持Ktemp的类相同,则可以使用第二个建议的解决方案。

您可以在命令窗口中使用whos来检查变量类。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM