在邊緣偵測中提到,可以利用OpenCV對影像做出邊緣偵測的運算,以下利用python進行簡單的影像運算。
這次一樣使用經典圖片,萊娜圖。
首先先匯入相關函式
import cv2
import numpy as np
import argparse
其中,argparse
是一個內建模組主要用來完成文字命令列的一些操作,這裡就不多做說明。
利用def
先行撰寫一個顯示模組,主要讓不同的圖片均可輸入並顯示
def display(windowsName,img):
cv2.namedWindow(windowsName, cv2.WINDOW_NORMAL) #使視窗可調整,並命名
size = img.shape# 影像尺寸最佳化
h = size[0]
w = size[1]
while(True):
if w>800 or h>800:
w = int(w/2)
h = int(h/2)
else:
break
cv2.resizeWindow(windowsName,w,h)
cv2.imshow(windowsName,img)
cv2.waitKey(0)
讀取圖片並完成Laplacian
完成邊緣計算
ap = argparse.ArgumentParser()
ap.add_argument('-i',required= True,help='Path to the image')
args = vars(ap.parse_args())
image = cv2.imread(args['i'],flags=0)
imagename = args['i']
display(imagename,image)
lap = cv2.Laplacian(image, cv2.CV_64F)#將函數轉為浮點格式CV_64F
lap = np.uint8(np.absolute(lap))#取得絕對值後轉為8bit資訊
lap = abs(255-lap)
display('LAP',lap)
輸出圖片
cv2.imwrite('.\\edge_lenna.png',lap)
or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up