在Python中计算图像中两条线之间的角度

时间:2017-09-22 04:54:39

标签: python image-processing

我有一张图片,我想计算这张图片中两条线之间的角度。让我们考虑一个非常简单的图像:

Two Lines

现在我想计算这张图片中两条线之间的角度。你知道我怎么能在python中做到这一点吗?

1 个答案:

答案 0 :(得分:2)

您可以尝试Hough变换。此变换允许您检测线,然后获取每条线的角度。 然后你可以使用这两个角度来计算两条线之间的角度,减去两者?

import numpy as np

from skimage.transform import (hough_line, hough_line_peaks,
                               probabilistic_hough_line)
from skimage.feature import canny
from skimage import data

from pylab import imread, imshow, gray, mean

import matplotlib.pyplot as plt
from matplotlib import cm

image = imread('bn2TV.jpg')
image = np.mean(image,axis=2)
image = (image < 128)*255

h, theta, d = hough_line(image)

fig, axes = plt.subplots(1, 3, figsize=(15, 6),
                         subplot_kw={'adjustable': 'box-forced'})
ax = axes.ravel()

ax[0].imshow(image, cmap=cm.gray)
ax[0].set_title('Input image')
ax[0].set_axis_off()
ax[1].imshow(np.log(1 + h),
             extent=[np.rad2deg(theta[-1]), np.rad2deg(theta[0]), d[-1], d[0]],
             cmap=cm.gray, aspect=1/1.5)
ax[1].set_title('Hough transform')
ax[1].set_xlabel('Angles (degrees)')
ax[1].set_ylabel('Distance (pixels)')
ax[1].axis('image')

ax[2].imshow(image, cmap=cm.gray)
for _, angle, dist in zip(*hough_line_peaks(h, theta, d)):
    y0 = (dist - 0 * np.cos(angle)) / np.sin(angle)
    y1 = (dist - image.shape[1] * np.cos(angle)) / np.sin(angle)
    ax[2].plot((0, image.shape[1]), (y0, y1), '-r')
ax[2].set_xlim((0, image.shape[1]))
ax[2].set_ylim((image.shape[0], 0))
ax[2].set_axis_off()
ax[2].set_title('Detected lines')

plt.tight_layout()
plt.show()

angle=[]
dist=[]
for _, a , d in zip(*hough_line_peaks(h, theta, d)):
    angle.append(a)
    dist.append(d)

angle = [a*180/np.pi for a in angle]
angle_reel = np.max(angle) - np.min(angle)

大部分代码来自此处:http://scikit-image.org/docs/dev/auto_examples/edges/plot_line_hough_transform.html

然后我们得到

enter image description here

其中28度角。似乎合理!