When I learn opencv python docoments, I found this interesting example : put an opencv logo on an image about messi.
# Sys.setenv(RETICULATE_PYTHON = 'D:\\application\\Miniconda3\\envs\\blog_python\\python.exe')
library(reticulate)
# !pip install opencv-python -i https://pypi.tuna.tsinghua.edu.cn/simple
import cv2 as cv
from matplotlib import pyplot as plt
# %matplotlib inline
# to RGB image display, below code transform bgr (blue-green-red) to rgb
# img[:,:,::-1]
# Load two images
img1 = cv.imread('data/messi_test.PNG')
img2 = cv.imread('data/opencv_logo_color_test.PNG')
plt.imshow(img1[:,:,::-1])
plt.show()
plt.imshow(img2[:,:,::-1])
plt.show()
# I want to put logo on top-left corner, So I create a ROI
rows,cols,channels = img2.shape
roi = img1[0:rows, 0:cols]
# Now create a mask of logo and create its inverse mask also
img2gray = cv.cvtColor(img2,cv.COLOR_BGR2GRAY)
ret, mask = cv.threshold(img2gray, 10, 255, cv.THRESH_BINARY)
mask_inv = cv.bitwise_not(mask)
plt.imshow(img2gray)
plt.show()
plt.imshow(mask)
plt.show()
plt.imshow(mask_inv)
plt.show()
# Now black-out the area of logo in ROI
img1_bg = cv.bitwise_and(roi,roi,mask = mask_inv)
plt.imshow(img1_bg[:,:,::-1])
plt.show()
# Take only region of logo from logo image.
img2_fg = cv.bitwise_and(img2,img2,mask = mask)
plt.imshow(img2_fg[:,:,::-1])
plt.show()
# Put logo in ROI and modify the main image
dst = cv.add(img1_bg,img2_fg)
img1[0:rows, 0:cols ] = dst
plt.imshow(img1[:,:,::-1])
plt.show()