0

我正在制作一个草图,它执行以下操作:

  • 调整大图像的大小以适应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);
    }  
    

    但是,只显示彩色图像:(
    我知道该算法有效,因为我已经在其他图像上尝试过它(不使用这个草图)。
    出了什么问题?

    4

    1 回答 1

    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()方法有问题。

    于 2013-07-16T09:22:28.303 回答