我有這張用于樹木線作物的影像。我需要找到裁剪對齊的大體方向。我試圖獲得影像的霍夫線,然后找到角度分布的模式。
可以很容易地看到主光束。您可以通過迭代多條具有遞增角度的線來提取它的角度,并對每條線上的幅度值求和,如下圖所示:

這是針對線的角度(以弧度為單位)繪制的每條線的幅度和:

基于此,您只需要找到使計算總和最大化的角度。
這是結果代碼:
def computeAngle(arr):
# Naive inefficient algorithm
n, m = arr.shape
yCenter, xCenter = (n-1, m//2-1)
lineLen = m//2-2
sMax = 0.0
bestAngle = np.nan
for angle in np.arange(0, math.pi, math.pi/300):
i = np.arange(lineLen)
y, x = (np.sin(angle) * i 0.5).astype(np.int_), (np.cos(angle) * i 0.5).astype(np.int_)
s = np.sum(arr[yCenter-y, xCenter x])
if s > sMax:
bestAngle = angle
sMax = s
return bestAngle
# Load the image in gray
img = cv2.imread('lines.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
# Apply some filters
gauss = cv2.GaussianBlur(gray, (3,3), 3)
gscale = cv2.Canny(gauss, 80, 140)
# Compute the 2D FFT of real values
freqs = np.fft.rfft2(gscale)
# Shift the frequencies (centering) and select the low frequencies
upperPart = freqs[:freqs.shape[0]//4,:freqs.shape[1]//2]
lowerPart = freqs[-freqs.shape[0]//4:,:freqs.shape[1]//2]
filteredFreqs = np.vstack((lowerPart, upperPart))
# Compute the magnitude spectrum
magnitude = np.log(np.abs(filteredFreqs))
# Correct the angle
magnitude = np.rot90(magnitude).copy()
# Find the major angle
bestAngle = computeAngle(magnitude)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/401965.html
上一篇:Python陣列的切片
