gpt4 book ai didi

opencv - 使用图像的轮廓创建单独的图像?

转载 作者:太空宇宙 更新时间:2023-11-03 21:46:40 25 4
gpt4 key购买 nike

我想使用图像的轮廓创建一个单独的图像。

我已经看到了答案herehere , 但是通过使用它们背景会变成黑色。

但我想要一个透明的背景,因为我必须进一步处理那些黑色会产生问题的图像。

问题:如何为提取的图像获取透明背景。

目前我正在使用下面的代码,通过它我可以创建一个单独的图像,但背景是黑色的:

Mat findRect::extractImage( int min_x, int min_y , int rows, int cols , Mat frame, vector<Point> ROI_Poly)
{
Mat mask = Mat::zeros(frame.rows, frame.cols, CV_8UC1);

// Fill polygon white
fillConvexPoly(mask, &ROI_Poly[0], ROI_Poly.size(), 255, 8, 0);

// Create new image for result storage
Mat imageDest = cvCreateMat(frame.rows, frame.cols, CV_8UC3);

// Cut out ROI and store it in imageDest
frame.copyTo(imageDest, mask);

// Extracting the ROI only
roi = Rect (min_x, min_y, cols, rows);
Mat detectedSquare;


if( 0 <= roi.x && 0 <= roi.width && roi.x + roi.width <= frame.cols && 0 <= roi.y && 0 <= roi.height && roi.y + roi.height <= frame.rows )
detectedSquare= imageDest(roi);

//imshow("extracted image" , detectedSquare);
return detectedSquare;
}

最佳答案

因此您已经有了轮廓和 3 channel 源图像。

  1. 现在只需通过绘制轮廓并将其反转来创建单 channel 图像,这将代表您的 alpha channel 。

  2. 假设您已经将源图像复制到黑色背景的新 Mat 中,只需将此图像拆分为大小为 3 的 Mat 数组即可。

  3. 现在您获得了三个主 channel R、G、B 和 Alpha。

  4. 现在只需将所有这些合并到一个新的 Mat 中即可。

完成! .

请看下面的代码,这里我使用阈值创建了 alpha,而你必须使用等高线绘制。

Mat src=imread("src.png",1);
Mat dst;
Mat tmp,alpha;

cvtColor(src,tmp,CV_BGR2GRAY);
threshold(tmp,alpha,10,255,THRESH_BINARY);

Mat rgb[3];
split(src,rgb);

Mat rgba[4]={rgb[0],rgb[1],rgb[2],alpha};
merge(rgba,4,dst);

BGR 来源

BGR source

背景的 Alpha(0 = 完全透明,255 = 无透明度)

enter image description here

具有背景 alpha 的结果

Result with background alpha

关于opencv - 使用图像的轮廓创建单独的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22301430/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com