利用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,1]
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)
# opencv卷积运算
# res = cv2.filter2D(grayimage,-1,conv_kernel)
# cv2.imshow("opencv卷积运算",res)
cv2.waitKey()
效果图
来源:CSDN
作者:步步星愿
链接:https://blog.csdn.net/qq_41940950/article/details/103462252