f-8
import numpy as np
from PIL import Image
import math
def corr2D(image:np.array, kernel:np.array):
# 翻转180度
kernel = kernel[::-1,::-1]
# kernel和图片的尺寸
kernel_size_w = kernel.shape[0]
kernel_size_h = kernel.shape[1]
image_w = image.shape[0]
image_h = image.shape[1]
# 0填充padding
padding_w = padding_h = int(kernel_size_w/2)
padding_image = np.pad(image,((1,padding_w),(1,padding_h)))
# 生成新的array
new_image_array = np.zeros((image_w,image_h))
for i in range(image_w):
for j in range(image_h):
# 卷积
new_image_array[i][j] = (np.multiply(padding_image[i:i+kernel_size_w,j:j+kernel_size_h],kernel)).sum()
return new_image_array.clip(0,255).astype("uint8")
def corr2D_xy(image:np.array, kernel_x:np.array,kernel_y:np.array):
# 翻转180度
kernel_x = kernel_x[::-1,::-1]
kernel_y = kernel_y[::-1,::-1]
# kernel和图片的尺寸
kernel_size_w = kernel_x.shape[0]
kernel_size_h = kernel_x.shape[1]
image_w = image.shape[0]
image_h = image.shape[1]
# 0填充padding
padding_w = padding_h = int(kernel_size_w/2)
padding_image = np.pad(image,((1,padding_w),(1,padding_h)))
# 生成新的array
new_image = np.zeros((image_w,image_h))
for i in range(image_w):
for j in range(image_h):
# 水平和垂直联合梯度
mx = (np.multiply(padding_image[i:i+kernel_size_w,j:j+kernel_size_h],kernel_x)).sum()
my = (np.multiply(padding_image[i:i+kernel_size_w,j:j+kernel_size_h],kernel_y)).sum()
new_image[i][j] = math.sqrt(mx*mx+my*my)
return new_image.clip(0,255).astype("uint8")
def pic_cor(pic,kernel,output="./output.png"):
# 卷积核
origin = Image.open(pic)
# 图片转array
image_array = np.array(origin)
# 对三个通道分别卷积
for tunnel in range(0,3):
image_array[:, :, tunnel] = corr2D(image_array[:, :, tunnel],kernel)
# 保存图片
merged=Image.fromarray(image_array)
merged.save(output)
def pic_cor_xy(pic,kernel_x,kernel_y,output="./output.png"):
origin = Image.open(pic)
# 图片转array
image_array = np.array(origin)
# 对三个通道分别卷积
for tunnel in range(0,3):
image_array[:, :, tunnel] = corr2D_xy(image_array[:, :, tunnel],kernel_x,kernel_y)
# 保存图片
merged=Image.fromarray(image_array)
merged.save(output)
pic= "./apple.png"
kernel_laplacian = np.array([[-1,-1,-1],[-1,8,-1],[-1,-1,-1]])
kernel_sobel_x = np.array([[-1,0,1],[-2,0,2],[-1,0,1]])
kernel_sobel_y = np.array([[-1,-2,-1],[0,0,0],[1,2,1]])
pic_cor(pic,kernel_laplacian,output="./laplacian.png")
pic_cor_xy(pic,kernel_sobel_x,kernel_sobel_y,output="./xy.png")