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

Tha*_*lia 6 c++ opencv image-processing

我试图混合两个图像.如果它们具有相同的大小,则很容易,但如果其中一个图像更小或更大,则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());
Run Code Online (Sandbox Code Playgroud)

甚至像cvSetImageROI这样的东西 - 可能有用,但我找不到c ++等价物 - 可能会有所帮助 - 但我不知道如何使用它仍然保留图像内容,只在ROI中放置另一个图像...

Jac*_*cob 13

// 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);
Run Code Online (Sandbox Code Playgroud)

请注意,如果您想B直接混合A,您只需要roi.

cv::addWeighted(A(roi),alpha,B,1-alpha,0.0,A(roi));
Run Code Online (Sandbox Code Playgroud)