Reputation: 701
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):
Inputs:
Mat mcSprite (global field).
onCameraFrame method{
try {
mcSprite = Utils.loadResource(this, R.drawable.icon);
System.out.println(mcSprite.empty());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Imgproc.resize(mcSprite, mZoomWindow, mZoomWindow.size());
}
The resulting image:
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.
Upvotes: 2
Views: 3069
Reputation: 701
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());
source.copyTo(background,mask);
source.release();
mask.release();
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);
}
}
}
Upvotes: 2
Reputation: 701
Solved:
public void overlayImage(Mat background, Mat foreground,Mat output)//, Point location)
{
background.copyTo(output);
Mat dst = new Mat();
Imgproc.resize(foreground, dst, background.size());
double alpha;
// start at row 0/col 0
for(int y = 0; y < background.rows() ; ++y)
{
for(int x = 0; x < background.cols() ; ++x)
{
double info[] = dst.get(y, x);
alpha = info[3];
// and now combine the background and foreground pixel, using the opacity,but only if opacity > 0.
if(alpha>0) //rude but this is what I need
{
double infof[] = dst.get(y, x);
output.put(y, x, infof);
}
}
}
Final Result:
Upvotes: 1