Nicola Nicola - 1 year ago 179
Java Question

OpenCV-Android: Import .png preserving transparency of empty areas

I am currently trying to transform an input .png file to a OpenCV:Mat, preserving its transparency on empty areas. Working on eclipse, using openCV4Android.

I've tried this (using a Drawable):


  • icon.png is a resource file that is correctly loaded as RGBA (4 channels).

  • Mat mcSprite (global field).

    onCameraFrame method{
    try {
    mcSprite = Utils.loadResource(this, R.drawable.icon);
    } catch (IOException e) {
    // TODO Auto-generated catch block
    Imgproc.resize(mcSprite, mZoomWindow, mZoomWindow.size());

The resulting image:

Black Zones

PS: If i import using:

mcSprite = Utils.loadResource(this, R.drawable.icon , -1);

>0 Return a 3-channel color image.
=0 Return a grayscale image.
<0 Return the loaded image as is (with alpha channel).

no image is displayed.

Answer Source

A lot faster solution, using masks:

    public Mat overlayImage(Mat background, Mat foreground)//, Point location)
          Mat mask = new Mat();
          Imgproc.resize(mCurrentMask, mask, background.size());

          Mat source = new Mat();             
          Imgproc.resize(foreground, source, background.size()); 

          return background;

    public void createMask (Mat sprite){
        mCurrentMask = new Mat(sprite.height(),sprite.width(),24);
        double f[] = {1,1,1,0};
        double e[] = {0,0,0,0};
        for(int y = 0; y < (int)(sprite.rows()) ; ++y)
              for(int x = 0; x < (int)(sprite.cols()) ; ++x)
                  double info[] = sprite.get(y, x);                 
                  if(info[3]>0) //rude but this is what I need
                      mCurrentMask.put(y, x, f);
                  else mCurrentMask.put(y, x, e);