三、数字图像的卷积计算python实现

╄→尐↘猪︶ㄣ 提交于 2019-12-15 06:18:39

利用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()

效果图

在这里插入图片描述

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!