1

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?

Community
  • 1
  • 1
Neeraj
  • 1,612
  • 7
  • 29
  • 47
  • 1
    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(newWidth, newHeight, CV_8UC4, cv::Scalar(0,0,0,0));` or cvtColor of src before creation of new mat – Micka Sep 02 '15 at 10:33
  • @Micka So what can I do? because my input image is not CV_8UC4. I can't change the line src.type() to CV_8UC4 while initializing Mat since I am trying to rotate the input image. Can I do cvtColor( src,dst, CV_BGR2BGRA ); ??? – Neeraj Sep 02 '15 at 10:40
  • I tried cvtColor( src,src, CV_BGR2BGRA ); but gives error... – Neeraj Sep 02 '15 at 10:46
  • your input image has an alpha channel? look at imread flags, there is a flag to load the image in original type and color instead of alwaya reading as 8UC3. if your input image file hast no alpha channel, use cvtColor with BGR2BGRA flag – Micka Sep 02 '15 at 10:46
  • did you test whether an input was loaded successfully by calling imshow or testing that src.empty() is false? – Micka Sep 02 '15 at 10:48
  • 1
    @Micka The error is from some other part of the code. I am also trying to blend this image to a video. The error will be fro this part. Give your comment as an answer, so that I can approve. :) – Neeraj Sep 02 '15 at 11:12

1 Answers1

4

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.

Micka
  • 19,585
  • 4
  • 56
  • 74
  • with this flag CV_LOAD_IMAGE_ANYDEPTH . we can add Alpha channel on Png? currently i am getting blue background on png if i use flag CV_LOAD_IMAGE_UNCHANGED and then add Alpha channel on png – Muhammad Hassaan Oct 01 '18 at 11:24