2011-09-23 58 views
1

我使用opencv通過使用opencv將android位圖轉換爲grescale。以下是我正在使用的代碼,灰度Iplimage到android位圖

  IplImage image = IplImage.create(bm.getWidth(), bm.getHeight(), IPL_DEPTH_8U, 4); //creates default image 
     bm.copyPixelsToBuffer(image.getByteBuffer()); 
     int w=image.width(); 
     int h=image.height(); 
      IplImage grey=cvCreateImage(cvSize(w,h),image.depth(),1); 
      cvCvtColor(image,grey,CV_RGB2GRAY); 

bm是源圖像。此代碼工作正常,並轉換爲灰度,我測試了它通過保存到SD卡,然後再次加載,但當我嘗試使用下面的方法加載它我的應用程序崩潰,任何建議。

   bm.copyPixelsFromBuffer(grey.getByteBuffer()); 
       iv1.setImageBitmap(bm); 

iv1是imageview,我想設置bm。

回答

0

我從來沒有使用Android的OpenCV綁定,但這裏有一些代碼讓你開始。把它當作僞代碼,因爲我無法嘗試......但你會得到基本的想法。它可能不是最快的解決方案。我正在粘貼this answer

public static Bitmap IplImageToBitmap(IplImage src) { 
    int width = src.width; 
    int height = src.height; 
    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); 
    for(int r=0;r<height;r++) { 
     for(int c=0;c<width;c++) { 
      int gray = (int) Math.floor(cvGet2D(src,r,c).getVal(0)); 
      bitmap.setPixel(c, r, Color.argb(255, gray, gray, gray)); 
     } 
    } 
    return bitmap; 
} 
+0

這是正確的,但它太慢了...... 800x600 img需要5秒。更快的解決方案? –

+0

對於性能嚴重的代碼,本機無法實現。這個可能有點老,但是會告訴你如何去做:http://www.ibm.com/developerworks/cn/education/opensource/os-androidndk/。 – bytefish

-1

IplImage grey只有一個通道,你的Bitmap bm有4個或3(ARGB_8888ARGB_4444RGB_565)。因此bm不能存儲灰度圖像。使用前必須將其轉換爲rgba。

例子: (代碼)

IplImage image = IplImage.create(bm.getWidth(), bm.getHeight(), IPL_DEPTH_8U, 4); 
bm.copyPixelsToBuffer(image.getByteBuffer()); 
int w=image.width(); int h=image.height(); 
IplImage grey=cvCreateImage(cvSize(w,h),image.depth(),1); 
cvCvtColor(image,grey,CV_RGB2GRAY); 

如果要加載: (你可以重用image或創建另一個(temp))

IplImage temp = cvCreateImage(cvSize(w,h), IPL_DEPTH_8U, 4); // 4 channel 
cvCvtColor(grey, temp , CV_GRAY2RGBA); //color conversion 
bm.copyPixelsFromBuffer(temp.getByteBuffer()); //now should work 
iv1.setImageBitmap(bm); 

我可能是會有幫助!