[英]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.