2016-05-12 68 views
0

我最近开始使用java中的图像。 我想实现一个基于颜色的基本运动跟踪系统(我知道这不会很有效,但它只是用于测试)。浏览图片的每个像素

现在我想用Java处理图像。 我想删除RGB图像中的所有颜色,而不是一个颜色或一系列颜色。

现在我还没有找到一个好的解决方案。我希望它尽可能保持简单,并尽量不要使用除标准Java之外的任何其他库。

+0

到目前为止发现了什么? –

回答

1

随着BufferedImage(java中的标准图像类),你有两个“好”的解决方案来访问像素。

1 - 使用栅格更容易,因为它自动处理编码,但速度较慢。

WritableRaster wr = image.getRaster() ; 
for (int y=0, nb=0 ; y < image.getHeight() ; y++) 
    for (int x=0 ; x < image.getWidth() ; x++, nb++) 
     { 
     int r = wr.getSample(x, y, 0) ; // You just give the channel number, no need to handle the encoding. 
     int g = wr.getSample(x, y, 1) ; 
     int b = wr.getSample(x, y, 2) ; 
     } 

2 - 使用DataBuffer,最快,因为直接访问像素,但你必须处理编码。

switch (image.getType()) 
    { 
    case BufferedImage.TYPE_3BYTE_BGR : // Classical color images encoding. 
     byte[] bb = ((DataBufferByte)image.getRaster().getDataBuffer()).getData() ; 
     for (int y=0, pos=0 ; y < image.getHeight() ; y++) 
      for (int x=0 ; x < image.getWidth() ; x++, pos+=3) 
       { 
       int b = bb[pos] & 0xFF ; 
       int g = bb[pos+1] & 0xFF ; 
       int r = bb[pos+2] & 0xFF ; 
       } 
     break ; 
    } 

getRGB()很简单,但比光栅慢很多,所以只是禁止它。