Neeraj
Neeraj

Reputation: 1680

Create a transparent image in opencv

I am trying to rotate an image in x, y and z axis as in this. The image should not be cropped while rotating So I am doing this

Mat src = imread("path");
int diagonal = (int)sqrt(src.cols*src.cols+src.rows*src.rows);
int newWidth = diagonal;
int newHeight =diagonal;

Mat targetMat(newWidth, newHeight, src.type());

I am creating a bigger image targetMat. The input image is a png image. But I want this image as a transparent image. So I tried this

Mat targetMat(newWidth, newHeight, src.type(), cv::Scalar(0,0,0,0));

But the output image was outputimage

What I need is transparent image (Transparent image is here)

So what change do I have to do?

Upvotes: 2

Views: 10231

Answers (1)

Micka
Micka

Reputation: 20160

The problem is, that your input image is type CV_8UC3 but you need CV_8UC4 to use the alpha channel. So try Mat targetMat(newHeight, newWidth, CV_8UC4, cv::Scalar(0,0,0,0)); or cvtColor of src before creation of new mat

To use your original image, there are two possibilities:

  1. use cv::cvtColor(src, src, CV_BGR2BGRA) (and adjust later code to use a 4 channel matrix - cv::Vec4b instead of cv::Vec3b etc)

  2. if your input file is a .png with alpha channel you can use the CV_LOAD_IMAGE_ANYDEPTH (hope this is the right one) flag to load it as a CV_xxC4 image (might be 16 bit too) and to use the original alpha values.

Upvotes: 5

Related Questions