一、函數簡介
1、add—圖像矩陣相加
函數原型:cv2.add(src1, src2, dst=None, mask=None, dtype=None)
src1:圖像矩陣1
src1:圖像矩陣2
dst:默認選項
mask:默認選項
dtype:默認選項
2、subtract—圖像矩陣相減
函數原型:cv2.subtract(src1, src2, dst=None, mask=None, dtype=None)
src1:圖像矩陣1
src1:圖像矩陣2
dst:默認選項
mask:默認選項
dtype:默認選項
3、bitwise_and—圖像與運算
函數原型:cv2.bitwise_and(src1, src2, dst=None, mask=None)
src1:圖像矩陣1
src1:圖像矩陣2
dst:默認選項
mask:默認選項
4、bitwise_or—圖像或運算
函數原型:cv2.bitwise_or(src1, src2, dst=None, mask=None)
src1:圖像矩陣1
src1:圖像矩陣2
dst:默認選項
mask:默認選項
5、bitwise_xor—圖像異或運算
函數原型:bitwise_xor(src1, src2, dst=None, mask=None)
src1:圖像矩陣1
src1:圖像矩陣2
dst:默認選項
mask:默認選項
6、bitwise_not—圖像非運算
函數原型:bitwise_not(src1, src2, dst=None, mask=None)
src1:圖像矩陣1
src1:圖像矩陣2
dst:默認選項
mask:默認選項
二、實例演示
1、原圖像每個像素都加100,大於255的按255處理
#原始圖像每個像素都加100, 大於255的按255處理 import cv2 import numpy as np img = cv2.imread("test.png") cv2.imshow("Original", img) cv2.waitKey(0) #圖像img各像素加100 M = np.ones(img.shape, dtype='uint8')*100#與img大小一樣的全100矩陣 added = cv2.add(img, M)#將圖像image與M相加 cv2.imshow("Added", added) cv2.waitKey(0)
效果如下圖所示:
原圖:
2、原圖像每個像素都減去50,小於0的按0處理
#原圖像每個像素都減去50, 小於0的按0處理 import cv2 import numpy as np image = cv2.imread('test.png') cv2.imshow("Orignal", image) cv2.waitKey(0) #圖像image各像素減去50 M = np.ones(image.shape, dtype="uint8")*50 subtracted = cv2.subtract(image, M) cv2.imshow("Subtracted", subtracted) cv2.waitKey(0)
效果如圖所示:
3、矩形與圓形的交運算
#矩形與圓形的交運算 import numpy as np import cv2 #畫矩形 Rectangle = np.zeros((300, 300), dtype="uint8") cv2.rectangle(Rectangle,(25, 25), (275, 275), 255 ,-1) cv2.imshow("Rectangle", Rectangle) cv2.waitKey(0) #畫圓形 Circle = np.zeros((300, 300), dtype='uint8') cv2.circle(Circle, (150, 150), 150, 255, -1) cv2.imshow("Circle", Circle) cv2.waitKey(0) #圖像的交 bitwiseAnd = cv2.bitwise_and(Rectangle, Circle) cv2.imshow("AND", bitwiseAnd) cv2.waitKey(0)
效果如下所示:
4、矩形與圓形的或運算
import numpy as np import cv2 #畫矩形 Rectangle = np.zeros((300, 300), dtype="uint8") cv2.rectangle(Rectangle,(25, 25), (275, 275), 255 ,-1) cv2.imshow("Rectangle", Rectangle) cv2.waitKey(0) #畫圓形 Circle = np.zeros((300, 300), dtype='uint8') cv2.circle(Circle, (150, 150), 150, 255, -1) cv2.imshow("Circle", Circle) cv2.waitKey(0) #圖形的或 bitwiseor = cv2.bitwise_or(Rectangle, Circle) cv2.imshow("OR", bitwiseor) cv2.waitKey(0)
效果如圖所示:
5、矩形與圓形的異或運算
import numpy as np import cv2 #畫矩形 Rectangle = np.zeros((300, 300), dtype="uint8") cv2.rectangle(Rectangle,(25, 25), (275, 275), 255 ,-1) cv2.imshow("Rectangle", Rectangle) cv2.waitKey(0) #畫圓形 Circle = np.zeros((300, 300), dtype='uint8') cv2.circle(Circle, (150, 150), 150, 255, -1) cv2.imshow("Circle", Circle) cv2.waitKey(0) #圖像的異或 bitwisexor = cv2.bitwise_xor(Rectangle, Circle) cv2.imshow("XOR", bitwisexor) cv2.waitKey(0)
效果如圖所示:
6、圓形的非運算
import numpy as np import cv2 #畫圓形 Circle = np.zeros((300, 300), dtype='uint8') cv2.circle(Circle, (150, 150), 150, 255, -1) cv2.imshow("Circle", Circle) cv2.waitKey(0) #圓形的非運算 bitwisenot = cv2.bitwise_not(Circle) cv2.imshow("NOT", bitwisenot) cv2.waitKey(0)
效果如圖所示: