In this tutorial, we will introduce how to replace a part of big image using an small image or numpy array, which is very useful when you plan to recognize objects from images.
Read a big image using python opencv
We will use python opencv to read an image data first.
import cv2 import numpy as np from matplotlib import pyplot as plt img = cv2.imread('comment_source.jpg', cv2.IMREAD_COLOR) img2 = img.copy()
Create a small image or numpy array
We will use a small image or numpy array to replace a part region of img2.
mask = np.zeros((100,300, 3)) print(mask.shape) #h, w, 3
In this code, mask is a small image with height=100 , width=300 and brg=(0,0,0)
Replace a part of big image
We will replace a part of big image from the coordinate (200, 200)
pos = (200, 200) img2[200:(200+mask.shape[0]), 200:(200+mask.shape[1])] = mask
In order to understand how to replace numpy array with a small array, you can read:
NumPy Replace Value in Array Using a Small Array or Matrix – NumPy Tutorial
Show the replaced image
We will use matplotlib to show img2.
To know how to display image using matplotlib, you can view:
Understand matplotlib.pyplot.imshow(): Display Data as an Image – Matplotlib Tutorial
plt.subplot(121), plt.imshow(img), plt.title('Source Image'), plt.axis('off') plt.subplot(122), plt.imshow(img2), plt.title('Replaced Image'), plt.axis('off') plt.show()
Run this code, you will find: