我想将彩色图像转换为灰度并将其保存在文件中..

时间:2013-11-17 12:13:40

标签: java

我的下面的代码保存图像..但它不是黑白的...它是黑色或白色.. 请帮忙..如果有任何错误..帮助我:( 和朋友们请尽量帮助我使用相同的代码本身..我现在不会理解任何其他代码..帮助...... !!! (此代码是我实现反向传播算法的整个代码的一部分)

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import java.awt.Color;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class PrintImageARGBPixels
{

    public static void main(String args[])throws IOException
    {   
        //extracting RGB values of each pixel of an image.

        BufferedImage image = ImageIO.read(new 
            File("C:\\Users\\ark\\Desktop\\project_doc\\logo_1004.jpg"));
        int total_pixels=1;
        float sum=0;
        ArrayList <Color> arr = new ArrayList<Color>();
        ArrayList <Float> grey_f = new ArrayList<Float>();
        System.out.println("Image Dimension: Height-" + h + ", Width-"+ w);
        int w = image.getWidth();
        int h = image.getHeight();
        total_pixels=(h * w);
        for(x=0;x<w;x++)
        {
            for(y=0;y<h;y++)
            {
                int rgb = image.getRGB(x, y);
                Color c = new Color(rgb);
                arr.add(c);
            }
        }
        for(int i=0;i<total_pixels;i++)
        {
            sum=(arr.get(i).getRed()+arr.get(i).getGreen()+arr.get(i).getBlue())/(3*255);
            grey_f.add(sum);
        }
        for(int i=0;i<total_pixels;i++)
        {
            Color co=new Color(grey_f.get(i),grey_f.get(i),grey_f.get(i));
            int rgb_1=co.getRGB();
            for(x=0;x<w;x++)
            {
                for(y=0;y<h;y++)
                {
                    image.setRGB(x,y,rgb_1);
                }
            }
        }
        ImageIO.write(image, "png", new 
            File("C:\\Users\\ark\\Desktop\\project_doc\\multi_gray.png"));
    }
}

2 个答案:

答案 0 :(得分:1)

对于您获得的每个RGB值,请执行

Color c = new Color(rgb);

int gr = (c.getRed() + c.getGreen() + c.getBlue())/3;

Color greyScale = new Color(gr, gr, gr);

希望这有帮助。

答案 1 :(得分:0)

我想问题出现在sum=arr.get(i).getRed()+arr.get(i).getGreen()+arr.get(i).getBlue())/(3*255);,因为它返回0或1的int。实际上只需要除以3以获得[[1}}范围内的值0255]。