图片就是矩阵, 图片的加法运算就是矩阵的加法运算, 这就要求加法运算的两张图shape必须是相同的.
# 图片加法
import cv2
cat = cv2.imread('./cat.jpeg')
dog = cv2.imread('./dog.jpeg')
# 加法要求两个图片大小一致
print(cat.shape)
print(dog.shape)
# 把猫的图片变小
# 注意坑. opencv中resize中传递新的宽度和高度, 先宽度再高度, 所有是先列后行, 和shape的输出反了.
new_cat = cv2.resize(cat, (dog.shape[:-1][::-1]))
# 和单个数字运算, 超过255 会被截断, 相当于 % 256
print(new_cat[0:5, 0:5])
print(new_cat[0:5, 0:5] + 100)
cv2.imshow('cat_dog', np.hstack((new_cat, dog)))
# 加法, 加法的效果是加起来如果超过255, 统一变成255
new_img = cv2.add(new_cat, dog)
print(new_img[0:5, 0:5])
cv2.imshow('cat_dog', np.hstack((new_cat, dog, new_img)))
cv2.waitKey(0)
cv2.destroyAllWindows()
subtract
opencv使用subtract来执行图像的减法运算, 图像对应位置的元素相减, 如果减完小于0, 统一变成0.
# 图片减法
import cv2
cat = cv2.imread('./cat.jpeg')
dog = cv2.imread('./dog.jpeg')
# 加法要求两个图片大小一致
print(cat.shape)
print(dog.shape)
# 把猫的图片变小
# 注意坑. opencv中resize中传递新的宽度和高度, 先宽度再高度, 所以是先列后行, 和shape的输出刚好反了.
new_cat = cv2.resize(cat, (dog.shape[:-1][::-1]))
# 减法
new_img = cv2.subtract(new_cat, dog)
print(new_cat[0:5, 0:5], dog[0:5, 0:5])
print(new_img[0:5, 0:5])
cv2.imshow('cat_dog', np.hstack((new_cat, dog, new_img)))
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.addWeighted(src1, alpha, src2, beta, gamma)
图片的融合操作相当于对图片进行线性运算 w1* x1 + w2 * x2 + b. 其中alpha是第一个权重参数, beta是第二个权重参数, gamma是偏差.
import cv2
cat = cv2.imread('./cat.jpeg')
dog = cv2.imread('./dog.jpeg')
new_cat = cv2.resize(cat, (dog.shape[:-1][::-1]))
# 相当于res = new_cat * 0.4 + dog * 0.6 + 0
res = cv2.addWeighted(new_cat, 0.4, dog, 0.6, 0)
cv2.imshow('cat_dog', np.hstack((new_cat, dog, res)))
cv2.waitKey(0)
cv2.destroyAllWindows()
#python中的非 python中的与,python中的或,python中的异或
215&204,215|204,~255,215^204
OpenCV 中 图像每个像素点的值 最大为 255,最小为0,因此,无论是加减乘除,还是与或非以及异或运算,结果若大于255 则值为255
import cv2
import numpy as np
cat = cv2.imread('./cat.jpeg')
dog = cv2.imread('./dog.jpeg')
new_cat = cv2.resize(cat, (dog.shape[:-1][::-1]))
cat_and_dog = cv2.bitwise_and(new_cat, dog)
cv2.imshow('not', np.hstack((new_cat, cat_and_dog)))
print('cat:', new_cat[:3, :3])
print('-----------')
print('dog:', dog[:3, :3])
print('-----------')
print(cat_and_dog[:3, :3])
cv2.waitKey(0)
cv2.destroyAllWindows()
bitwise_or 或运算 对应元素做或运算
简单来说 或操作 数据会变大 图片变亮
bitwise_xor 异或运算 对应元素做异或运算
import cv2
import numpy as np
#创建一张图片
img = np.zeros((200,200), np.uint8)
img2 = np.zeros((200,200), np.uint8)
img[20:120, 20:120] = 255
img2[80:180, 80:180] = 255
#new_img = cv2.bitwise_bit(img)
#new_img = cv2.bitwise_and(img, img2)
#new_img = cv2.bitwise_or(img, img2)
new_img = cv2.bitwise_xor(img, img2)
cv2.imshow('new_img', new_img)
cv2.imshow('img', img)
cv2.imshow('img2', img2)
cv2.waitKey(0)
import cv2
import numpy as np
cat = cv2.imread('./cat.jpeg')
dog = cv2.imread('./dog.jpeg')
cat_not = cv2.bitwise_not(cat)
cat_not_not = cv2.bitwise_not(cat_not)
cv2.imshow('not', np.hstack((cat, cat_not, cat_not_not)))
print(cat[:3, :3])
print(cat_not[:3, :3])
print(cat_not_not[:3, :3]
cv2.waitKey(0)
cv2.destroyAllWindows()