OpenCV-Python之像素运算

1.算术运算:加减乘除

import cv2 as cv

def add_img(m1, m2):
    dst = cv.add(m1, m2)
    cv.imshow("add image", dst)

def subtract_img(m1, m2):
    dst = cv.subtract(m1, m2)
    cv.imshow("subtract image", dst)

def multiply_img(m1, m2):
    dst = cv.multiply(m1, m2)
    cv.imshow("multiply image", dst)

def divide_img(m1, m2):
    dst = cv.divide(m1, m2)
    cv.imshow("divide image", dst)

src1 = cv.imread("./data/LinuxLogo.jpg", 1)
src2 = cv.imread("./data/WindowsLogo.jpg", 1)
cv.imshow("src1 image", src1)
cv.imshow("src2 image", src2)
print(src1.shape, src2.shape)

add_img(src1, src2)
subtract_img(src1, src2)
divide_img(src1, src2)
multiply_img(src1, src2)


cv.waitKey(0)
cv.destroyAllWindows()

OpenCV-Python之像素运算_第1张图片

2.求均值和标准差

import cv2 as cv
#仅求均值
def mean_image(m1, m2):
    M1 = cv.mean(m1)
    M2 = cv.mean(m2)
    print(M1)
    print(M2)
#求均值以及标准差
def others(m1, m2):
    M1, dev1 = cv.meanStdDev(m1)
    M2, dev2 = cv.meanStdDev(m2)
	#构造纯黑图片
    h, w = m1.shape[:2]#get height and width
    img = np.zeros([h, w], np.uint8)
    m, d = cv.meanStdDev(img)

    print(M1,'\n',  dev1)
    print(M2,'\n', dev2)
    print(m, '\n',d)
    
src1 = cv.imread("./data/LinuxLogo.jpg", 1)
src2 = cv.imread("./data/WindowsLogo.jpg", 1)
cv.imshow("src1 image", src1)
cv.imshow("src2 image", src2)
others(src1, src2)
cv.waitKey(0)
cv.destroyAllWindows()

3.逻辑运算

应用:遮罩层控制

#逻辑运算 与或非
def logic_demo(m1, m2):
    dst_and = cv.bitwise_and(m1, m2)
    dst_or = cv.bitwise_or(m1, m2)
    dst_not = cv.bitwise_not(m1, m2)
    cv.imshow("logic_and image", dst_and)
    cv.imshow("logic_or image", dst_or)
    cv.imshow("logic_not image", dst_not)
src1 = cv.imread("./data/LinuxLogo.jpg", 1)
src2 = cv.imread("./data/WindowsLogo.jpg", 1)
cv.imshow("src1 image", src1)
cv.imshow("src2 image", src2)
logic_demo(src2, src1)
cv.waitKey(0)
cv.destroyAllWindows()

OpenCV-Python之像素运算_第2张图片

4. 调整亮度和对比度

需要用到的API为addWeighted:
addWeighted(src1, alpha, src2, beta, gamma, dst=None, dtype=None)

非常重要:python灵活的一点在于,只要参数为None的,都可以作为返回值接收

# 对比度和亮度调整
def contract_brightness_demo(img, c, b):
    h, w, ch = img.shape
    blank = np.zeros([h, w, ch], img.dtype)
    dst = cv.addWeighted(img, c, blank, 1-c, b)
    cv.imshow("con_bri_demo", dst)
image = cv.imread('./data/lena.jpg', 1)
cv.imshow('source image', image)
contract_brightness_demo(image, 1.2, 50)
cv.waitKey(0)
cv.destroyAllWindows()

OpenCV-Python之像素运算_第3张图片

你可能感兴趣的:(Computer,Vision,#,OpenCV,OpenCV)