Draw on transparent background

I want to draw a white circle on transparent background using OpenCV, I use code for this:

cv::Mat m(500, 500, CV_8UC4, cv::Scalar(0, 0, 0, 0));
cv::circle(m, cv::Point(250, 250), 100, cv::Scalar(255, 255, 255, 255), 10, cv::LINE_AA);
cv::imwrite("img.png", m);

But as result I have circle with grey outline on transparent background.

Outline color depends on “color” of transparent background - if I draw circve over

cv::Mat m(500, 500, CV_8UC4, cv::Scalar(0, 0, 255, 0));

the outline is red.

How to avoid this and draw circle without outline?

OpenCV is not made to handle alpha channels. it treats that like any other channel, which isn’t how alpha channels need to be treated. especially drawing functions need to handle alpha channels specially.

fill the whole picture with white (first 3 channels), then set alpha of your circle as required.

what happened here is that those pixels on the border get blended for antialiasing, but not just the alpha value got smoothed, but also the color values. that’s wrong. the color values have to “stay” fully the nominal color, while only the alpha value may change.

1 Like

I found if perform the color conversion before saveing

cv::cvtColor(m, m, cv::COLOR_mRGBA2RGBA);
cv::imwrite("img.png", m);

it looks better, so may be opencv use premultiplied alpha when drawing?

in a sense it is premultiplied but only “accidentally” because the drawing function is really unaware of alpha. it scales all channels equally during antialiasing.