有一對夫婦的事情,以改善:
- 沒有硬編碼圖像尺寸(300,300),利用IMG的
.width
和.height
屬性:它會更容易重新使用您的代碼
- 如果您要遍歷每個像素,則不需要使用嵌套循環和
imgP
函數從ax,y位置計算像素索引。簡單地循環一次通過img.pixels
(從0到img.pixels.length
)
在閾值條件失敗而言,捕捉的是條件,主要比較值:if (img.pixels[imgP(i, j)] >= 128)
如果要打印的像素的值,您會注意到該值不是從0到255. 您的圖像可能是RGB,因此像素值在不同的範圍內。 假設紅色,將-65536
作爲有符號整數或0xFFFF0000
(十六進制)(通知ARGB
))。您的閾值不應該是128
,而是-8355712
(FF808080
)。
這裏的函數的重構版本:
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();
}
非常感謝!你真的幫助我了! –