OpenCV(python)从入门到精通——运算操作

发布于:2024-12-21 ⋅ 阅读:(10) ⋅ 点赞:(0)
  • 加法减法操作
import cv2 as cv
import numpy as np

x = np.uint8([250])
y = np.uint8([10])

x_1 = np.uint8([10])
y_1 = np.uint8([20])

# 加法,相加最大只能为255
print(cv.add(x,y))

# 减法,相互减最小值只能为0
print(cv.subtract(x_1,y_1))
  • 图像加法
    在这里插入图片描述
import cv2 as cv
import numpy as np

img1 = cv.imread("./images/1.jpg")

img2 = cv.imread("./images/1_test.jpg")


img = cv.add(img1,img2)

cv.imshow("pic",img)
cv.waitKey(0)

在这里插入图片描述

  • 图像权重相加,因为我使用的都是同一张图片
import cv2 as cv
import numpy as np

img1 = cv.imread("./images/1.jpg")

img2 = cv.imread("./images/1_test.jpg")


# img = cv.add(img1,img2)
img = cv.addWeighted(img1,0.5,img2,0.8,gamma=0)
cv.imshow("pic",img)
cv.waitKey(0)

在这里插入图片描述

  • 按位与操作
import cv2 as cv
import numpy as np

img1 = cv.imread("./images/1.jpg")

img2 = cv.imread("./images/1_test.jpg")


# img = cv.add(img1,img2)
# img = cv.addWeighted(img1,0.5,img2,0.8,gamma=0)
rows,cols,channels = img2.shape
roi = img1[0:rows,0:cols]
img2gray = cv.cvtColor(img2,cv.COLOR_BGR2GRAY)
ret,mask = cv.threshold(img2gray,10,255,cv.THRESH_BINARY|cv.THRESH_OTSU)
mask_inv = cv.bitwise_not(mask)

img1_bg = cv.bitwise_and(roi,roi,mask=mask_inv)
cv.imshow("img1_bg",img1_bg)
cv.waitKey(0)



在这里插入图片描述

  • 按位取反操作
import cv2 as cv
import numpy as np

img1 = cv.imread("./images/1.jpg")

img2 = cv.imread("./images/1_test.jpg")


# img = cv.add(img1,img2)
# img = cv.addWeighted(img1,0.5,img2,0.8,gamma=0)
rows,cols,channels = img2.shape
roi = img1[0:rows,0:cols]
img2gray = cv.cvtColor(img2,cv.COLOR_BGR2GRAY)
ret,mask = cv.threshold(img2gray,10,255,cv.THRESH_BINARY|cv.THRESH_OTSU)
mask_inv = cv.bitwise_not(mask)

img1_bg = cv.bitwise_not(roi,roi,mask=mask_inv)
cv.imshow("img1_bg",img1_bg)
cv.waitKey(0)


在这里插入图片描述

  • 按位或

import cv2 as cv
import numpy as np

img1 = cv.imread("./images/1.jpg")

img2 = cv.imread("./images/1_test.jpg")


# img = cv.add(img1,img2)
# img = cv.addWeighted(img1,0.5,img2,0.8,gamma=0)
rows,cols,channels = img2.shape
roi = img1[0:rows,0:cols]
img2gray = cv.cvtColor(img2,cv.COLOR_BGR2GRAY)
ret,mask = cv.threshold(img2gray,10,255,cv.THRESH_BINARY|cv.THRESH_OTSU)
cv.imshow("img3",roi)
cv.imshow("img1",mask)
mask_inv = cv.bitwise_not(mask)

img1_bg = cv.bitwise_or(roi,roi,mask=mask_inv)
cv.imshow("img1_bg",img1_bg)
cv.waitKey(0)




在这里插入图片描述

  • 按位异或
import cv2 as cv
import numpy as np

img1 = cv.imread("./images/1.jpg")

img2 = cv.imread("./images/1_test.jpg")


# img = cv.add(img1,img2)
# img = cv.addWeighted(img1,0.5,img2,0.8,gamma=0)
rows,cols,channels = img2.shape
roi = img1[0:rows,0:cols]
img2gray = cv.cvtColor(img2,cv.COLOR_BGR2GRAY)
ret,mask = cv.threshold(img2gray,10,255,cv.THRESH_BINARY|cv.THRESH_OTSU)
cv.imshow("img3",roi)
cv.imshow("img1",mask)
mask_inv = cv.bitwise_xor(mask,mask)

img1_bg = cv.bitwise_or(roi,roi,mask=mask_inv)
cv.imshow("img1_bg",img1_bg)
cv.waitKey(0)