使用opencv复制/混合不同大小的图像

Copy / blend images of different sizes using opencv

本文关键字:图像 opencv 复制 混合 使用      更新时间:2023-10-16

我正在尝试混合两个图像。如果它们的大小相同,这很容易,但如果其中一个图像较小或较大,则cv::addWeighted失败。

图像A(预计会更大)图像B(预计较小)

我试着创建一个ROI——试着创建第三个a大小的图像,并在里面复制B——我似乎做不好。请帮忙。

double alpha = 0.7; // something
int min_x = ( A.cols - B.cols)/2 );
int min_y = ( A.rows - B.rows)/2 );
int width, height;
if(min_x < 0) {
  min_x = 0; width = (*input_images).at(0).cols - 1;
}
else         width = (*input_images).at(1).cols - 1;
if(min_y < 0) {
  min_y = 0; height = (*input_images).at(0).rows - 1;
}
else         height = (*input_images).at(1).rows - 1;
cv::Rect roi = cv::Rect(min_x, min_y, width, height);            
cv::Mat larger_image(A);
// not sure how to copy B into roi, or even if it is necessary... and keep the images the same size
cv::addWeighted( larger_image, alpha, A, 1-alpha, 0.0, out_image, A.depth());

即使是像cvSetImageROI这样的东西-可能会起作用,但我找不到c++等价物-可能会有所帮助-但我不知道如何使用它来保持图像内容,只在ROI内放置另一个图像。。。

// min_x, min_y should be valid in A and [width height] = size(B)
cv::Rect roi = cv::Rect(min_x, min_y, B.cols, B.rows);  
// "out_image" is the output ; i.e. A with a part of it blended with B
cv::Mat out_image = A.clone();
// Set the ROIs for the selected sections of A and out_image (the same at the moment)
cv::Mat A_roi= A(roi);
cv::Mat out_image_roi = out_image(roi);
// Blend the ROI of A with B into the ROI of out_image
cv::addWeighted(A_roi,alpha,B,1-alpha,0.0,out_image_roi);

请注意,如果要将B直接混合到A中,则只需要roi

cv::addWeighted(A(roi),alpha,B,1-alpha,0.0,A(roi));

使用addWeighted()函数可以轻松地混合两个图像

addWeighted(src1, alpha, src2, beta, 0.0, dst);

声明两个图像

src1 = imread("c://test//blend1.jpg");
src2 = imread("c://test//blend2.jpg");

声明alphabeta的值,然后调用该函数。你完了。您可以在链接中找到详细信息:使用Opencv 混合图像