cristi stefan
cristi stefan

Reputation: 27

Making the background of a picture transparent using opencv

I have looked through most of the other related questions, and most of them dont apply to my code.

I am creating a 2D racing game, and i have to add 2 car images to my background image, in order to do this i had to load the images as Mat (I was able to make it work like that).

The problem is not that my cars (.png) have a fuchsia background and i want to make it transparent. Most of the solutions involve loading the images as IplImagewhich i tried and somehow ruined other parts of my code.

 #include <opencv\cv.h>
 #include <stdio.h>
 #include <opencv\highgui.h>
 #include <iostream>


 using namespace std;
 using namespace cv;

int main()
{
Mat car1, car2, BKGR;

int key = 0;

/* load images and checks if correct images loaded */
 BKGR = imread("map.jpg", CV_LOAD_IMAGE_COLOR); //937x768
car1 = imread("car1.png", CV_LOAD_IMAGE_COLOR); //70x75
car2 = imread("car2.png", CV_LOAD_IMAGE_COLOR); //70x75

if((!BKGR.data)||(!car1.data)||(!car2.data))
    cout << "Could not open one or more images." << endl;
else 
    cout << "Images were loaded succesfully." << endl;
    waitKey(0);

    car1.copyTo(BKGR.colRange(450,520).rowRange(630,705));
    car2.copyTo(BKGR.colRange(350,420).rowRange(430,505));
    waitKey(0);

    cv::floodFill(car1, cv::Point(150,150), cv::Scalar(255.0, 255.0, 255.0));
    cv::floodFill(car2, cv::Point(150,150), cv::Scalar(255.0, 255.0, 255.0));

/* create a window, display the result, wait for a key */
cvNamedWindow("Game", CV_WINDOW_AUTOSIZE);
imshow("Game", BKGR);


cvWaitKey(0);
return 0;
 }

So if you guys know a way of making the background of the image transparent without using IplImage I would really be grateful. Thanks

Upvotes: 1

Views: 4542

Answers (1)

Haris
Haris

Reputation: 14043

You can find similar kind of example here

And if you need load transparent image(with alpha) use

imread("map.jpg",-1)

instead of

imread("map.jpg", CV_LOAD_IMAGE_COLOR)

which will load alpha, See OpenCV Doc for more info.

Upvotes: 2

Related Questions