【问题标题】:gray-scale image to matrix and matrix to gray-scale image灰度图像转矩阵和矩阵转灰度图像
【发布时间】:2018-10-18 07:45:59
【问题描述】:

我正在尝试从灰度图像中获取二维矩阵并对其进行修改,然后返回到灰度图像。

但是当尝试将图像转换为矩阵时,像素返回黑色值。

我怎样才能找到这个问题的解决方案?

您可以在代码下方找到图片

Java 代码:

public class MyImageProcessing {
    private SampleModel sampleModel;
    public int[][] compute(File file)
{
try 
{
    BufferedImage img= ImageIO.read(file);
    Raster raster=img.getData();
    sampleModel = raster.getSampleModel();
    int w=raster.getWidth(),h=raster.getHeight();
    int pixels[][]=new int[w][h];
    for (int x=0;x<w;x++)
    {
        for(int y=0;y<h;y++)
        {
            pixels[x][y]=raster.getSample(x,y,0);
        }
    }

    return pixels;

}
catch (Exception e)
{
    e.printStackTrace();
}
return null;
}


    public void getImage(int pixels[][])
{
     int w=pixels.length;
     int h=pixels[0].length;
      WritableRaster raster= Raster.createWritableRaster(sampleModel, new Point(0,0));
     for(int i=0;i<w;i++)
     {
         for(int j=0;j<h;j++)
         {
             raster.setSample(i,j,0,pixels[i][j]);
         }
     }
BufferedImage image=new BufferedImage(w,h,BufferedImage.TYPE_BYTE_GRAY);
image.setData(raster);
File output=new File("C:\\Users\\salam\\Pictures\\3.png");
try {
    ImageIO.write(image,"png",output);
}
catch (Exception e)
{
    e.printStackTrace();
}
}

}

原图:

从矩阵中检索到的图像:

【问题讨论】:

    标签: java image-processing


    【解决方案1】:

    试试这个代码。

    如果这不是您所需要的,那么也许您可以从我的帖子中获得的是代码应该始终整洁、可读、适当缩进和注释,所有这些都增加了程序的可理解性。

    注意:您的图像在转换为灰度时返回几乎相同的黑白图像,因为您的图像是黑白的,很像二值图像。

    我还可以推荐 OpenCV (https://opencv.org/),它是在 BSD 许可证下的,它简单、强大并且可用于 Java - 尽管我记得在 Ubuntu 16.04 上安装它时它是一个 PITA .

    import java.io.File;
    import java.io.IOException;
    import java.awt.image.BufferedImage;
    import javax.imageio.ImageIO;
    
    /**
     * This class converts images to grayscale color.
     */
    
    public class GrayscaleConverter {
    
    /**
     * Creates a new grayscaled BufferedImage object from the given source image
     * by averaging each pixels RGB value.
     * 
     * @param inputImageAbsPath the absolute path of the image file, including its name and extension.
     * @return a BufferedImage object.
     */
    private BufferedImage compute(String inputImageAbsPath) {
        
        System.out.println("... Converting source image to gray scale.");
        
        BufferedImage img = null; // image file
    
        // Read the source image or throw an exception
        try {
            img = ImageIO.read(new File(inputImageAbsPath));
        } catch(Exception e) {
            e.printStackTrace();
        }
    
        // Get the image width and height dimensions
        int width = img.getWidth();
        int height = img.getHeight();
    
        // Convert to grayscale by looping over pixels, beginning at top-most left coordinate (0,0)
        for (int y = 0; y < height; y++) { // y = rows
            for (int x = 0; x < width; x++) { // x = columns
        
                // Get the pixel value at this (x,y) coordinate
                int p = img.getRGB(x,y);
        
                // Extract the alpha, R, G, B values from pixel p
                int a = (p>>24) & 0xff; // Shift bits and unsign
                int r = (p>>16) & 0xff;
                int g = (p>>8) & 0xff;
                int b = p & 0xff;
        
                // Calculate average color (grayscale it)
                int avg = (r+g+b)/3;
        
                // Replace RGB value with avg
                p = (a<<24) | (avg<<16) | (avg<<8) | avg;
                img.setRGB(x, y, p);
            }
        }
        return img;
    }
    
    /**
     * Saves the converted grayscale image. This method builds the save path from the provided file name,
     * file extension, and absolute path of the folder that you want to save the image in.
     * 
     * @param path the absolute path of the folder that you would like to save the image inside.
     * @param imageName the name you would like to save the image with.
     * @param imageFileType the image file extension, without the dot (.) preceding the image file type.
     * @param image the BufferedImage object returned from the compute method.
     */
    private void saveImage(String path, String imageName, String imageFileType, BufferedImage image) {
        
        // Save or throw exception
        try {
            System.out.println("... Saving grayscale image to "
                    + path.concat("\\").concat(imageName).concat(".").concat(imageFileType)); // save path displayed to user
            
            ImageIO.write(image,
                        imageFileType,
                        new File(path.concat("\\").concat(imageName).concat(".").concat(imageFileType)));
            
        } catch(Exception e) {
            e.printStackTrace();
        }
        System.out.println("... Image saved.");
    }
    
    
    // Driver
    public static void main(String args[]) throws IOException {
        
        /*
         * Tested for .png and .jpg files. Both worked successfully.
         */
        
        // Test
        System.out.println("Testing GrayscaleConverter.\n");
        
        String input = "*source images absolute file path including name and extension*";
        String outputPath = "*absolute path to folder where you will save grayscale image in*";
        String outputFileName = "*save image with this name*";
        String outputFileType = "*save image with this file extension (no dot (.) e.g. png or jpg)*";
        
        GrayscaleConverter gsc = new GrayscaleConverter();
        BufferedImage convertedImage = gsc.compute(input);
        gsc.saveImage(outputPath, outputFileName, outputFileType, convertedImage );
        
        System.out.println("\nTest complete.");
    }
    

    }

    您提供的输入图片:

    您的输出图片:

    另一个示例输入图像:

    另一个示例输出图像:

    我用 .png 和 .jpg 图像文件测试了我的程序,它工作正常。祝你好运。

    【讨论】:

    • 亲爱的,我想从该项目中从灰度图像中提取二维矩阵并使用盐过滤器对其进行修改,然后从修改后的矩阵中检索图像。
    • 嗨,Semo,使用我的代码获取灰度图像。然后至少您可以使用灰度图像,您可以在其中应用“盐”过滤器,然后保存该图像。早些时候,我尝试使用 BufferedImage.TYPE_BYTE_GREY/BINARY/INDEX 并且背景始终是黑色的,所以我认为您正在以一种“时髦”的方式读取像素值,这种方式有效但不是有意的。相信我,看看 OpenCV 在图像处理方面的惊人之处。我发现 Raster API 混淆了这种情况,我对此了解不多。祝你好运。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-03
    • 2020-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-09
    相关资源
    最近更新 更多