簡體   English   中英

java如何從黑白圖像獲取布爾數組

[英]java how to get a boolean array from a black and white image

我有這張用ms paint繪制的圖像是106x17 ,我想將整個位圖轉換成數字。 圖像本身以.png存儲,我需要一種讀取圖像並將每個像素作為一點存儲在BigInteger 我需要讀取圖像的方式是相當具體的,有點怪異...需要從上到下從右到左從行開始讀取圖像...因此右上角像素應該是第一位在數字中,最左下方的像素應該是數字中的最后一位。

編輯:我可能應該澄清一下,由於文件存儲為.png文件,因此我無法將其讀取為數字,因此我將在發布此更新后立即嘗試將其導出為位圖圖像。 我也將其存儲在BigInteger因為該數字的106x17= 1802應為106x17= 1802位,因此該數字不能通過int或long優先傳遞,因為它將丟失大部分信息。 最后,在這種情況下,黑色像素代表1,白色像素代表0 ...抱歉,這很奇怪,但這或多或少是我正在使用的。

如果您想要非常簡單的黑白圖像,也許可以將.pbm格式的圖像導出並作為文本文件使用,或者如果將其導出為.ppm,則可能甚至不必根據自己的需要進行處理。想。
看看這些格式

位圖已經是一個數字。 只需打開它並閱讀。

image = ImageIO.read(getClass().getResourceAsStream("path/to/your/file.bmp"));
int color = image.getRGB(x, y);
BigInteger biColor = BigInteger.valueOf(color); 
BufferedImage bi = yourImage;

//the number of bytes required to store all bits
double size = ((double) bi.getWidth()) * ((double) bi.getHeight()) / 8;
int tmp = (int) size;
if(tmp < size)
    tmp += 1;

byte[] b = new byte[tmp];
int bitPos = 7;
int ind = 0;

for(int i = 0 ; i < bi.getHeight() ; i++)
     for(int j = 0 ; j < bi.getWidth() ; j++){
         //add a 1 at the matching position in b, if this pixel isn't black
         b[ind] |= (bi.getRgb(j , i) > 0 ? 0 : (1 << bitPos));

         //next pixel -> next bit
         bitPos -= 1;
         if(bitPos == -1){//the current byte is filled with continue with the next byte
             bitPos = 7;
             ind++;
         }
     }

BigInteger result = new BigInteger(b);

有專門用於圖像處理ImageJ Java API,您可以在此處下載必要的Jar鏈接, http://imagej.nih.gov/ij/download.html和文檔鏈接http://imagej.nih.gov/ij /docs/index.html

有一些教程和示例可用於使用此API對圖像進行基本操作,我將嘗試為您的任務編寫基本代碼

    // list of points
    List<Point> pointList = new ArrayList<>();

    ImagePlus imp = IJ.openImage("/path/to/image.tif"); 
    ImageProcessor imageProcessor = imp.getProcessor(); 

    // width and height of image
    int width = imageProcessor.getWidth();
    int height = imageProcessor.getHeight();

    // iterate through width and then through height
    for (int u = 0; u < width; u++) {
        for (int v = 0; v < height; v++) {
            int valuePixel = imageProcessor.getPixel(u, v);
            if (valuePixel > 0) {
                pointList.add(new Point(u, v));
            }
        }
    }

    // convert list to array
    pointList.toArray(new Point[pointList.size()]);

這是更多示例的另一個鏈接, http://albert.rierol.net/imagej_programming_tutorials.html#ImageJ

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM