学习图像上的算术运算,加法,减法,位运算等。
# -*- coding: utf-8 -*-
import numpy as np
import cv2
# 图像加法
cv2.imread("namei.jpeg")
x = np.uint8([250])
y = np.uint8([10])
print(cv2.add(x, y))
print(x+y)
# 图像混合
img1 = cv2.imread("lufei.jpg")
img2 = cv2.imread("namei.jpeg")
img3 = img2[0:636,0:500]
print(img1.size)
print(img1.shape)
print(img2.size)
print(img2.shape)
print(img3.shape)
print(img3.size)
add = cv2.add(img1, img3)
dst = cv2.addWeighted(img1, 0.3, img3, 0.7, 0)
cv2.imshow('add', add)
cv2.imshow("dst", dst)
cv2.waitKey(0)
cv2.destroyAllWindows()
image.png
按位运算
import cv2
import numpy as np
img1 = cv2.imread('lufei.jpg')
img2 = cv2.imread('namei.jpeg')
# I want to put lufei on top-left corner, So I create a ROI
rows, cols, channels = img1.shape
print('rows: %s, cols: %s, channels: %s'%(rows,cols,channels))
namei = img2[0:rows, 0:cols]
# Now create a mask of logo and create its inverse mask also
img1gray = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
ret, mask = cv2.threshold(img1gray, 245, 255, cv2.THRESH_BINARY)
mask_inv = cv2.bitwise_not(mask)
# Now black-out the area of logo in ROI
# 取roi 中与mask 中不为零的值对应的像素的值,其他值为0
# 注意这里必须有mask=mask 或者mask=mask_inv, 其中的mask= 不能忽略
img2_bg = cv2.bitwise_and(namei, namei, mask=mask)
img1_fg = cv2.bitwise_and(img1, img1, mask=mask_inv)
# Put logo in ROI and modify the main image
dst = cv2.add(img2_bg, img1_fg)
img2[0:rows, 0:cols] = dst
cv2.imshow('lufei', img1)
# cv2.imshow('img1gray', img1gray)
# cv2.imshow('mask_inv', mask)
# cv2.imshow('img2_fg', img1_fg)
# cv2.imshow('namei', namei)
cv2.imshow('res', img2)
cv2.waitKey(0)
cv2.destroyAllWindows()
image.png
网友评论