天天看點

基于Python的圖像拉普拉斯變化/圖像銳化實作

部落客本學習選修數字圖像處理課程,用到的教材是岡薩雷斯的《數字圖像處理》,作業要求完成圖像拉普拉斯變化,雖然用Matalb比較容易就能實作,但還是想嘗試用python完成。

Python+OpenCV拉普拉斯圖像銳化這一篇部落格是我實作代碼的基礎,但部落客給出的代碼有一部分錯不,到後期無法實作拉普拉斯變化,而且灰階圖像比較繁瑣,是以做了一部分的改進。

原理參考

拉普拉斯濾波實作圖像增強

代碼實作

# -*- coding: utf-8 -*-
"""
Created on Mon Mar 18 20:47:35 2019

@author: hy
"""

import numpy as np
import cv2
from PIL import Image
from matplotlib import pyplot as plt


ori = Image.open(r'C:\Users\hy\Desktop\iml\leina.jpg')
ori_gray = ori.convert('L')

ori = np.array(ori)
ori_gray = np.array(ori_gray )
weight = ori.shape[0]
height = ori.shape[1]


ori_pad = np.pad(ori_gray,((1,1),(1,1)),'edge')


t1 = np.array([[0,1,0],[1,-4,1],[0,1,0]])
img = np.zeros((weight,height))
for i in range(weight-2):
    for j in range(height-2):
        img[i,j]=np.sum(ori_pad[i:i+3,j:j+3]*t1)
        if img[i,j] < 0:
            img[i,j] = 0

img_sharp = np.zeros((weight,height))
img_sharp = ori_gray - img
           

其中阻擋我很久的部分在于這裡:

img = np.zeros((weight,height))
for i in range(weight-2):
    for j in range(height-2):
        img[i,j]=np.sum(ori_pad[i:i+3,j:j+3]*t1)
        if img[i,j] < 0:
            img[i,j] = 0

           

參考部落格中用 img = np.zeros((weight,height),np.uint8),導緻最後計算出來的負數全部轉化為8位形式,而實際上拉普拉斯算子中,負數像元全部轉為0。

代碼實作

基于Python的圖像拉普拉斯變化/圖像銳化實作

原始圖檔

基于Python的圖像拉普拉斯變化/圖像銳化實作

灰階後的雷娜

基于Python的圖像拉普拉斯變化/圖像銳化實作

拉普拉斯變化後的雷娜

基于Python的圖像拉普拉斯變化/圖像銳化實作

銳化後的雷娜