图像相加:
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)