我最近开始使用java中的图像。 我想实现一个基于颜色的基本运动跟踪系统(我知道这不会非常有效,但它只是用于测试)。
现在我想用Java处理图像。 我想删除RGB图像中的所有颜色而不是一个或代替一系列颜色。
现在我还没有找到一个好的解决方案。 我希望它保持尽可能简单,尽量不要使用除标准Java之外的任何其他库。
I recently started working with images in java. I want to implement a basic motion-tracking system based on colors (I know that this won't be very efficient, but it is just for testing).
Right now I want to process an image in Java. I want to delete all Colors in a RGB image instead of one or instead of a range of colors.
Right now I haven't found a good solution. I want it to keep it as simple an possible and try not to use any other libraries than the standard ones of Java.
最满意答案
使用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()很容易,但比光栅慢得多,也不容易,所以请禁止它。
With the BufferedImage (standard image class in java), you have two "good" solutions to access the pixels.
1 - Using the raster, easier because it automatically handles the encoding, but it is slower.
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 - Using the DataBuffer, fastest because direct access to the pixels, but YOU have to handle the encoding.
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() is easy but much slower and not easier than the raster, so just ban it.
更多推荐
Java,want,电脑培训,计算机培训,IT培训"/> <meta name="description" c
发布评论