<pre name="code" class="cpp">//白底不贴,遍历像素时,若为白色,则忽略,否则将像素值复制到背景上 //因为目标图片中可能含有白色点,并且对抠出的图片要求挺高的不然就会出现第二幅图的效果,所以这种方式局限性较大。
Mat hero = imread("2.jpg");
for (int i = 0; i < hero.rows; i++)
{
for (int j = 0; j < hero.cols; j++)
{
int a = hero.at<Vec3b>(i, j)[2];
int b = hero.at<Vec3b>(i, j)[1];
int c = hero.at<Vec3b>(i, j)[0];
if (!(a == 255 && b == 255 && c == 255))
{
background.at<Vec3b>(i + pos_x, j + pos_y)[2] = hero.at<Vec3b>(i, j)[2];
background.at<Vec3b>(i + pos_x, j + pos_y)[1] = hero.at<Vec3b>(i, j)[1];
background.at<Vec3b>(i + pos_x, j + pos_y)[0] = hero.at<Vec3b>(i, j)[0];
}
}
}//透明底不贴,通过将图片保存为含有四通道的png格式,判断alpha值!=0,不贴透明底
Mat background = imread("back.jpg");
Mat hero = imread("2.png",-1);
for (int i = 0; i < hero.rows; i++)
{
for (int j = 0; j < hero.cols; j++)
{
int a = hero.at<Vec3b>(i, j)[2];
int b = hero.at<Vec3b>(i, j)[1];
int c = hero.at<Vec3b>(i, j)[0];
if (hero.at<Vec4b>(i, j)[3] !=0)
{
background.at<Vec3b>(i + pos_x, j + pos_y)[2] = hero.at<Vec4b>(i, j)[2];
background.at<Vec3b>(i + pos_x, j + pos_y)[1] = hero.at<Vec4b>(i, j)[1];
background.at<Vec3b>(i + pos_x, j + pos_y)[0] = hero.at<Vec4b>(i, j)[0];
}
}
}
用抠图软件将图像抠出,第一种是将图片存在一张白底的背景上,第二种是透明背景,效果如下:
原文地址:http://blog.csdn.net/u013298384/article/details/44188007