灰度Iplimage到android位图

时间:2011-09-23 10:57:00

标签: android opencv iplimage grayscale

我使用opencv通过opencv将android位图转换为grescale。下面是我正在使用的代码,

          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。

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:-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);

我可能会有所帮助!