[英]Java - get pixel array from image
我正在尋找從BufferedImage
獲取像素數據(int int[][]
形式)的最快方法。 我的目標是能夠使用int[x][y]
從圖像中處理像素(x, y)
。 我發現的所有方法都沒有這樣做(它們中的大多數返回int[]
s)。
我只是在玩同樣的主題,這是訪問像素的最快方法。 我目前知道這樣做的兩種方法:
getRGB()
方法。通過使用直接訪問像素數組:
byte[] pixels = ((DataBufferByte) bufferedImage.getRaster().getDataBuffer()).getData();
如果您正在處理大圖像並且性能是一個問題,那么第一種方法絕對不是 go 的方法。 getRGB()
方法將 alpha、red、green 和 blue 值組合到一個 int 中,然后返回結果,在大多數情況下,您將執行相反的操作來取回這些值。
第二種方法將直接返回每個像素的紅色、綠色和藍色值,如果有 alpha 通道,它將添加 alpha 值。 使用這種方法在計算指數方面更難,但比第一種方法快得多。
在我的應用程序中,只需從第一種方法切換到第二種方法,我就能將處理像素的時間減少 90% 以上!
這是我設置的比較兩種方法的比較:
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.IOException;
import javax.imageio.ImageIO;
public class PerformanceTest {
public static void main(String[] args) throws IOException {
BufferedImage hugeImage = ImageIO.read(PerformanceTest.class.getResource("12000X12000.jpg"));
System.out.println("Testing convertTo2DUsingGetRGB:");
for (int i = 0; i < 10; i++) {
long startTime = System.nanoTime();
int[][] result = convertTo2DUsingGetRGB(hugeImage);
long endTime = System.nanoTime();
System.out.println(String.format("%-2d: %s", (i + 1), toString(endTime - startTime)));
}
System.out.println("");
System.out.println("Testing convertTo2DWithoutUsingGetRGB:");
for (int i = 0; i < 10; i++) {
long startTime = System.nanoTime();
int[][] result = convertTo2DWithoutUsingGetRGB(hugeImage);
long endTime = System.nanoTime();
System.out.println(String.format("%-2d: %s", (i + 1), toString(endTime - startTime)));
}
}
private static int[][] convertTo2DUsingGetRGB(BufferedImage image) {
int width = image.getWidth();
int height = image.getHeight();
int[][] result = new int[height][width];
for (int row = 0; row < height; row++) {
for (int col = 0; col < width; col++) {
result[row][col] = image.getRGB(col, row);
}
}
return result;
}
private static int[][] convertTo2DWithoutUsingGetRGB(BufferedImage image) {
final byte[] pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
final int width = image.getWidth();
final int height = image.getHeight();
final boolean hasAlphaChannel = image.getAlphaRaster() != null;
int[][] result = new int[height][width];
if (hasAlphaChannel) {
final int pixelLength = 4;
for (int pixel = 0, row = 0, col = 0; pixel + 3 < pixels.length; pixel += pixelLength) {
int argb = 0;
argb += (((int) pixels[pixel] & 0xff) << 24); // alpha
argb += ((int) pixels[pixel + 1] & 0xff); // blue
argb += (((int) pixels[pixel + 2] & 0xff) << 8); // green
argb += (((int) pixels[pixel + 3] & 0xff) << 16); // red
result[row][col] = argb;
col++;
if (col == width) {
col = 0;
row++;
}
}
} else {
final int pixelLength = 3;
for (int pixel = 0, row = 0, col = 0; pixel + 2 < pixels.length; pixel += pixelLength) {
int argb = 0;
argb += -16777216; // 255 alpha
argb += ((int) pixels[pixel] & 0xff); // blue
argb += (((int) pixels[pixel + 1] & 0xff) << 8); // green
argb += (((int) pixels[pixel + 2] & 0xff) << 16); // red
result[row][col] = argb;
col++;
if (col == width) {
col = 0;
row++;
}
}
}
return result;
}
private static String toString(long nanoSecs) {
int minutes = (int) (nanoSecs / 60000000000.0);
int seconds = (int) (nanoSecs / 1000000000.0) - (minutes * 60);
int millisecs = (int) ( ((nanoSecs / 1000000000.0) - (seconds + minutes * 60)) * 1000);
if (minutes == 0 && seconds == 0)
return millisecs + "ms";
else if (minutes == 0 && millisecs == 0)
return seconds + "s";
else if (seconds == 0 && millisecs == 0)
return minutes + "min";
else if (minutes == 0)
return seconds + "s " + millisecs + "ms";
else if (seconds == 0)
return minutes + "min " + millisecs + "ms";
else if (millisecs == 0)
return minutes + "min " + seconds + "s";
return minutes + "min " + seconds + "s " + millisecs + "ms";
}
}
你能猜到 output 嗎? ;)
Testing convertTo2DUsingGetRGB:
1 : 16s 911ms
2 : 16s 730ms
3 : 16s 512ms
4 : 16s 476ms
5 : 16s 503ms
6 : 16s 683ms
7 : 16s 477ms
8 : 16s 373ms
9 : 16s 367ms
10: 16s 446ms
Testing convertTo2DWithoutUsingGetRGB:
1 : 1s 487ms
2 : 1s 940ms
3 : 1s 785ms
4 : 1s 848ms
5 : 1s 624ms
6 : 2s 13ms
7 : 1s 968ms
8 : 1s 864ms
9 : 1s 673ms
10: 2s 86ms
BUILD SUCCESSFUL (total time: 3 minutes 10 seconds)
像這樣的東西?
int[][] pixels = new int[w][h];
for( int i = 0; i < w; i++ )
for( int j = 0; j < h; j++ )
pixels[i][j] = img.getRGB( i, j );
我發現 Mota 的回答讓我的速度提高了 10 倍 - 所以感謝 Mota。
我已經將代碼封裝在一個方便的 class 中,它在構造函數中采用 BufferedImage 並公開了一個等效的 getRBG(x,y) 方法,這使得它可以替代使用 BufferedImage.getRGB(x,y) 的代碼
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
public class FastRGB
{
private int width;
private int height;
private boolean hasAlphaChannel;
private int pixelLength;
private byte[] pixels;
FastRGB(BufferedImage image)
{
pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
width = image.getWidth();
height = image.getHeight();
hasAlphaChannel = image.getAlphaRaster() != null;
pixelLength = 3;
if (hasAlphaChannel)
{
pixelLength = 4;
}
}
int getRGB(int x, int y)
{
int pos = (y * pixelLength * width) + (x * pixelLength);
int argb = -16777216; // 255 alpha
if (hasAlphaChannel)
{
argb = (((int) pixels[pos++] & 0xff) << 24); // alpha
}
argb += ((int) pixels[pos++] & 0xff); // blue
argb += (((int) pixels[pos++] & 0xff) << 8); // green
argb += (((int) pixels[pos++] & 0xff) << 16); // red
return argb;
}
}
除非您的 BufferedImage 來自 Monochrome Bitmap,否則 Mota 的答案非常好。 單色 Bitmap 的像素只有 2 個可能的值(例如 0 = 黑色和 1 = 白色)。 當使用單色 Bitmap 時,則
final byte[] pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
調用以每個字節包含多個像素的方式返回原始像素數組數據。
因此,當您使用單色 Bitmap 圖像創建 BufferedImage object 時,這就是您要使用的算法:
/**
* This returns a true bitmap where each element in the grid is either a 0
* or a 1. A 1 means the pixel is white and a 0 means the pixel is black.
*
* If the incoming image doesn't have any pixels in it then this method
* returns null;
*
* @param image
* @return
*/
public static int[][] convertToArray(BufferedImage image)
{
if (image == null || image.getWidth() == 0 || image.getHeight() == 0)
return null;
// This returns bytes of data starting from the top left of the bitmap
// image and goes down.
// Top to bottom. Left to right.
final byte[] pixels = ((DataBufferByte) image.getRaster()
.getDataBuffer()).getData();
final int width = image.getWidth();
final int height = image.getHeight();
int[][] result = new int[height][width];
boolean done = false;
boolean alreadyWentToNextByte = false;
int byteIndex = 0;
int row = 0;
int col = 0;
int numBits = 0;
byte currentByte = pixels[byteIndex];
while (!done)
{
alreadyWentToNextByte = false;
result[row][col] = (currentByte & 0x80) >> 7;
currentByte = (byte) (((int) currentByte) << 1);
numBits++;
if ((row == height - 1) && (col == width - 1))
{
done = true;
}
else
{
col++;
if (numBits == 8)
{
currentByte = pixels[++byteIndex];
numBits = 0;
alreadyWentToNextByte = true;
}
if (col == width)
{
row++;
col = 0;
if (!alreadyWentToNextByte)
{
currentByte = pixels[++byteIndex];
numBits = 0;
}
}
}
}
return result;
}
如果有用,試試這個:
BufferedImage imgBuffer = ImageIO.read(new File("c:\\image.bmp"));
byte[] pixels = (byte[])imgBuffer.getRaster().getDataElements(0, 0, imgBuffer.getWidth(), imgBuffer.getHeight(), null);
這是在此處找到的另一個 FastRGB 實現:
public class FastRGB {
public int width;
public int height;
private boolean hasAlphaChannel;
private int pixelLength;
private byte[] pixels;
FastRGB(BufferedImage image) {
pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
width = image.getWidth();
height = image.getHeight();
hasAlphaChannel = image.getAlphaRaster() != null;
pixelLength = 3;
if (hasAlphaChannel)
pixelLength = 4;
}
short[] getRGB(int x, int y) {
int pos = (y * pixelLength * width) + (x * pixelLength);
short rgb[] = new short[4];
if (hasAlphaChannel)
rgb[3] = (short) (pixels[pos++] & 0xFF); // Alpha
rgb[2] = (short) (pixels[pos++] & 0xFF); // Blue
rgb[1] = (short) (pixels[pos++] & 0xFF); // Green
rgb[0] = (short) (pixels[pos++] & 0xFF); // Red
return rgb;
}
}
這是什么?
通過 BufferedImage 的 getRGB 方法逐像素讀取圖像非常慢,這個 class 就是解決這個問題的方法。
這個想法是,您通過向 object 提供一個 BufferedImage 實例來構造它,它會一次讀取所有數據並將它們存儲在一個數組中。 一旦你想得到像素,你就調用 getRGB
依賴項
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
注意事項
盡管 FastRGB 可以更快地讀取像素,但它可能會導致 memory 的高使用率,因為它只是存儲圖像的副本。 因此,如果您在 memory 中有一個 4MB 的 BufferedImage,一旦您創建了 FastRGB 實例,memory 的使用量將變為 8MB。 但是,您可以在創建 FastRGB 后回收 BufferedImage 實例。
在內存是瓶頸的 Android 手機等設備上使用時,請注意不要陷入OutOfMemoryException
這對我有用:
BufferedImage bufImgs = ImageIO.read(new File("c:\\adi.bmp"));
double[][] data = new double[][];
bufImgs.getData().getPixels(0,0,bufImgs.getWidth(),bufImgs.getHeight(),data[i]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.