处理草图不会在屏幕上显示修改后的图像

时间:2013-07-16 09:03:58

标签: image-processing processing

我正在制作一个草图,其中包含以下内容:

  • 调整大图片的大小以使其适合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);
    }  
    

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

    1 个答案:

    答案 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>