关于图像的位操作,目的是为了将一个logo覆盖到另一个图片上。
# -*- coding: utf-8 -*-
import numpy as np
import cv2
def show(img_name,img_data):
cv2.imshow(img_name,img_data)
cv2.waitKey(0)
cv2.destroyAllWindows()
# Load two images
img1 = cv2.imread('ml.png')
img2 = cv2.imread('opencv_logo.png')
# I want to put ligo on top-left corner,so I create a ROI
rows,cols,channels = img2.shape
roi = img1[0:rows,0:cols]
#show('roi',roi)
# Now create a mask of logo and create its inverse mask also
img2gray = cv2.cvtColor(img2,cv2.COLOR_BGR2GRAY)
#show('img2gray',img2gray)
# threshold 阀值函数
# grayscale image; threshold; maxval; function of style
# THRESH_BINARY
ret, mask = cv2.threshold(img2gray,10,255,cv2.THRESH_BINARY)
#show('mask',mask)
mask_inv = cv2.bitwise_not(mask)
#show('mask_inv',mask_inv)
# Now black-out the area of logo in ROI
# sr1;sr2;dst;mask;
# dst 就是记录结果的 mask 就是控制位
# 就是 2个数据都要先和mask按位和 然后再按位和 如果有mask这个参数的话
# 通过位的与运算,达到“掩盖”的目的
img1_bg = cv2.bitwise_and(roi,roi,mask = mask_inv)
#show('img1_bg',img1_bg)
# Take only region of logo from logo image
img2_fg = cv2.bitwise_and(img2,img2,mask=mask)
#show('img2_fg',img2_fg)
# Put logo in ROI and modify the main image
dst = cv2.add(img1_bg,img2_fg)
show('dst',dst)
img1[0:rows,0:cols] = dst
show('res',img1)
转自https://www.cnblogs.com/buzhizhitong/p/5918504.html