如何在保留颜色的同时将Mat对象转换为位图? [英] How to convert the Mat object to a Bitmap while perserving the color?
问题描述
在我正在开发的App中,我使用 CameraBridgeViewBase.CvCameraViewListener2
使用 OpenCV4Android
打开相机,当我触摸屏幕时,将该框架设置为 ImageView
,如下代码所示.问题是设置为 imageview
的图像的颜色总是与相机上预览的颜色不同,如图所示.我认为此问题与我在以下代码中说明的转换有关
In the App I am developing I open the Camera using OpenCV4Android
using CameraBridgeViewBase.CvCameraViewListener2
and when I touch the screen I set that frame as an image inside an ImageView
as shown below in the code.
the problem is the image set to the imageview
is always of different color than the preview on the camera as shown in the picture. I believe that this issue has something to do with the conversion I made which is stated in the code below
我的问题是如何将Mat对象转换为保留相同颜色的 Bitmap
?
My question is how to convert the Mat object to a Bitmap
preserving the same color?
图片
代码:
@Override
public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
Log.w(TAG, "onCameraFrame");
if (mRGBT != null) {
mRGBT.release();
}
mRGBT = inputFrame.rgba().t();
Core.flip(mRGBT, mRGBT, 1);
Imgproc.resize(mRGBT, mRGBT, inputFrame.rgba().size());
if (touched) {
touched = false;
Imgproc.cvtColor(mRGBT, mRGBT, CvType.CV_8U);
final Bitmap bitmap = Bitmap.createBitmap(mRGBT.cols(), mRGBT.rows(), Bitmap.Config.RGB_565);
Utils.matToBitmap(mRGBT, bitmap);
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
mIV.setImageBitmap(bitmap);
}
});
}
return mRGBT;
}
推荐答案
您不正确地转换了图像.
You are converting the image incorrectly.
如果您希望位图是彩色图像,则不需要 cvtColor
. inputFrame.rgba()
返回RGBA Mat,这是 Utils.matToBitmap
所需的输入(请参见
If you want the bitmap to be a color image, you don't need the cvtColor
.
inputFrame.rgba()
returns a RGBA Mat and that is the input you need for Utils.matToBitmap
(See JavaDoc).
if (touched) {
touched = false;
final Bitmap bitmap =
Bitmap.createBitmap(mRGBT.cols(), mRGBT.rows(), Bitmap.Config.RGB_565);
Utils.matToBitmap(mRGBT, bitmap);
runOnUiThread(new Runnable() {
@Override
public void run() {
mIV.setImageBitmap(bitmap);
}
});
}
如果您希望位图为灰色图像,请使用 Imgproc.COLOR_BGRA2GRAY
:
If you want the bitmap to be a gray image use Imgproc.COLOR_BGRA2GRAY
:
if (touched) {
touched = false;
Imgproc.cvtColor(mRGBT, mRGBT, Imgproc.COLOR_BGRA2GRAY);
final Bitmap bitmap =
Bitmap.createBitmap(mRGBT.cols(), mRGBT.rows(), Bitmap.Config.RGB_565);
Utils.matToBitmap(mRGBT, bitmap);
runOnUiThread(new Runnable() {
@Override
public void run() {
mIV.setImageBitmap(bitmap);
}
});
}
如果需要使用位图 Bitmap.Config.ARGB_8888
,请在 Utils.matToBitmap
中添加 true
作为第三个参数,因此Mat转换为alpha预乘格式(请参见
If you need to work with bitmaps Bitmap.Config.ARGB_8888
add true
as a third parameter in Utils.matToBitmap
, so the Mat is converted to alpha premultiplied format (See JavaDoc).
final Bitmap bitmap =
Bitmap.createBitmap(mRGBT.cols(), mRGBT.rows(), Bitmap.Config.ARGB_8888);
Utils.matToBitmap(mRGBT, bitmap, true);
这篇关于如何在保留颜色的同时将Mat对象转换为位图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!