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

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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值