- 1 image overlay
- 2 image fusion
- 3 bitwise operation
1 image overlay
Two images can be added through the opencv function cv. Add() or simply through the numpy operation, res = img1 + img2. The two images should have the same depth and type, or the second image can be a scalar value
- Opencv addition is a saturation operation, that is, there is an upper limit value, while numpy addition is a modular operation.
- When adding two images, opencv function will provide better results. So always adhere to opencv function better
import cv2 import numpy as np x = np.uint8() y = np.uint8() print( cv2.add(x,y) ) # 250+10 = 260 => 255 print( x+y ) # 250+10 = 260 % 256 = 4
2 image fusion
This is also image addition, but the image is given different weights (between 0 and 1) to make it have a sense of mixing or transparency.
import cv2 import numpy as np img1 = cv2.imread('img.jpg') img2 = cv2.imread('img2.jpg') Img2 = cv2.resize (img2, (480331)) # unified picture size dst = cv2.addWeighted(img1,0.5,img2,0.5,0) cv2.imshow('dst',dst) cv2.waitKey(0) cv2.destroyAllWindows()
3 bitwise operation
Including bitwise and, or, not and XOR operations
You want to put the opencv logo above the image. If you overlay two images, it will change the color; If you fuse two images, you will get a transparent effect. I want it to be opaque. If it is a rectangular area, I can use ROI to operate as described above, but the opencv logo is not rectangular and can complete relevant functions by bit
import cv2 import numpy as np img1 = cv2.imread('img.jpg') img2 = cv2.imread('img1.jpg') img2 = cv2.resize(img2,(100,100)) # 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 = cv2.cvtColor(img2,cv2.COLOR_BGR2GRAY) ret, mask = cv2.threshold(img2gray, 200, 255, cv2.THRESH_BINARY) mask_inv = cv2.bitwise_not(mask) # Now black-out the area of logo in ROI img1_bg = cv2.bitwise_and(roi,roi,mask = mask) # Take only region of logo from logo image. img2_fg = cv2.bitwise_and(img2,img2,mask = mask_inv) # Put logo in ROI and modify the main image dst = cv2.add(img1_bg,img2_fg) img1[0:rows, 0:cols ] = dst cv2.imshow('res',img1) cv2.waitKey(0) cv2.destroyAllWindows()
Arithmetic Operations on Images
This is the end of this article about the specific implementation of OpenCV image overlay, image fusion and bitwise operation in Python. For more information about OpenCV image overlay, image fusion and bitwise operation, please search for previous articles of developpaer or continue to browse the relevant chapters below. I hope you will support developpaer in the future!