以图片为输入,制作灰度和&然后输出 [英] Taking a picture as input, Make grey scale and & then outputting

查看:157
本文介绍了以图片为输入,制作灰度和&然后输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将图片作为输入,然后操纵所述图片(我特意想让它成为灰度),然后输出新图像。这是我正在编辑的代码片段,但是我遇到了困难。关于我可以改变/做什么的任何想法。非常感谢!

I'm attempting to take a picture as input, then manipulate said picture (I specifically want to make it greyscale) and then output the new image. This is a snippet of the code that I'm editing in order to do so but I'm getting stuck. Any ideas of what I can change/do next. Greatly appreciated!

public boolean recieveFrame (Image frame) {
    int width = frame.width();
    int height = frame.height();

    for (int i = 0; i < width; i++) {
        for (int j = 0; j < height; j++) {
            Color c1 = frame.get(i, j);
            double greyScale = (double) ((Color.red *.3) + (Color.green *.59) + (Color.blue * .11));
            Color newGrey = Color.greyScale(greyScale);
            frame.set(i, j, newGrey);
        }
    }

    boolean shouldStop = displayImage(frame); 
    return  shouldStop;
}


推荐答案

我要试试尽可能接近你已经拥有的东西。所以,我假设您正在寻找如何在 Image 上进行像素级处理,而不仅仅是寻找适合转换为灰度的技术。

I'm going to try to stick as close as possible to what you already have. So, I'll assume that you are looking for how to do pixel-level processing on an Image, rather than just looking for a technique that happens to work for converting to greyscale.

第一步是您需要图像为 BufferedImage 。这是默认情况下从 ImageIO 获得的,但如果您有其他类型的图像,则可以创建 BufferedImage 并首先将其他图像绘制到其中:

The first step is that you need the image to be a BufferedImage. This is what you get by default from ImageIO, but if you have some other type of image, you can create a BufferedImage and paint the other image into it first:

BufferedImage buffer = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g = buffer.createGraphics();
g.drawImage(image, 0, 0);
g.dispose()

然后,您可以对像素进行操作:

Then, you can operate on the pixels like this:

public void makeGrey(BufferedImage image) {
   for(int x = 0; x < image.getWidth(); ++x) {
      for(int y = 0; y < image.getHeight(); ++y) {
         Color c1 = new Color(image.getRGB(x, y));
         int grey = (int)(c1.getRed() * 0.3 
                        + c1.getGreen() * 0.59 
                        + c1.getBlue() * .11
                        + .5);
         Color newGrey = new Color(grey, grey, grey);
         image.setRGB(x, y, newGrey.getRGB());
      }
   }
}

请注意,此代码非常可怕慢。一个更快的选择是将BufferedImage中的所有像素提取到 int [] 中,对其进行操作,然后将其重新设置为图像。这将使用您在javadoc中找到的 setRGB() / getRGB()方法的其他版本。

Note that this code is horribly slow. A much faster option is to extract all the pixels from the BufferedImage into an int[], operate on that, and then set it back into the image. This uses the other versions of the setRGB()/getRGB() methods that you'll find in the javadoc.

这篇关于以图片为输入,制作灰度和&amp;然后输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆