OpenCV: Merging two images using OpenCV

2019-08-30 05:43发布

问题:

What is the best way to make the size of box 2 equal to Box 1 so that CvCopy(); can be applied:

EDIT:

Perhaps I did not put the question properly. So I am re-phrasing it. Given an Image 2 (as shown above), I want to convert it as shown below:

Basically I have to add a black border across it. resize will not work as my image will get distorted. Putting in other words, I have to add zeros in a define thikness around the image.

Also although shown empty, these images(boxes) may have some objects inside them, which I have not shown.

回答1:

You can use copyMakeBorder function to do so. I don't know dotnet, below is a sample code in python. Also visit docs for above function : DOCS

First load the two images. imb is the big image, and ims is the small image.

import cv2
import numpy as np

imb = cv2.imread('messi4.jpg')
ims = cv2.imread('template.jpg')

Now let rb,cb be the number of rows and columns of big image, and similarly rs,cs for small image.

rb,cb = imb.shape[:2]
rs,cs = ims.shape[:2]

Finally, to use the copyMakeBorder function, you need the number of rows and columns to be added at top,bottom,left and right. So we need to find them.

top = (rb-rs)/2
bottom = rb - rs - top
left = (cb-cs)/2
right = cb - cs - left

Finally apply the function.

res = cv2.copyMakeBorder(ims,top,bottom,left,right,cv2.BORDER_CONSTANT)

Now see the results :

Original Small Image :

Modified New Image :

It has the same size of that of my big image ( hasn't shown here, thought it won't be necessary, if you want, i can upload)



回答2:

Expanding the smaller one would not be the best idea as you'll get a lot of image distortion - rather it would be better to shrink the larger one if the final size is not an issue.

You can resize images using cv::resize( ) (this is the C++ function - I haven't used OpenCV dot net).

Implementation details are in the API.

In terms of merging, it depends on your definition, but simply using cv::copy( ) won't do it. There's a full tutorial on image merging in the documentation, here.