2015-04-12 48 views
0

我有這個圖像,我在ms繪製是106x17,我想要把整個位圖變成一個數字。圖像本身存儲爲.png,我需要一種讀取圖像並將每個像素存儲在BigInteger中的方法。我需要讀取圖像的方式相當具體,並且有點奇怪......圖像需要從右到左按照從上到下的順序讀取......所以右上像素應該是第一位在數字中,最左下角的像素應該是數字中的最後一位。java如何從黑白圖像獲取布爾數組

編輯:我應該澄清一點點,因爲該文件存儲爲.png我不能只讀它作爲一個數字,我會嘗試將它導出到位圖圖像後我發佈此更新。另外,我將它存儲在BigInteger中,因爲數字應該是106x17= 1802比特長,所以數字不能先通過int或long,因爲它會丟失大部分信息。最後,在這種情況下,一個黑色像素代表一個1,一個白色像素代表一個0 ...對於奇怪的約定感到抱歉,但這或多或少是我正在處理的。

+1

你的意思是像QR碼掃描儀? –

+0

如果你使用的是BufferedImage,你可以調用'getRGB'函數,然後使用'val = image.getRGB(x,y)> 0?真:假',我猜。 – Gentatsu

+0

[你有什麼嘗試](http://mattgemmell.com/what-have-you-tried/)? – RealSkeptic

回答

0

如果你想要一些非常簡單和黑白的東西,也許你可以以.pbm格式導出圖像,並將其作爲文本文件處理,或者如果將其導出爲.ppm,則可能不需要處理它取決於你想要什麼。
看看these的格式

0

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

image = ImageIO.read(getClass().getResourceAsStream("path/to/your/file.bmp")); 
int color = image.getRGB(x, y); 
BigInteger biColor = BigInteger.valueOf(color); 
0
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); 
+0

這個算法不起作用,我把它運行在我的圖像上,返回的值是'-64'......我建議徹底擺脫'byte []'並在BigInteger本身執行位操作試圖自己調整它,但在所有誠實中,當涉及到按位操作,特別是位圖時,我已經失去了自己的元素......我嘗試自己調整代碼,但沒有運氣,如果我得到它,我會在這裏發佈它。 – Totalllyrandomguy

+0

你可以這樣做。但我想有幾個問題:我的算法生成一個二進制補碼錶示法。這意味着,如果第一個像素不是黑色的,你會收到一個負值 - 你應該指定圖像應該如何解釋(我想你想要一個無符號值)。圖像的黑色像素不是完全黑色(RGB == 0),因此該算法僅產生1位。只需將條件替換爲1位即可。 – Paul

0

沒有爲圖像處理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