在图像中仅显示45度线

时间:2019-02-16 12:39:02

标签: python opencv convolution edge-detection

我想检测图像中仅相对于原点成45度角的线。我只需要使用3x3卷积即可。我已经解决了所有这样的问题,即所有45度角的线条都被删除了,其他所有内容都保持不变(与我想要的相反)。非常感谢从这里到我最终目标的任何帮助。

import cv2
import numpy as np
import matplotlib.pyplot as plt


img = cv2.imread('Lines.png')

plt.imshow(img, cmap='gray')
plt.show()

kernel = np.array([[0, -1, 0],
                   [1, 0, 1],
                   [0, -1, 0]])

dst = cv2.filter2D(img, -1, kernel)
cv2.imwrite("filtered.png", dst)

这是卷积之前的图像:

enter image description here

这是卷积之后的图像:

This is what is happening right now

2 个答案:

答案 0 :(得分:2)

我使用的过滤器是:

kernel = np.array([[0, -25, 1],
                   [-25, 5, -25],
                   [1, -25, 0]])

结果是:

enter image description here

这不是完美的,但希望对您有所帮助。

答案 1 :(得分:2)

根据您在问题中提供的代码,我们获得了除要获得的行之外的行。因此,我们可以接受它并dilate来填充行。

img = cv2.imread('lines.png')
kernel = np.array([[0, -1, 0],
                   [1, 0, 1],
                   [0, -1, 0]])

dst = cv2.filter2D(img, -1, kernel)
kernel = np.ones((5, 5), np.uint8)
dilated = cv2.dilate(dst, kernel, iterations = 1)

dilated lines

然后,我们需要以45度的角度去除线条上方的点,因此我们为此使用morphological opening并对图像进行阈值处理,以将所有线条转换为像素值= 255。

kernel = np.ones((7, 7), np.uint8)
opening = cv2.morphologyEx(dilated, cv2.MORPH_OPEN, kernel)
_,thresh = cv2.threshold(opening,10,255,cv2.THRESH_BINARY)

filled and thresholded

然后使用原始图像的cv2.bitwise_and和阈值的cv2.bitwise_not获得线。

res = cv2.bitwise_and(img, cv2.bitwise_not(thresh))

intermediate result

我们获得了线条,但是我们需要删除中间的圆圈。为此,我们在原始图像上使用cv2.erode仅获得中间圆,对其设置阈值,然后再次使用cv2.bitwise_andcv2.bitwise_not将其从分辨率中删除。

kernel = np.ones((7, 7), np.uint8)
other = cv2.erode(img, kernel, iterations = 1)
_,thresh = cv2.threshold(other,10,255,cv2.THRESH_BINARY)
result = cv2.bitwise_and(res, cv2.bitwise_not(thresh))
cv2.imshow("Image", result)
cv2.waitKey(0)
cv2.destroyAllWindows()

Final result