Python OpenCV(四)像素运算

一、像素的算术运算

1、加减乘除

import cv2as cv

#加add,减subtract,乘multiply,除divide

def add_demo(m1,m2):

    src = cv.add(m1,m2)

    cv.imshow("add_demo",src)

def subtract_demo(m1,m2):

    src = cv.subtract(m1,m2)

    cv.imshow("subtract_demo",src)

def divide_demo(m1,m2):

    src = cv.divide(m1,m2)

    cv.imshow("divide_demo",src)

def multiply_demo(m1,m2):

    src = cv.multiply(m1,m2)

    cv.imshow("multiply_demo",src)

img1 = cv.imread("D:/temp/img/LinuxLogo.jpg")

img2 = cv.imread("D:/temp/img/WindowsLogo.jpg")

cv.imshow("img1",img1)

cv.imshow("img2",img2)

add_demo (img1,img2)

subtract_demo (img1,img2)

divide_demo (img1,img2)

multiply_demo (img1,img2)

cv.waitKey(0)

cv.destroyAllWindows()

2、均值和方差

#返回均值

def others1(m1,m2):

    M1=cv.mean(m1)

    M2=cv.mean(m2)

    print(M1)

    print(M2)

#返回均值和方差

def others2(m1,m2):

    M1,dev1=cv.meanStdDev(m1)

    M2,dev2=cv.meanStdDev(m2)

    print(M1)

    print(M2)

    print(dev1)

    print(dev2)

二、像素的逻辑运算

1、逻辑运算:与或非

def logic_demo(m1,m2):

    scr1 = cv.bitwise_and(m1,m2)

    cv.imshow("logic_and",scr1)

    scr2 = cv.bitwise_or(m1, m2)

    cv.imshow("logic_or", scr2)

    src3 = cv.bitwise_not(m1)

    src4 = cv.bitwise_not(m2)

    cv.imshow("logic_or_src3",src3)

    cv.imshow("logic_or_src4", src4)

2、视频内容过滤进阶

import cv2 as cv

import  numpy as np

def extract_obj():

    cap = cv.VideoCapture("D:/temp/video/test12.mp4")

    while 1:

        ret,frame = cap.read()

        if ret ==False:

            break

        # 把视频中的黑色过滤出来,同时播放时依然显示黑色画面

        hsv = cv.cvtColor(frame,cv.COLOR_BGR2HSV)

        lower_hsv = np.array([0,0,0])

        upper_hsv = np.array([180,255,46])

        mask = cv.inRange(hsv,lowerb=lower_hsv,upperb=upper_hsv)

        dsc = cv.bitwise_and(frame,frame,mask=mask)

        cv.imshow("video",frame)

        cv.imshow("mask",dsc)

        if cv.waitKey(24)==30:

            break

extract_obj()

cv.waitKey(0)

cv.destroyAllWindows()

三、调节亮度和对比度

import cv2 as cv

#对比度、亮度调整

def contrast_brightness_demo(image,c,b):    #参数c对比度,b亮度

    h,w,ch=image.shape

    blank=np.zeros([h,w,ch],image.dtype)

    dst=cv.addWeighted(image,c,blank,0-c,b)

    cv.imshow("con_bri_demo",dst)

img=cv.imread("D:/temp/img/lena.jpg")

cv.imshow("img",img)

contrast_brightness_demo(img,1,100)

cv.waitKey (0)

cv.destroyAllWindows()

你可能感兴趣的:(Python OpenCV(四)像素运算)