开发者

greyscale Iplimage to android bitmap

I am using opencv to convert android bitmap to grescale by using opencv. below is the code i am using,

          IplImage image = IplImage.create( bm.getWidth(), bm.getHeight(), IPL_DEPTH_8U, 4); //creates default image
        bm.copyPixelsToBuffer(image.getByt开发者_如何学PythoneBuffer());
        int w=image.width();
        int  h=image.height();
          IplImage grey=cvCreateImage(cvSize(w,h),image.depth(),1);
          cvCvtColor(image,grey,CV_RGB2GRAY);

bm is source image. This code works fine and converts to greyscale, i have tested it by saving to sdcard and then loading again, but when i try to load it using below method my app crashes, any suggestions.

                bm.copyPixelsFromBuffer(grey.getByteBuffer());
               iv1.setImageBitmap(bm);

iv1 is imageview where i want to set the bm.


I've never used the OpenCV bindings for Android, but here's some code to get you started. Regard it as pseudocode, because I can't try it out... but you'll get the basic idea. It may not be the fastest solution. I'm pasting from 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;
}


Your IplImage grey has only one channel, and your Bitmap bm has 4 or 3 (ARGB_8888, ARGB_4444, RGB_565). Therefore the bm can't store the greyscale image. You have to convert it to rgba before use.

Example: (your code)

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);

If you want to load it: (You can reuse your image or create another one (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);

I might it will help!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜