python-opencv-圖像的算數運算


 

圖像相加:

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)

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM