OpenCV学习笔记7-图像算术运算

1.图像加法

cv2.add(img1, img2[, dst[, mask[, dtype]]]) -> dst(图像矩阵)

*img1和img2应该是大小相同的两个图像矩阵


import numpy as np
import cv2

img1 = cv2.imread('1.png')
img2 = cv2.imread('opencv_logo.jpg')
img3 = cv2.add(img1, img2)
cv2.imshow('image', img3)
cv2.waitKey(0)
cv2.destroyAllWindows()

2.图像加权

cv2.addWeighted(img1, 权重1, img2, 权重2, 常数项[, dst[,dtype]]) -> dst(图像矩阵)

dst = a*img1 + b*img2 + c


import numpy as np
import cv2

img1 = cv2.imread('1.png')
img2 = cv2.imread('opencv_logo.jpg')
img3 = cv2.addWeighted(img1, 0.7, img2, 0.3, 0)
cv2.imshow('image', img3)
cv2.waitKey(0)
cv2.destroyAllWindows()

3.位运算(AND/OR/NOT/XOR)

  • bitwise_and(src1, src2[, dst[, mask]]) -> dst
  • bitwise_or(src1, src2[, dst[, mask]]) -> dst
  • bitwise_not(src[, dst[, mask]]) -> dst
  • bitwise_xor(src1, src2[, dst[, mask]]) -> dst
  • threshold(src, thresh(阈值), maxval, type[, dst]) -> retval, dst #获取二元值的灰度图像

*mask是运算的模版,可认为是控制每个像素点是否进行运算的矩阵


import numpy as np
import cv2
from matplotlib import pyplot as plt

img1 = cv2.imread('Yzy.jpg')
img2 = cv2.imread('opencv_logo.jpg')

#按照opencv_logo的大小,以及想被放置的位置,从Yzy.jpg中取出ROI
rows, cols, channels = img2.shape
roi = img1[0:rows, 0:cols, :]

#将opencv_logo灰度图像二值化,获取mask和mask_inv
img2gray = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
ret, mask = cv2.threshold(img2gray, 175, 255, cv2.THRESH_BINARY)
mask_inv = cv2.bitwise_not(mask)

#取roi中与mask中不为0的值对应的像素的值,其他值为0,将roi中放置logo的地方标记出来
#取img2中与mask_inv中不为0的值对应的像素的值,其他值为0,仅把logo分割出来
img1_bg = cv2.bitwise_and(roi, roi, mask=mask)
img2_fg = cv2.bitwise_and(img2, img2, mask=mask_inv)

#将背景和前景相加
dst = cv2.add(img1_bg, img2_fg)
img1[0:rows, 0:cols, :] = dst

cv2.namedWindow('res', cv2.WINDOW_NORMAL)
cv2.imshow('res', img1)
#cv2.imshow('1', img1_bg)
#cv2.imshow('2', img2_fg)
cv2.waitKey(0)
cv2.destroyAllWindows()

你可能感兴趣的:(opencv学习笔记,opencv)