图像基本运算
图像算数运算:
1)图像加法
示例代码:
import cv2
import numpy as np
img1 = cv2.imread(‘…/datas/fengjing1.png’)#(546, 820, 3)
img2 = cv2.imread(‘…/datas/logo.png’)#(512, 512, 3)
print(img1.shape)
img1resize = cv2.resize(img1, (244, 300) )
dst = cv2.add(img1resize, img2)
dstw = cv2.addWeighted(img1resize, 0.6, img2, -1, 100)
dst2 = img1resize + img2
cv2.imshow(‘add’, np.hstack([dst, dstw,dst2 ]))
cv2.waitKey(0)
cv2.addWeighted() # 权重加和
2)图像减法
示例代码:
import cv2
import numpy as np
img1 = cv2.imread(‘…/datas/fengjing1.png’)#(546, 820, 3)
img2 = cv2.imread(‘…/datas/logo.png’)#(512, 512, 3)
print(img1.shape)
img1resize = cv2.resize(img1, (244, 300) )
dstw = cv2.addWeighted(img1resize, 0.6, img2, -1, 100)
dst2 = cv2.subtract(img1resize, img2)
cv2.imshow(‘sub’, np.hstack([dstw, dst2]))
cv2.waitKey(0)
cv2.subtract() #图像相减
3)图像乘除法
dst = 2 * img1
dst = img1/3
图像逻辑运算:
1)图像相与
2)图像相或
3)图像异或
照片裁剪示例代码:
import cv2
import numpy as np
img1 = cv2.imread(‘…/datas/fengjing1.png’)
img2 = cv2.imread(‘…/datas/logo.png’)
h, w, c = img2.shape
roi = img1[0:h, 0:w]
cv2.imshow(‘roi’, roi)
cv2.waitKey(0)
应用示例代码:
import cv2
import numpy as np
img1 = cv2.imread(‘…/datas/fengjing1.png’)
img2 = cv2.imread(‘…/datas/logo.png’)
h, w, c = img2.shape
roi = img1[0:h, 0:w]
test = cv2.bitwise_and(roi, roi)
#二值化
img2gray = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
retval, mask = cv2.threshold(img2gray, 230, 255, cv2.THRESH_BINARY)
masks = cv2.merge([mask, mask, mask])# np.stack([mask, mask, mask], axis=2)
#roi与roi进行逻辑与,使用mask(获取背景)
dst_bg = cv2.bitwise_and(roi, roi, mask=mask)
#获取前景
mask_inv = cv2.bitwise_not(mask)
masks_inv = np.stack([mask_inv, mask_inv, mask_inv], axis=2)
#cv2.imshow(‘logo and mask’, np.hstack([img2,masks_inv, masks]))
#cv2.waitKey(0)
dst_fg = cv2.bitwise_and(img2, img2, mask=mask_inv)
#cv2.imshow(‘dst_fg’, np.hstack([img2, masks_inv, dst_fg]))
#cv2.waitKey(0)
dst1 = dst_bg + dst_fg
dst2 = cv2.add(dst_bg, dst_fg)
img1[0:h, 0:w] = dst1
#cv2.imshow(‘and’, np.hstack([roi, dst_bg, dst_fg, dst1, dst2]))
#cv2.waitKey(0)
cv2.imshow(‘result’, img1)
cv2.waitKey(0)