transparently overlay two images with Java

asked 2017-11-09 10:46:17 -0600

Noah gravatar image


I am working with opencv for a few days. I would like to write a program which overlays two images and at the end i´ll have a picture on which all contents of the two images are included. I've searched everywhere but found only tutorials written with c ++ and not in would be cool if someone could help me. Thank you very much

P.S. sorry for my bad english!

edit retag flag offensive close merge delete


opencv is a computer-vision library, and usually ignores all things alpha (they're irrelevant)

you do not need opencv, for what you're trying, and you better should look for something else, like imageJ

berak gravatar imageberak ( 2017-11-09 10:55:31 -0600 )edit

It does however go to show that OpenCV handles 4-channel PNG images, with transparency intact. The blending between the two images is up to you.

I notice that although there's transparency data, the imshow function doesn't take the transparency data into account; it draws everything with 0 transparency by default. I used Pixelmator to create the file bg.png by setting the first layer's transparency to 50%.

Mat frame = imread("bg.png", CV_LOAD_IMAGE_UNCHANGED);

for (int j = 0; j < frame.rows; j++)
    for (int i = 0; i < frame.cols; i++)
        Vec4b v =<Vec4b>(j, i);

        cout << (int)v[0] << endl; // 255
        cout << (int)v[1] << endl; // 255
        cout << (int)v[2] << endl; // 255
        cout << (int)v[3] << endl; // 127
        cout << endl;

imshow("f", frame);

sjhalayka gravatar imagesjhalayka ( 2017-11-09 12:04:25 -0600 )edit

GIMP also exports 4-channel PNG files.

sjhalayka gravatar imagesjhalayka ( 2017-11-09 12:42:25 -0600 )edit

Your blending will probably look something like this:

unsigned char red = unsigned char((float(red1) + float(red2)*(alpha2/255.0f))/2.0f);
sjhalayka gravatar imagesjhalayka ( 2017-11-09 13:18:22 -0600 )edit

@sjhalayka -- why would any of this require using opencv ?

berak gravatar imageberak ( 2017-11-09 13:23:23 -0600 )edit

@berak If I were doing something like this, I'd use OpenCV simply for the ease of loading image files. I found this might work too:

sjhalayka gravatar imagesjhalayka ( 2017-11-09 13:31:04 -0600 )edit