簡體   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