繁体   English   中英

在java中将像素值设置为灰度等级时,丢失图像部分

[英]loss of image parts while setting pixel values to 0 and 1 from grayscale in java

我正在使用java进行图像处理。 我读取灰度图像并将像素值转换为0和1我只为一些图像正确获得了输出图像。 在其他一些图像部分丢失在这里是我用来使图像阵列回到图像的代码

`BufferedImage I = ImageIO.read(new File("path"));
 SampleModel sampleModel;
 Raster pixelData;
 pixelData = I.getData();
 int[][] pixels=new int[wid][hgt];
 sampleModel=pixelData.getSampleModel();



 BufferedImage image=new BufferedImage(wid,hgt,BufferedImage.TYPE_BYTE_BINARY);
 WritableRaster raster=Raster.createWritableRaster(sampleModel,new Point(0,0));
     for(int i=0;i<wid;i++)
     {
         for(int j=0;j<hgt;j++)
         {
            raster.setSample(i,j,0,pixels[i][j]);
         }
     }
     image.setData(raster);

File output=new File("path");
    ImageIO.write(image,"png",output);
 System.out.println("..End..");`

图像的大小与原始大小相同,但整个大小只包含原始图像的一部分。大家帮帮我

您的问题可能与您使用的样本模型有关。 样本模型负责描述Raster如何存储数据,也许您正在使用一个模型,每个像素放置更多信息,然后图像只获得原始缓冲区的一部分。

干杯

[更新] @Joop Egen是正确的,您需要使用您定义的图像中的样本模型,即每个像素使用灰度字节“配置”

得到了我的问题的gud答案它适用于所有图像(包括24位和8位图像)

 BufferedImage I = ImageIO.read(new File("path"));
 Raster pixelData;
 pixelData = I.getData();
 int pixels[][]=new int[wid][hgt];


     for ( x=0;x<wid;x++)
     {
         for( y=0;y<hgt;y++)
         {
             pixels[x][y]=pixelData.getSample(x,y,0);
          }  
     }


 BufferedImage image=new BufferedImage(wid,hgt,BufferedImage.TYPE_BYTE_BINARY);
 ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
 int[] nBits = { 8 };
 ColorModel cm = new ComponentColorModel(cs, nBits, false, true,Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
 SampleModel sm = cm.createCompatibleSampleModel(wid, hgt);
 WritableRaster raster=Raster.createWritableRaster(sm,new Point(0,0));
     for(int i=0;i<wid;i++)
     {
         for(int j1=0;j1<hgt;j1++)
         {
            raster.setSample(i,j1,0,pixels[i][j1]);
         }
     }
  image.setData(raster);
  File output=new File("path");
  ImageIO.write(image,"png",output);` 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM