2016-08-21 140 views
2

我被困在Android中用OpenCV 3.0加載放置在資產文件夾中的圖像。我在這裏閱讀了很多答案,但我無法弄清楚我做錯了什麼。從Android的資產文件夾中加載OpenCV的圖像

「my image.jpg」直接放置在Android Studio創建的資產文件夾中。 這是我正在使用的代碼。我已檢查並且庫已正確加載。

 Mat imgOr = Imgcodecs.imread("file:///android_asset/myimage.jpg"); 
     int height = imgOr.height(); 
     int width = imgOr.width(); 
     String h = Integer.toString(height); 
     String w = Integer.toString(width); 

     if (imgOr.dataAddr() == 0) { 
      // If dataAddr() is different from zero, the image has been loaded 
      // correctly 
      Log.d(TAG, "WRONG UPLOAD"); 
     } 

     Log.d(h, "height"); 
     Log.d(w, "width"); 

當我嘗試運行我的應用程序,這是我得到:

08-21 18:13:32.084 23501-23501/com.example.android D/MyActivity: WRONG UPLOAD 
08-21 18:13:32.085 23501-23501/com.example.android D/0: height 
08-21 18:13:32.085 23501-23501/com.example.android D/0: width 

好像圖像沒有尺寸。我猜是因爲它沒有被正確加載。我也嘗試加載它放置在可繪製的文件夾中,但它無法正常工作,我寧願使用資源之一。 任何人都可以請幫助我,告訴我如何找到正確的圖像路徑?

感謝

回答

1

問題:imread需要絕對路徑和你的資產是一個APK裏面,和底層的C++類不能從那裏讀取。

選項1:無需使用可繪製文件夾中的imread將圖像加載到Mat中。

   InputStream stream = null; 
       Uri uri = Uri.parse("android.resource://com.example.aaaaa.circulos/drawable/bbb_2"); 
       try { 
        stream = getContentResolver().openInputStream(uri); 
       } catch (FileNotFoundException e) { 
        e.printStackTrace(); 
       } 

       BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options(); 
       bmpFactoryOptions.inPreferredConfig = Bitmap.Config.ARGB_8888; 

       Bitmap bmp = BitmapFactory.decodeStream(stream, null, bmpFactoryOptions); 
       Mat ImageMat = new Mat(); 
       Utils.bitmapToMat(bmp, ImageMat); 

選項2:將圖像複製到緩存並從絕對路徑加載。

File file = new File(context.getCacheDir() + "/" + filename); 
if (!file.exists()) 
try { 

InputStream is = context.getAssets().open(filename); 
int size = is.available(); 
byte[] buffer = new byte[size]; 
is.read(buffer); 
is.close(); 

FileOutputStream fos = new FileOutputStream(file); 

fos.write(buffer); 
fos.close(); 
} catch (Exception e) { 
throw new RuntimeException(e); 
} 

if (file.exists()) { 
image = cvLoadImage(file.getAbsolutePath(), type); 
} 
+0

我按照你的建議使用了可繪製文件夾,現在它可以工作。謝謝! – andraga91

相關問題