Opencv+Python 像素运算

要求:图片的shape、dtype一致

import cv2

def add_demo(i1, i2, winName):  # 相加
    add_img = cv2.add(i1, i2)
    cv2.imshow(winName, add_img)

def subtract_demo(i1, i2, winName):  # 相减
    subtract_img = cv2.subtract(i1, i2)  # 相减注意先后顺序,此处为i1 - i2
    cv2.imshow(winName, subtract_img)

def multiply_demo(i1, i2, winName):  # 相乘
    multiply_img = cv2.multiply(i1, i2)
    cv2.imshow(winName, multiply_img)

def divide_demo(i1, i2, winName):  # 相除
    divide_img = cv2.divide(i1, i2)    # 相减注意先后顺序,此处为i1 / i2
    cv2.imshow(winName, divide_img)

def mean_demo(i1, i1_name):  # 通道均值
    mean_demo = cv2.mean(i1)
    print("%s的通道均值:%s" % (i1_name, mean_demo))

def meanStdDev(i1, i1_name):  # 通道均值,方差
    mean_demo, meanStdDev_demo = cv2.meanStdDev(i1)
    print("%s的通道均值:%s,方差:%s" % (i1_name, mean_demo, meanStdDev_demo))

def logic_demo(i1, i2, winName):  # 逻辑运算
    logic_img = cv2.bitwise_and(i1, i2)
    # cv2.bitwise_or()  # 或
    # cv2.bitwise_not()  # 非
    # cv2.bitwise_xor()  # 异或
    cv2.imshow(winName, logic_img)

img1 = cv2.imread(r"D:\OpencvTest\LinuxLogo.jpg", cv2.IMREAD_COLOR)
img2 = cv2.imread(r"D:\OpencvTest\WindowsLogo.jpg", cv2.IMREAD_COLOR)

add_demo(img1, img2, "img1 + img2")
subtract_demo(img1, img2, "img1 - img2")  # img1 - img2
subtract_demo(img2, img1, "img2 - img1")  # img2 - img1
multiply_demo(img1, img2, "img1 * img2")  # img1 * img2
multiply_demo(img2, img1, "img2 * img1")  # img2 * img1
divide_demo(img1, img2, "img1 / img2")  # img1 / img2
divide_demo(img2, img1, "img2 / img1")  # img2 / img1
mean_demo(img1, "img1")  # img1 的通道均值
mean_demo(img2, "img2")  # img2 的通道均值
meanStdDev(img1, "img1")  # img1 的通道均值、方差
meanStdDev(img2, "img2")  # img2 的通道均值、方差
logic_demo(img1, img2, "img1 and img2")  # and: 与运算

cv2.imshow("img1", img1)
cv2.imshow("img2", img2)

cv2.waitKey(0)
cv2.destroyAllWindows()

你可能感兴趣的:(Opencv+Python)