我想检测图像中仅相对于原点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)
这是卷积前的图像:
这是卷积后的图像:
那么你在问题中提供的代码我们获得了除了我们想要获得的代码之外的代码。所以我们可以把它和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)
然后我们需要删除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)
然后使用原始图像的cv2.bitwise_and
和获得的阈值的cv2.bitwise_not
,我们获得了我们的线。
res = cv2.bitwise_and(img, cv2.bitwise_not(thresh))
我们获得了线,但我们需要删除中间的圆。为此我们在原始图像上使用cv2.erode
只获得中间圆,阈值然后再次使用cv2.bitwise_and
和cv2.bitwise_not
将其从res中移除。
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()