圖像相加:
import cv2 import numpy as np image = cv2.imread("3.jpg") cv2.imshow("3",image) #圖像image各像素加100 M = np.ones(image.shape,dtype="uint8")*100 #與image大小一樣的全100矩陣 added = cv2.add(image,M) #兩個圖像相加 # 大於255的按255處理 cv2.imshow("Added",added) cv2.waitKey(0)
效果圖:
圖像相減:
import cv2 import numpy as np image = cv2.imread("3.jpg") cv2.imshow("yuan",image) #圖像image各像素減去50 M = np.ones(image.shape,dtype="uint8")*50 #與image大小一樣的全100矩陣 img = cv2.subtract(image,M) #圖像image減去圖像M # 小於0的按0處理 cv2.imshow("hou",img) cv2.waitKey(0)
效果圖:
圖像的交集運算--與運算
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) #畫圓形 Circle = np.zeros((300,300),dtype="uint8") cv2.circle(Circle,(150,150),150,255,-1) cv2.imshow("Circle",Circle) #圖像的交 bitwiseAnd = cv2.bitwise_and(Rectangle,Circle) cv2.imshow("AND",bitwiseAnd) cv2.waitKey(0)
cv2.bitwise_and()是對二進制數據進行“與”操作,即對圖像(灰度圖像或彩色圖像均可)每個像素值進行二進制“與”操作,1&1=1,1&0=0,0&1=0,0&0=0
效果圖:
圖像的或運算:
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) #畫圓形 Circle = np.zeros((300,300),dtype="uint8") cv2.circle(Circle,(150,150),150,255,-1) cv2.imshow("Circle",Circle) #圖像的交 bitwiseAnd = cv2.bitwise_or(Rectangle,Circle) #或運算--並集 cv2.imshow("AND",bitwiseAnd) cv2.waitKey(0)
效果圖:
異或運算:
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) #畫圓形 Circle = np.zeros((300,300),dtype="uint8") cv2.circle(Circle,(150,150),150,255,-1) cv2.imshow("Circle",Circle) #圖像的交 bitwiseXor = cv2.bitwise_xor(Rectangle,Circle) #圖像的異或 cv2.imshow("XOR",bitwiseXor) cv2.waitKey(0)
效果圖:
非運算:
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) bitwiseNot = cv2.bitwise_not(Circle) #非運算 cv2.imshow("NOT",bitwiseNot) cv2.waitKey(0)