利用python实现数字图像的卷积
import cv2
import numpy as np
import math
import os
import pandas as pd
from tqdm import tqdm
image = cv2.imread("peng.png")
def rgb2gray(image):
h = image.shape[0]
w = image.shape[1]
grayimage = np.zeros((h,w),np.uint8)
for i in tqdm(range(h)):
for j in range(w):
grayimage [i,j] = 0.144*image[i,j,0]+0.587*image[i,j,1]+0.299*image[i,j,2]
return grayimage
grayimage = rgb2gray(image)
print("显示灰度图")
cv2.imshow("grayimage",grayimage)
conv_kernel = np.array([[ -1,-1, 0],
[ -1, 0, 1],
[ 0, 1, 1]])
def matrix(image,conv_ker):
res = (image * conv_ker).sum()
if (res < 0):
res = 0
elif res > 255:
res = 255
return res
def conv_operation(image):
conv_kernel_heigh = conv_kernel.shape[0]
conv_kernel_width = conv_kernel.shape[1]
conv_heigh = grayimage.shape[0] - conv_kernel.shape[0] + 1
conv_width = grayimage.shape[1] - conv_kernel.shape[1] + 1
conv_ret = np.zeros((conv_heigh, conv_width), np.uint8)
for i in tqdm(range(conv_heigh)):
for j in range(conv_width):
conv_ret[i,j] = matrix(image[i:(i + conv_kernel_heigh),j:(j + conv_kernel_width) ],conv_kernel)
return conv_ret
conv_ret = conv_operation(grayimage)
cv2.imshow("手写卷积运算",conv_ret)
cv2.waitKey()
效果图
