Android上的OpenCV转换为灰度无法正常工作

时间:2013-04-09 20:58:15

标签: java android opencv

我正在尝试将一些OpenCV Mat转换为灰度以进行Contours检测算法。由于某种原因,转换后的图像全黑。我的代码(b是Android Bitmap):

Mat tmp = new Mat (b.getWidth(), b.getHeight(), CvType.CV_8UC1);
Utils.bitmapToMat(b, tmp);
Imgproc.cvtColor(tmp, tmp, Imgproc.COLOR_BGR2GRAY);
//there could be some processing
Imgproc.cvtColor(tmp, tmp, Imgproc.COLOR_GRAY2BGRA, 4);
Utils.matToBitmap(tmp, b);

现在我正在绘制这个位图,它全是黑色的。当我将轮廓检测应用于此位图(代替注释)时没有匹配,所以我认为问题在于转换。删除转换后(只需调用bitmapToMat和matToBitmap),然后位图不是全黑的,所以转换为Mat也有效。位图在ARGB_8888中并且没有错误,只是输出位图全黑。

编辑:为了确保我尝试使用ocv imwrite保存位图 - 它仍然全黑,所以cvtColor的问题是100%......

2 个答案:

答案 0 :(得分:7)

如果位图b来自Android设备,请尝试使用COLOR_RGB2GRAY而不是COLOR_BGR2GRAY,因为BGR是OpenCV图像的默认像素格式,而不是所有图像。

试试这段代码:

Mat tmp = new Mat (b.getWidth(), b.getHeight(), CvType.CV_8UC1);
Utils.bitmapToMat(b, tmp);
Imgproc.cvtColor(tmp, tmp, Imgproc.COLOR_RGB2GRAY);
//there could be some processing
Imgproc.cvtColor(tmp, tmp, Imgproc.COLOR_GRAY2RGB, 4);
Utils.matToBitmap(tmp, b);

答案 1 :(得分:0)

我尝试过这种方法并且效果很好,首先必须将其转换为灰度,然后转换为Canny,最后转换为Bitmap。

此函数返回黑白图像。

public static Bitmap edgesim(Mat img1) {

Bitmap image1;

//mat gray img1 holder
Mat imageGray1 = new Mat();

//mat canny image
Mat imageCny1 = new Mat();

//mat canny image
Mat imageCny2 = new Mat();

/////////////////////////////////////////////////////////////////

//Convert img1 into gray image
Imgproc.cvtColor(img1, imageGray1, Imgproc.COLOR_BGR2GRAY);

//Canny Edge Detection
Imgproc.Canny(imageGray1, imageCny1, 10, 100, 3, true);

///////////////////////////////////////////////////////////////////

//////////////////Transform Canny to Bitmap/////////////////////////////////////////
image1= Bitmap.createBitmap(imageCny1.cols(), imageCny1.rows(), Bitmap.Config.ARGB_8888);
Utils.matToBitmap(imageCny1, image1);

return image1;

}