我试图理解我在 Rosettacode.org 上找到的 Python 中 Canny 运算符的这种实现,但不明白它是如何计算 thetaQ 的。为什么它在这个公式中使用 5 以及它如何量化方向?有人可以帮我吗?
#!/bin/python
import numpy as np
from scipy.ndimage.filters import convolve, gaussian_filter
from scipy.misc import imread, imshow
def CannyEdgeDetector(im, blur = 1, highThreshold = 91, lowThreshold = 31):
im = np.array(im, dtype=float) #Convert to float to prevent clipping values
#Gaussian blur to reduce noise
im2 = gaussian_filter(im, blur)
#Use sobel filters to get horizontal and vertical gradients
im3h = convolve(im2,[[-1,0,1],[-2,0,2],[-1,0,1]])
im3v = convolve(im2,[[1,2,1],[0,0,0],[-1,-2,-1]])
#Get gradient and direction
grad = np.power(np.power(im3h, 2.0) + np.power(im3v, 2.0), 0.5)
theta = np.arctan2(im3v, im3h)
thetaQ = (np.round(theta * (5.0 / np.pi)) + 5) % 5 #Quantize direction
#Non-maximum suppression
gradSup = grad.copy()
for r in range(im.shape[0]):
for c in range(im.shape[1]):
#Suppress pixels at the image edge
if r == 0 or r == im.shape[0]-1 or c == 0 or c == im.shape[1] - 1:
gradSup[r, c] = 0
continue
tq = thetaQ[r, c] % 4
if tq == 0: #0 is E-W (horizontal)
if grad[r, c] <= grad[r, c-1] or grad[r, c] <= grad[r, c+1]:
gradSup[r, c] = 0
if tq == 1: #1 is NE-SW
if grad[r, c] <= grad[r-1, c+1] or grad[r, c] <= grad[r+1, c-1]:
gradSup[r, c] = 0
if tq == 2: #2 is N-S (vertical)
if grad[r, c] <= grad[r-1, c] or grad[r, c] <= grad[r+1, c]:
gradSup[r, c] = 0
if tq == 3: #3 is NW-SE
if grad[r, c] <= grad[r-1, c-1] or grad[r, c] <= grad[r+1, c+1]:
gradSup[r, c] = 0
.........