1. 程式人生 > >Python+OpenCV拉普拉斯影象銳化

Python+OpenCV拉普拉斯影象銳化

                   **Python實現基於OpenCV的拉普拉斯影象銳化**

研一學習數字影象處理(剛薩雷斯版),導師讓我用Python編寫基於拉普拉斯運算元的影象銳化,並且是在不直接呼叫OpenCV的情況下,由於現在還沒有學習銳化彩色影象,所以本部落格先聯絡銳化灰度圖。
Python程式碼如下:

import cv2 as cv
import numpy as np
rgb = cv.imread("D:/a.jpg")
weight=rgb.shape[0]
height=rgb.shape[1]
number=rgb.shape[2]
print("原影象大小:\n""weight: %d \nheight: %d \nnumber: %d" %(weight,height,number)) # 檢查影象大小
img=cv.resize(rgb,(int(weight/6),int(height/6)),interpolation=cv.INTER_CUBIC) # 將影象縮小為原來的六分之一倍
grayimg=np.zeros((img.shape[0],img.shape[1],1),np.uint8)
weight=int(weight/6)
height=int(height/6)
print("裁剪後圖像大小:\n""weight: %d \nheight: %d \nnumber: %d" %(weight,height,number))
for i in range(weight):
    for j in range(height):
        grayimg[i,j] = 0.299 * img[i, j, 0] + 0.587 * img[i, j, 1] + 0.114 * img[i, j, 2] # 將原圖片轉為灰度圖片
t1 = list([[0,1,0],
           [1,-4,1],
           [0,1,0]]) # 定義拉普拉斯濾波器
shp=grayimg*1 # 設定一個新的圖片變數,防止修改原圖片
shp=np.pad(grayimg,((1, 1), (1, 1),(0,0)),"constant",constant_values=0) # 為原圖片加一層邊緣
for i in range(1,weight-1):
    for j in range(1,height-1):
        shp[i,j]=abs(np.sum(shp[i:i+3,j:j+3]*t1)) # 對灰度圖進行銳化
cv.imshow('srcImage', img)
cv.imshow('grayImage', grayimg)
cv.imshow("Laplacian",grayimg+shp[1:shp.shape[0]-1,1:shp.shape[1]-1])
cv.waitKey(0)
cv.destroyAllWindow()

寫著玩,只想記錄自己在Python和影象處理的成長。