小刘总学人工智能之计算机视觉CV

    技术2022-07-10  94

    import cv2 import numpy as np import matplotlib.pyplot as plt %matplotlib inline cat_img = cv2.imread('cat.bmp') cat_img = cv2.cvtColor(cat_img, cv2.COLOR_BGR2RGB) plt.imshow(cat_img)

    高斯分布函数

    12𝜋𝛿2𝑒−((𝑥−𝑥0)2+(𝑦−𝑦0)2)2𝛿2

    kernel_size = 9 sigma = 1 def gassian_kernel(kernel_size, sigma): kernel = np.zeros((kernel_size, kernel_size), dtype=np.float) centre = kernel_size // 2 for i in range(kernel_size): for j in range(kernel_size): d = (i - centre)**2 + (j - centre)**2 kernel[i, j] = np.exp(-d/(2*sigma**2)) kernel /= (2 * np.pi * sigma**2) kernel /= kernel.sum() # 归一化 return kernel ​ kernel = gassian_kernel(kernel_size, sigma) kernel def convolution(img, kernel): img_h, img_w = img.shape[:2] bored = int(kernel.shape[0] / 2) new_img = np.zeros((img_h, img_w, 3), dtype=np.float) for c in range(3): for x in range(bored, img_w - bored): for y in range(bored, img_h - bored): new_img[y, x, c] = np.sum(kernel * img[y-bored:y+bored+1, x-bored:x+bored+1, c]) new_img = np.clip(new_img, 0, 255) new_img = new_img.astype(np.uint8) return new_img img = convolution(cat_img, kernel) print(img.shape) plt.imshow(img) def add_padding(img, kernel_size): p = kernel_size//2 black = [0, 0, 0] padding_img = cv2.copyMakeBorder(img, p, p, p, p, cv2.BORDER_CONSTANT, value=black ) return padding_img img = convolution(add_padding(cat_img, kernel_size), kernel) print(img.shape) plt.imshow(img)
    Processed: 0.015, SQL: 9