2014-03-06 134 views
0

我創建一個代碼barre閱讀器,我已經採取了一個RGB圖片,並使用onPictureTaken(byte [] _data,相機_camera)存儲在一個數組中,現在我需要它轉換爲二進制矩陣(灰度) 這個我做了什麼至今轉換圖像灰度與陣列矩陣RGB android

public class cam extends Activity implements Callback { 
Camera camera = null; 
@SuppressWarnings("deprecation") 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    requestWindowFeature(Window.FEATURE_NO_TITLE); 
    SurfaceView view = new SurfaceView(this); 
    view.getHolder().addCallback(this); 
    view.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); 
    setContentView(view); 
} 




@Override 
public void surfaceChanged(SurfaceHolder holder, int format, int width, 
     int height) { 
    Camera.Parameters parameters = camera.getParameters(); 
    parameters.setPreviewSize(width, height); 
    parameters.getSupportedPictureFormats(); 
    List<Integer> formats = parameters.getSupportedPictureFormats(); 
     if (formats.contains(PixelFormat.RGB_888)) 
      parameters.setPictureFormat(PixelFormat.RGB_888); 
    camera.setParameters(parameters); 
    camera.startPreview(); 

} 

@Override 
public void surfaceCreated(SurfaceHolder holder) { 
    try { 
     camera = Camera.open(); 
     camera.setPreviewDisplay(holder); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    }  
} 

@Override 
public void surfaceDestroyed(SurfaceHolder holder) { 
    camera.stopPreview(); 
    camera.release(); 
    camera = null; 
} 

@SuppressLint("ShowToast") 
@Override 
public boolean onTouchEvent(MotionEvent event) { 
    switch(event.getAction()){ 
    case MotionEvent.ACTION_DOWN: 

     PictureCallback jpegCallback = new PictureCallback() { 
      public void onPictureTaken(byte[] _data, Camera _camera) {     
       try { 
        File fs = new File(cam.this.getFilesDir()+"/image.jpeg");            
        FileOutputStream fos = new FileOutputStream(fs); 
        fos.write(_data); 
        fos.flush(); 
        fos.close(); 
        Toast.makeText(cam.this,fs.getAbsolutePath(),0).show(); 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 
       camera.startPreview(); 

      } 
     }; 
     camera.takePicture(null, null, jpegCallback);   
     break; 
    } 
    return super.onTouchEvent(event); 
} 

}

回答

0

做一個Bitmap出來的,然後做

private byte[] convertToGray(Bitmap bmp) { 
    int width = bmp.getWidth(); 
    int height = bmp.getHeight(); 
    byte[] grayscale = new byte[width*height]; 
    int val, R, G, B; 
    for (int i = 0; i < height; i++) { 
     for (int j = 0; j < width; j++) { 
      val = bmp.getPixel(j, i); 
      R = (val >> 16) & 0xff ;  
      G = (val >> 8) & 0xff ; 
      B = val & 0xff ; 
      grayscale[i*width + j] = (byte)(0.21*R + 0.71*G + 0.07*B); 
     } 
    } 

    return grayscale; 

乾杯!