Try   HackMD

利用Lapacian進行邊緣偵測

邊緣偵測中提到,可以利用OpenCV對影像做出邊緣偵測的運算,以下利用python進行簡單的影像運算。

使用影像

這次一樣使用經典圖片,萊娜圖。

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

範例

  1. 首先先匯入相關函式

    import cv2
    ​import numpy as np
    ​import argparse
    

    其中,argparse是一個內建模組主要用來完成文字命令列的一些操作,這裡就不多做說明。

  2. 利用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)
    
  3. 讀取圖片並完成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)
    
  4. 輸出圖片

    ​cv2.imwrite('.\\edge_lenna.png',lap)
    
Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →
輸出結果