android-opencv使用matToBitmap / bitmapToMat将mat转换为灰度

时间:2011-12-10 05:07:05

标签: android opencv bitmap grayscale

我在eclipse中使用了更新的willowgarage opencv库。我想将mat变量转换为灰度,我已经尝试了我在网上找到的所有东西,但它们对我没用。

这是我的代码

package com.deneme.deneme;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;
import org.opencv.android.Utils;
import org.opencv.core.Mat;
import org.opencv.imgproc.Imgproc;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
public class main extends Activity {
/** Called when the activity is first created. */

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ImageView img=(ImageView) findViewById(R.id.pic);

    Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.p26);

    Mat imgToProcess=Utils.bitmapToMat(bmp);

    //******
    //right here I need to convert this imgToProcess to grayscale for future opencv processes
    //******

    Bitmap bmpOut = Bitmap.createBitmap(imgToProcess.cols(), imgToProcess.rows(), Bitmap.Config.ARGB_8888); 

    Utils.matToBitmap(imgToProcess, bmpOut);
    img.setImageBitmap(bmpOut);
}

}

1 个答案:

答案 0 :(得分:15)

在代码块中添加以下代码:

Imgproc.cvtColor(imgToProcess, imgToProcess, Imgproc.COLOR_BGR2GRAY);
Imgproc.cvtColor(imgToProcess, imgToProcess, Imgproc.COLOR_GRAY2RGBA, 4);

或者您可以自己访问像素:

for(int i=0;i<imgToProcess.height();i++){
    for(int j=0;j<imgToProcess.width();j++){
        double y = 0.3 * imgToProcess.get(i, j)[0] + 0.59 * imgToProcess.get(i, j)[1] + 0.11 * imgToProcess.get(i, j)[2];
        imgToProcess.put(i, j, new double[]{y, y, y, 255});
    }
}