2017-10-01 64 views
1

我試圖手動實現sobel算子。使用filter2D(OpenCV)做Sobel算子時,平方會引入很多噪音

出於某種原因,操作員的水平和垂直分量似乎有良好的結果,但組合圖像有很多噪音。

我注意到當我做了像(imgv ** 2)** 0.5之類的東西時,即使理想情況下也會引入大量噪音,但我應該再次獲得大致相同的圖像。

有人知道這裏發生了什麼嗎?我是否應該以不同的方式組合圖像?

這裏是我的代碼在Python:

import cv2 
import numpy as np 

sobelX = np.array([[1,0,-1],[2,0,-2],[1,0,-1]]) 
sobelY = sobelX.T 

imgoriginal = cv2.imread("building.bmp") 

imgv = cv2.filter2D(imgoriginal, -1, sobelY) 
imgh = cv2.filter2D(imgoriginal, -1, sobelX) 
imgboth = (imgv**2 + img**2)**0.5 

這是輸出:

enter image description here

回答

3

更新:一個更好方法。

#!/usr/bin/python3 
# 2017.12.22 21:48:22 CST 

import cv2 
import numpy as np 

## parameters 
sobelX = np.array([[1,0,-1],[2,0,-2],[1,0,-1]]) 
sobelY = sobelX.T 
ddepth = cv2.CV_16S 

## calc gx and gy 
#img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 
img = cv2.GaussianBlur(img, (3,3), 0) 
gx = cv2.filter2D(img, ddepth, sobelX) 
gy = cv2.filter2D(img, ddepth, sobelY) 

## calc gridxy 
gxabs = cv2.convertScaleAbs(gx) 
gyabs = cv2.convertScaleAbs(gy) 
grad = cv2.addWeighted(gxabs, 0.5, gyabs, 0.5, 0) 

cv2.imwrite("result.png", grad) 

enter image description here


原來的答覆:

是的,它在numpy的OpenCV的圖像做數學運算時一直困擾着我。圖像數據類型默認爲np.uint8。所以,當溢出/下溢做數學運算的時候,如果你不改變percision

試試這個:

import cv2 
import numpy as np 

sobelX = np.array([[1,0,-1],[2,0,-2],[1,0,-1]]) 
sobelY = sobelX.T 

img = cv2.imread("cat.png") 

## Change the color space 
#img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 

imgv = cv2.filter2D(img, -1, sobelY) 
imgh = cv2.filter2D(img, -1, sobelX) 

## Change the percision first, then do math operation 
imghv = (np.float32(imgv)**2 + np.float32(img)**2)**0.5 
#imghv = (np.float32(imgv)**2 + np.float32(img)**2)**0.5 

## Normalize and change the percision 
## Use cv2.convertScaleAbs() to convert value into the right range [0, 255] 
imghv = imghv/imghv.max()*255 
imghv = cv2.convertScaleAbs(imghv) 

## Display 
res = np.hstack((imgh, imgv, imghv)) 
cv2.imshow("Sobel", res) 
cv2.waitKey() 
cv2.destroyAllWindows() 

Colorful Sobel

Grayscale Sobel