2016-11-30 71 views
0

我正在開發一個項目,在該項目中我必須從攝像頭獲取圖像(cmucam4),該項目已通過Xbee連接到我的計算機。 問題是我可以通過串口獲取圖像數據,但是當我將它保存爲文件時,該文件不能作爲圖像打開。 我注意到,當我用記事本++打開文件時,文件沒有像其他圖像(相機發送bmp圖像)的標題。如何從通過串口接收的數據創建BufferedImage

我試圖使用ImageIO保存圖像,但我不知道如何將數據接收到圖像!

BufferedImage img = new BufferedImage(640, 480,BufferedImage.TYPE_INT_RGB);    
ImageIO.write(img, "BMP", new File("img/tmp.bmp")); 

回答

1

如果相機真的發送BMP格式,您可以將數據寫入磁盤。然而,更可能的(看起來是這樣,從你的鏈接讀取規格),卡片發送一個原始位圖,這是不一樣的。

使用從卡規範PDF此信息:

RAW圖像轉儲通過串行或閃存卡

  • (640:320:160:80)×(480:240:120 :60)的圖像分辨率
  • RGB565/YUV655顏色空間

的RGB565像素佈局mentione d以上應該與BufferedImage.TYPE_USHORT_565_RGB完美匹配,所以應該是最容易使用的。

byte[] bytes = ... // read from serial port 

ShortBuffer buffer = ByteBuffer.wrap(bytes) 
     .order(ByteOrder.BIG_ENDIAN) // Or LITTLE_ENDIAN depending on the spec of the card 
     .asShortBuffer();   // Our data will be 16 bit unsigned shorts 

// Create an image matching the pixel layout from the card 
BufferedImage img = new BufferedImage(640, 480, BufferedImage.TYPE_USHORT_565_RGB); 

// Get the pixel data from the image, and copy the data from the card into it 
// (the cast here is safe, as we know this will be the case for TYPE_USHORT_565_RGB) 
short[] data = ((DataBufferUShort) img.getRaster().getDataBuffer()).getData(); 
buffer.get(data); 

// Finally, write it out as a proper BMP file 
ImageIO.write(img, "BMP", new File("temp.bmp")); 

PS:上面的代碼對我的作品,使用byte陣列長度640 * 480 * 2的,用隨機數據初始化(如我顯然不具備這樣的卡)。

+1

謝謝,它的工作原理。 – NYoussef