計算機視覺之影象處理(4)【梯度與邊緣檢測】
import
cv2
import
matplotlib。pyplot
as
plt
import
numpy
as
np
#比較soble、scharr、laplacian運算元的梯度差異
#dst = cv2。Sobel(src, ddepth, dx, dy, ksize)
# ddepth:影象的深度
# dx和dy分別表示水平和豎直方向
# ksize是Sobel運算元的大小
#白到黑是正數,黑到白就是負數了,所有的負數會被截斷成0,所以要取絕對值
def
cv_operator
():
img
=
cv2
。
imread
(
‘。/img/lena。jpg’
,
cv2
。
IMREAD_GRAYSCALE
)
sobelx
=
cv2
。
Sobel
(
img
,
cv2
。
CV_64F
,
1
,
0
,
ksize
=
3
)
sobely
=
cv2
。
Sobel
(
img
,
cv2
。
CV_64F
,
0
,
1
,
ksize
=
3
)
sobelx
=
cv2
。
convertScaleAbs
(
sobelx
)
#右減左相減過程會出現負數 取絕對值防止截斷
sobely
=
cv2
。
convertScaleAbs
(
sobely
)
#左減右相減過程會出現負數 取絕對值防止截斷
sobelxy
=
cv2
。
addWeighted
(
sobelx
,
0。5
,
sobely
,
0。5
,
0
)
scharrx
=
cv2
。
Scharr
(
img
,
cv2
。
CV_64F
,
1
,
0
)
scharry
=
cv2
。
Scharr
(
img
,
cv2
。
CV_64F
,
0
,
1
)
scharrx
=
cv2
。
convertScaleAbs
(
scharrx
)
scharry
=
cv2
。
convertScaleAbs
(
scharry
)
scharrxy
=
cv2
。
addWeighted
(
scharrx
,
0。5
,
scharry
,
0。5
,
0
)
laplacian
=
cv2
。
Laplacian
(
img
,
cv2
。
CV_64F
)
laplacian
=
cv2
。
convertScaleAbs
(
laplacian
)
res
=
np
。
hstack
((
sobelxy
,
scharrxy
,
laplacian
))
cv2
。
imshow
(
“res”
,
res
)
cv2
。
waitKey
()
cv2
。
destroyAllWindows
()
#cv_operator()
#Canny邊緣檢測 minVal maxVal 梯度大於maxVal處理為邊界 梯度小於minVal不處理邊界
#梯度介於minVal和maxVal,若連有邊界(附近的點處理為邊界)處理為邊界
#minVal越小 畫面的細節捕捉的越豐富 maxVal亦如此
def
cv_canny
():
img
=
cv2
。
imread
(
“。/img/car。png”
,
cv2
。
IMREAD_GRAYSCALE
)
v1
=
cv2
。
Canny
(
img
,
150
,
100
)
v2
=
cv2
。
Canny
(
img
,
50
,
100
)
res
=
np
。
hstack
((
v1
,
v2
))
cv2
。
imshow
(
“res”
,
res
)
cv2
。
waitKey
()
cv2
。
destroyAllWindows
()
#cv_canny()