學習記錄: openCV 圖像邊緣檢測
一. openCV 調用API Canny 實現邊緣檢測
''' Canny邊緣檢測步驟 1. 獲取圖像信息 2. 圖像灰度處理 3. 高斯濾波 4. Canny邊緣檢測處理 ''' import cv2 img = cv2.imread('test.jpg', -1) height, width, deep = img.shape gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #灰度處理 imgG = cv2.GaussianBlur(gray, (3,3), 0) # 高斯濾波 dst = cv2.Canny(img, 50, 50) # Canny 邊緣檢測 cv2.imshow('src', img) cv2.imshow('dst', dst) cv2.waitKey(0)
二. python與Sobel算子實現邊緣檢測
'''
python與sobel算子實現邊緣檢測
步驟:
1. sobel 算子模板
2. 圖像卷積
3. 閾值判決
1.sobel算子模板:
y方向
1 2 1
0 0 0
-1 -2 -1
x方向
1 0 -1
2 0 -2
1 0 -1
2. 圖像卷積:
矩陣對應元素乘積之和
3. 浮值與閾值比較:
sqrt(Gx*Gx+Gy*Gy) # gx 爲水平方向的梯度, gy爲垂直反向的梯度
'''
import cv2
import numpy as np
import math
img = cv2.imread('test.jpg', -1)
height, width, deep = img.shape
dst = np.zeros((height,width,1),np.uint8)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
for i in range(height-2):
for j in range(width-2):
gy = gray[i,j]*1 + gray[i,j+1]*2 + gray[i,j+2]*1 - gray[i+2, j]*1 - gray[i+2, j+1]*2 - gray[i+2, j+2]*1
gx = gray[i,j]*1 + gray[i+1,j]*2 + gray[i+2,j]*1 - gray[i,j+2]*1 - gray[i+1, j+2]*2 - gray[i+2,j+2]*1
grad = math.sqrt(gx*gx + gy*gy)
if grad > 50:
dst[i, j] = 255
else:
dst[i, j] = 0
cv2.imshow('src', img)
cv2.imshow('dst', dst)
cv2.waitKey()