2017-03-18 91 views
1

我試圖在處理中實現我自己的閾值方法,但是當我嘗試在圖像上運行該方法時,我得到全黑圖像。任何幫助?閾值方法是將每個像素變成黑色

void threshold(PImage img) { 
    for (int i = 0; i < 300; i++) { 
    for (int j = 0; j < 300; j++) { 
     if (img.pixels[imgP(i, j)] >= 128) 
     img.pixels[imgP(i, j)] = 255; 
     else 
     img.pixels[imgP(i, j)] = 0; 
    } 
    } 
    img.updatePixels(); 
} 

int imgP(int i, int j) { 
    return i*300 + j; 
} 

回答

0

有一對夫婦的事情,以改善:

  1. 沒有硬編碼圖像尺寸(300,300),利用IMG的.width.height屬性:它會更容易重新使用您的代碼
  2. 如果您要遍歷每個像素,則不需要使用嵌套循環和imgP函數從ax,y位置計算像素索引。簡單地循環一次通過img.pixels(從0到img.pixels.length

在閾值條件失敗而言,捕捉的是條件,主要比較值:if (img.pixels[imgP(i, j)] >= 128)

如果要打印的像素的值,您會注意到該值不是從0到255. 您的圖像可能是RGB,因此像素值在不同的範圍內。 假設紅色,將-65536作爲有符號整數或0xFFFF0000(十六進制)(通知ARGB))。您的閾值不應該是128,而是-8355712FF808080)。

這裏的函數的重構版本:

void threshold(PImage img,int value) { 
    for(int i = 0 ; i < img.pixels.length; i++){ 
    if(img.pixels[i] >= color(value)){ 
     img.pixels[i] = color(255); 
    }else{ 
     img.pixels[i] = color(0); 
    } 
    } 
    img.updatePixels(); 
} 

這裏的樣品草圖修改後的版本從處理>例子>圖像> LoadDisplayImage

/** 
* Load and Display 
* 
* Images can be loaded and displayed to the screen at their actual size 
* or any other size. 
*/ 

PImage img; // Declare variable "a" of type PImage 

void setup() { 
    size(640, 360); 
    // The image file must be in the data folder of the current sketch 
    // to load successfully 
    img = loadImage("moonwalk.jpg"); // Load the image into the program 

} 

void draw() { 
    // Displays the image at its actual size at point (0,0) 
    image(img, 0, 0); 
    //copy the original image and threshold it based on mouse x coordinates 
    PImage thresh = img.get(); 
    threshold(thresh,(int)map(mouseX,0,width,0,255)); 

    // Displays the image at point (0, height/2) at half of its size 
    image(thresh, 0, height/2, thresh.width/2, thresh.height/2); 
} 
void threshold(PImage img,int value) { 
    for(int i = 0 ; i < img.pixels.length; i++){ 
    if(img.pixels[i] >= color(value)){ 
     img.pixels[i] = color(255); 
    }else{ 
     img.pixels[i] = color(0); 
    } 
    } 
    img.updatePixels(); 
} 
+0

非常感謝!你真的幫助我了! –

相關問題