Python+OpenCV3.3图像处理视频教程 贾志刚 代码笔记1

2 图像加载与保存

import cv2 as cv
import numpy as np


def video_demo():
    capture = cv.VideoCapture(0)
    while(True):
        ret, frame = capture.read()
        frame = cv.flip(frame, 1)#左右调换
        cv.imshow("video", frame)
        c = cv.waitKey(50)
        if c == 27:
            break


def get_image_info(image):
    print(type(image))
    print(image.shape)
    print(image.size)
    print(image.dtype)
    pixel_data = np.array(image)
    print(pixel_data)


print("--------- Hello Python ---------")
src = cv.imread("D:/vcprojects/images/dog.jpg")
cv.namedWindow("input image", cv.WINDOW_AUTOSIZE)
cv.imshow("input image", src)
get_image_info(src)
video_demo()#调用摄像头
gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
cv.imwrite("D:/result.png", gray)
#cv.imshow("gray image", gray)
cv.waitKey(0)

cv.destroyAllWindows()

--------- Hello Python ---------

(576, 768, 3)
1327104
uint8
[[[ 50 58 57]
[ 51 59 58]
[ 53 61 60]

[ 47 89 142]
[ 41 50 88]
[ 47 71 63]]

[[ 51 59 58]
[ 51 59 58]
[ 52 60 59]

[ 37 74 124]
[ 41 50 83]
[ 46 70 58]]

[[ 51 59 58]
[ 51 59 58]
[ 52 60 59]

[ 25 54 98]
[ 48 54 77]
[ 43 62 45]]

[[179 168 160]
[179 168 160]
[182 171 163]

[ 64 64 80]
[ 36 39 53]
[ 48 53 62]]

[[180 169 161]
[179 168 160]
[175 164 156]

[ 61 61 79]
[ 37 40 54]
[ 52 56 67]]

[[176 165 157]
[178 167 159]
[172 161 153]

[ 62 62 80]
[ 33 36 50]
[ 35 39 50]]]

3 numpy数组操作

import cv2 as cv
import numpy as np


def access_pixels(image):
    print(image.shape);
    height = image.shape[0]
    width = image.shape[1]
    channels = image.shape[2]
    print("width : %s, height : %s channels : %s"%(width, height, channels))
    for row in range(height):
        for col in range(width):
            for c in range(channels):
                pv = image[row, col, c]
                image[row, col, c] = 255 - pv
    cv.imshow("pixels_demo", image)


def inverse(image):
    dst = cv.bitwise_not(image)#像素值二进制非操作,像素取反
    cv.imshow("inverse demo", dst)


def create_image():
    """
    img = np.zeros([400, 400, 3], np.uint8)
    #img[: , : , 0] = np.ones([400, 400])*255
    img[:, :, 2] = np.ones([400, 400]) * 255
    cv.imshow("new image", img)

    img = np.ones([400, 400, 1], np.uint8)
    img = img * 0
    cv.imshow("new image", img)
    cv.imwrite("D:/myImage.png", img)
    """

    m1 = np.ones([3, 3], np.uint8)
    m1.fill(12222.388)
    print(m1)

    m2 = m1.reshape([1, 9])
    print(m2)

    m3 = np.array([[2,3,4], [4,5,6],[7,8,9]], np.int32)
    #m3.fill(9)
    print(m3)

print("--------- Hello Python ---------")
src = cv.imread("D:/vcprojects/images/demo.png") # blue, green red
cv.namedWindow("input image", cv.WINDOW_AUTOSIZE)
cv.imshow("input image", src)
access_pixels(src)

t1 = cv.getTickCount()
create_image()
t2 = cv.getTickCount()
time = (t2-t1)/cv.getTickFrequency();#运行时间 s
print("time : %s ms"%(time*1000))
cv.waitKey(0)

cv.destroyAllWindows()

--------- Hello Python ---------
(448, 444, 3)
width : 444, height : 448 channels : 3
[[190 190 190]
[190 190 190]
[190 190 190]]
[[190 190 190 190 190 190 190 190 190]]
[[2 3 4]
[4 5 6]
[7 8 9]]
time : 0.6542 ms

Python+OpenCV3.3图像处理视频教程 贾志刚 代码笔记1_第1张图片

4 色彩空间1

import cv2 as cv
import numpy as np

def color_space_demo(image):
    gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
    cv.imshow("gray", gray)
    hsv = cv.cvtColor(image, cv.COLOR_BGR2HSV)
    cv.imshow("hsv", hsv)
    yuv = cv.cvtColor(image, cv.COLOR_BGR2YUV)
    cv.imshow("yuv", yuv)
    Ycrcb = cv.cvtColor(image, cv.COLOR_BGR2YCrCb)
    cv.imshow("ycrcb", Ycrcb)

print("--------- Hello Python ---------")
src = cv.imread("D:/vcprojects/images/demo.png")
cv.namedWindow("input image", cv.WINDOW_AUTOSIZE)
cv.imshow("input image", src)

color_space_demo(src)

cv.waitKey(0)
cv.destroyAllWindows()

5 色彩空间2

import cv2 as cv
import numpy as np

def extrace_object_demo():
    #capture = cv.VideoCapture("D:/vcprojects/images/video_006.mp4")
    capture = cv.VideoCapture("D:/vcprojects/images/color_object.mp4")

    while(True):
        ret, frame = capture.read()
        if ret == False:
            break;
        hsv = cv.cvtColor(frame, cv.COLOR_BGR2HSV)
        # #hsv绿色 min max:
        # lower_hsv = np.array([37, 43, 46])
        # upper_hsv = np.array([77, 255, 255])

        #hsv红色 min max:
        lower_hsv = np.array([0, 43, 46])
        upper_hsv = np.array([10, 255, 255])

        mask = cv.inRange(hsv, lowerb=lower_hsv, upperb=upper_hsv)
        dst = cv.bitwise_and(frame, frame, mask=mask)
        cv.imshow("video", frame)
        cv.imshow("mask", dst)
        c = cv.waitKey(40)
        if c == 27:#esc
            break


print("--------- Hello Python ---------")
src = cv.imread("D:/vcprojects/images/demo.png")
cv.namedWindow("input image", cv.WINDOW_AUTOSIZE)
cv.imshow("input image", src)

b, g, r = cv.split(src)
cv.imshow("blue", b)
cv.imshow("green", g)
cv.imshow("red", r)

src = cv.merge([b, g, r])#通道合并
src[:, :, 0] = 0
cv.imshow("changed image", src)

extrace_object_demo()

cv.waitKey(0)
cv.destroyAllWindows()

Python+OpenCV3.3图像处理视频教程 贾志刚 代码笔记1_第2张图片

6 像素运算1

import cv2 as cv
import numpy as np

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

def subtract_demo(m1, m2):#减
    dst = cv.subtract(m1, m2)
    cv.imshow("subtract_demo", dst)

def divide_demo(m1, m2):#除
    dst = cv.divide(m1, m2)
    cv.imshow("divide_demo", dst)

def multiply_demo(m1, m2):#乘
    dst = cv.multiply(m1, m2)
    cv.imshow("multiply_demo", dst)

def others(m1, m2):
    M1, dev1 = cv.meanStdDev(m1)#均值、标准方差
    M2, dev2 = cv.meanStdDev(m2)
    h, w = m1.shape[:2]

    print(M1)
    print(M2)

    print(dev1)
    print(dev2)

    img = np.zeros([h, w], np.uint8)
    m, dev = cv.meanStdDev(img)
    print(m)
    print(dev)
    

print("--------- Hello Python ---------")
src1 = cv.imread("D:/vcprojects/images/LinuxLogo.jpg")
src2 = cv.imread("D:/vcprojects/images/WindowsLogo.jpg")
print(src1.shape)
print(src2.shape)
cv.namedWindow("image1", cv.WINDOW_AUTOSIZE)
cv.imshow("image1", src1)
cv.imshow("image2", src2)

add_demo(src1, src2)
subtract_demo(src1, src2)
divide_demo(src1, src2)
multiply_demo(src1, src2)

others(src1, src2)

cv.waitKey(0)

cv.destroyAllWindows()

--------- Hello Python ---------
(240, 320, 3)
(240, 320, 3)
[[15.0128125]
[15.0128125]
[15.0128125]]
[[128.05269531]
[109.60858073]
[ 62.55748698]]
[[58.14062149]
[58.14062149]
[58.14062149]]
[[54.60093646]
[45.52335089]
[50.01800277]]
[[0.]]
[[0.]]

Python+OpenCV3.3图像处理视频教程 贾志刚 代码笔记1_第3张图片

7 像素运算2

import cv2 as cv
import numpy as np

def logic_demo(m1, m2):#逻辑运算
    dst_and = cv.bitwise_and(m1, m2)
    cv.imshow("logic_and", dst_and)
    dst_or = cv.bitwise_or(m1, m2)
    cv.imshow("logic_or", dst_or)
    image = cv.imread("D:/vcprojects/images/test.jpg")
    cv.imshow("image", image)
    dst_not = cv.bitwise_not(image)
    cv.imshow("logic_not", dst_not)

def contrast_brightness_demo(image, c, b):#改变亮度、对比度
    h, w, ch = image.shape
    blank = np.zeros([h, w, ch], image.dtype)
    dst = cv.addWeighted(image, c, blank, 1-c, b)
    #参数分别为:图1,图1的权重,图2,图2的权重,权重和
    
    cv.imshow("con-bri-demo", dst)

print("--------- Hello Python ---------")
src1 = cv.imread("D:/vcprojects/images/LinuxLogo.jpg")
src2 = cv.imread("D:/vcprojects/images/WindowsLogo.jpg")
cv.imshow("image1", src1)
cv.imshow("image2", src2)
logic_demo(src1, src2)

src = cv.imread("D:/vcprojects/images/lena.png")
cv.imshow("image3", src)
contrast_brightness_demo(src, 1.5, 0)

cv.waitKey(0)

cv.destroyAllWindows()

8 ROI与泛洪填充

import cv2 as cv
import numpy as np


def fill_color_demo(image):
    copyImg = image.copy()
    h, w = image.shape[:2]
    mask = np.zeros([h+2, w+2], np.uint8)
    cv.floodFill(copyImg, mask, (30, 30), (0, 255, 255), (100, 100, 100), (50, 50, 50), cv.FLOODFILL_FIXED_RANGE)
    #参数分别为输入图像、mask掩膜、填充起始点、填充颜色、填充颜色低值、填充颜色高值
    cv.imshow("fill_color_demo", copyImg)

def fill_binary():
    image = np.zeros([400, 400, 3], np.uint8)
    image[100:300, 100:300, : ] = 255
    cv.imshow("fill_binary", image)

    mask = np.ones([402, 402, 1], np.uint8)
    mask[101:301, 101:301] = 0
    cv.floodFill(image, mask, (200, 200), (100, 2, 255), cv.FLOODFILL_MASK_ONLY)
    cv.imshow("filled binary", image)


print("--------- Hello Python ---------")
src = cv.imread("D:/vcprojects/images/demo.png")
cv.namedWindow("input image", cv.WINDOW_AUTOSIZE)
cv.imshow("input image", src)
src1 = src.copy()

face = src1[50:250, 100:300]
gray = cv.cvtColor(face, cv.COLOR_BGR2GRAY)
backface = cv.cvtColor(gray, cv.COLOR_GRAY2BGR)
src1[50:250, 100:300] = backface
cv.imshow("face", src1)

fill_color_demo(src)
fill_binary()

cv.waitKey(0)
cv.destroyAllWindows()

Python+OpenCV3.3图像处理视频教程 贾志刚 代码笔记1_第4张图片

9 模糊操作

import cv2 as cv
import numpy as np

def junzhi_blur_demo(image):
    dst = cv.blur(image, (5, 5))
    cv.imshow("junzhi_blur", dst)

def median_blur_demo(image):#去椒盐噪声
    dst = cv.medianBlur(image, 5)
    cv.imshow("median_blur", dst)

def custom_blur_demo(image):#自定义模糊
    kernel1 = np.ones([5, 5], np.float32)/25
    kernel2 = np.array([[0, -1, 0],[-1, 5, -1],[0, -1, 0]], np.float32)#锐化算子,和为1
    dst1 = cv.filter2D(image, -1, kernel=kernel1)
    cv.imshow("custom_blur1", dst1)

    dst2 = cv.filter2D(image, -1, kernel=kernel2)
    cv.imshow("custom_blur2", dst2)


print("--------- Hello Python ---------")
src = cv.imread("D:/vcprojects/images/demo.png")
cv.namedWindow("input image", cv.WINDOW_AUTOSIZE)
cv.imshow("input image", src)

junzhi_blur_demo(src)
median_blur_demo(src)
custom_blur_demo(src)
cv.waitKey(0)

cv.destroyAllWindows()

10 高斯模糊

import cv2 as cv
import numpy as np

def clamp(pv):
    if pv > 255:
        return 255
    if pv < 0:
        return 0
    else:
        return pv

def gaussian_noise(image):
    h, w, c = image.shape
    for row in range(h):
        for col in range(w):
            s = np.random.normal(0, 20, 3)
            b = image[row, col, 0]  # blue
            g = image[row, col, 1]  # green
            r = image[row, col, 2]  # red
            image[row, col, 0] = clamp(b + s[0])
            image[row, col, 1] = clamp(g + s[1])
            image[row, col, 2] = clamp(r + s[2])
    cv.imshow("gaussian_noise image", image)


print("--------- Hello Python ---------")
src = cv.imread("D:/vcprojects/images/example.png")
cv.namedWindow("input image", cv.WINDOW_AUTOSIZE)
cv.imshow("input image", src)

t1 = cv.getTickCount()
gaussian_noise(src)
t2 = cv.getTickCount()
time = (t2 - t1)/cv.getTickFrequency()
print("time consume : %s"%(time))

dst = cv.GaussianBlur(src, (0, 0), 15)
cv.imshow("Gaussian Blur", dst)

cv.waitKey(0)
cv.destroyAllWindows()

time consume : 1.758002

你可能感兴趣的:(opencv,python,贾志刚)