Il est possible de convertir l'image d'entrée à canal BGRA (image de couleur avec canal alpha), puis modifier chaque pixel qui est blanc pour régler la valeur alpha à zéro.
Voir ce code:
// load as color image BGR
cv::Mat input = cv::imread("C:/StackOverflow/Input/transparentWhite.png");
cv::Mat input_bgra;
cv::cvtColor(input, input_bgra, CV_BGR2BGRA);
// find all white pixel and set alpha value to zero:
for (int y = 0; y < input_bgra.rows; ++y)
for (int x = 0; x < input_bgra.cols; ++x)
{
cv::Vec4b & pixel = input_bgra.at<cv::Vec4b>(y, x);
// if pixel is white
if (pixel[0] == 255 && pixel[1] == 255 && pixel[2] == 255)
{
// set alpha to zero:
pixel[3] = 0;
}
}
// save as .png file (which supports alpha channels/transparency)
cv::imwrite("C:/StackOverflow/Output/transparentWhite.png", input_bgra);
Cela permettra d'économiser votre image avec la transparence. L'image résultat ouvert avec GIMP ressemble:
Comme vous pouvez le voir, certaines « régions blanches » ne sont pas transparents, cela signifie que votre pixel ceux n'étaient pas parfaitement blanc dans l'image d'entrée. Au lieu de cela, vous pouvez essayer
// if pixel is white
int thres = 245; // where thres is some value smaller but near to 255.
if (pixel[0] >= thres&& pixel[1] >= thres && pixel[2] >= thres)
cv :: cvtColor (entrée, sortie; CV_BGR2BGRA); puis, pour chaque pixel: si pixel == blanc, définissez la valeur alpha de ce pixel sur zéro. – Micka
ah non, votre image d'entrée est-elle déjà transparente? utilisez l'indicateur CV_LOAD_IMAGE_ANYDEPTH. – Micka
ou utilisez une valeur négative comme indiqué dans http://docs.opencv.org/2.4/modules/highgui/doc/reading_and_writing_images_and_video.html#imread – Micka