我正在制作一个草图,其中包含以下内容:
800 x 600
屏幕。 Done
消息
一切正常,期望它不能正确显示图像。
这是黑白效果:
void blackAndWhite() {
loadPixels();
for (int i = 0;i < img.pixels.length;i++) {
int pixel = img.pixels[i];
// println("Working on pixel " + i + " out of " + img.pixels.length);
int red = (int) red(pixel);
int green = (int) green(pixel);
int blue = (int) blue(pixel);
/*
* Luminosity Method.
*/
// red = (int) (red * 0.21);
// green = (int) (green * 0.71);
// blue = (int) (blue * 0.07);
/*
* Average Method
*/
// float avg = (int) (red + green + blue / 3);
// red = green = blue = (int) avg;
/*
* Lightness Method
*/
int mostProminent = max(red, green, blue);
int leastProminent = min(red, green, blue);
int avg = (int) ((mostProminent + leastProminent) / 2);
red = green = blue = avg;
pixel = color(red, green, blue);
img.pixels[i] = pixel;
}
println("Done");
updatePixels();
image(img, WIDTH/2, HEIGHT/2, calculatedWidth, calculatedHeight);
}
但是,只显示彩色图像:(
我知道算法有效,因为我在其他图像上尝试过(不使用此草图)
出了什么问题?
答案 0 :(得分:2)
以下代码可以正常使用:
PImage img;
void setup () {
img = loadImage ("img.png");
size(img.width, img.height);
}
void draw () {
image(img, 0, 0);
}
void keyReleased () {
blackAndWhite();
}
void blackAndWhite() {
img.loadPixels();
for (int i = 0;i < img.pixels.length;i++) {
int pixel = img.pixels[i];
// println("Working on pixel " + i + " out of " + img.pixels.length);
int red = (int) red(pixel);
int green = (int) green(pixel);
int blue = (int) blue(pixel);
/*
* Luminosity Method.
*/
// red = (int) (red * 0.21);
// green = (int) (green * 0.71);
// blue = (int) (blue * 0.07);
/*
* Average Method
*/
// float avg = (int) (red + green + blue / 3);
// red = green = blue = (int) avg;
/*
* Lightness Method
*/
int mostProminent = max(red, green, blue);
int leastProminent = min(red, green, blue);
int avg = (int) ((mostProminent + leastProminent) / 2);
red = green = blue = avg;
pixel = color(red, green, blue);
img.pixels[i] = pixel;
}
println("Done");
img.updatePixels();
}
我的猜测是你忘了写 img .loadPixels()而不是loadPixels(),或者草图的 draw()方法出错了。< / p>