I want to add image 'abc.jpg' on xyz.jpg using openCV and python. I have got the coordinates x,y on which I have to add the image and also resized my 'abc.jpg' so that it will fit on the image. Now how can I add it?
-
https://docs.opencv.org/3.2.0/d0/d86/tutorial_py_image_arithmetics.html – user8190410 Apr 22 '19 at 14:28
1 Answers
To computers, images are just a grid of numbers. There are a few ways to 'add' a grid of numbers. In this answer, I will explain three ways to add image 'abc' on image 'xyz'. This is a very simple task a + b = c. But, that only works if the images are the same shape. To work with images of different shapes, only certain parts of the images should be modified using the code image[y: y+height, x: x+width]
.
To start, let's take a look at the sample images I created. Image xyz has vertical bars and a shape of 600,600. The bars are the color 123 (where 0 is black and 255 is white).
Next, I created another image to add on top of image xyz. This image is called image abc. It has a shape of 300,300. The horizontal bars are also the color 123:
You can 'add' the images by replacing the pixels in the xyz image with the pixels in the abc image:
x,y = 123,123
replace = xyz.copy()
replace[y: y + abc_size, x: x + abc_size] = abc
cv2.imshow('replace', replace)
You can 'add' the images by summing the arrays. This will result in an image that is brighter in places than either of the source images. Summing will produce odd results if the values go out of the range (0, 255).
x,y = 123,123
added = xyz.copy()
added[y: y + abc_size, x: x + abc_size] += abc
cv2.imshow('added', added)
If you want to average the pixels in the images you can use the cv2.addWeighted() function.
background = np.zeros_like(xyz)
x,y = 123,123
background[y: y + abc_size, x: x + abc_size] = abc
add_weighted = cv2.addWeighted(background, .5, xyz, .5, 1)
cv2.imshow('add_weighted', add_weighted)

- 2,820
- 1
- 13
- 25