[小脚本] 可视化图片梯度方向

此生再无相见时 提交于 2019-12-26 10:08:32

大致就是算出梯度, 然后利用直线的变换表示梯度的方向

img = cv.imread("tempdir/DoG.png")
#img = cv.imread("tempdir/robot.jpg")
gray_blur = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# 3x3 sobel filters for edge detection
sobel_x = np.array([[ -1, 0, 1], 
                   [ -2, 0, 2], 
                   [ -1, 0, 1]])


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


# Filter the blurred grayscale images using filter2D
filtered_blurred_x = cv2.filter2D(gray_blur, cv2.CV_32F, sobel_x)
filtered_blurred_y = cv2.filter2D(gray_blur, cv2.CV_32F, sobel_y)

# Compute the orientation of the image
orien = cv2.phase(np.array(filtered_blurred_x, np.float32), np.array(filtered_blurred_y, dtype=np.float32), angleInDegrees=True)

yids, xids = np.where( gray_blur > 200 ) 
yids = yids[::20]
xids = xids[::20]
n = len(yids)

orien = orien[ yids, xids ]
orien *= np.pi / 180

Rs=np.zeros( (n , 4), dtype=np.float32 )

Rs[:, 0] = Rs[:, 3]  = np.cos(orien)
Rs[:, 1] = Rs[:, 2]  = np.sin(orien)
Rs[:, 1] *= -1

Rs=Rs.reshape(-1, 2, 2)

lines = np.zeros( (n , 4), dtype=np.float32 )
#lines.fill(0)
lines[:, 3] = 15
lines=lines.reshape(-1, 2, 2)
lines = np.einsum("ijk, ilk -> ijl" , lines, Rs )
lines[:, :, 0] += xids[:, None]
lines[:, :, 1] += yids[:, None]
lines = lines.reshape(-1, 4).astype(np.int32)

lineThickness = 1
for e in lines:
    cv2.line(img, (e[0], e[1]), (e[2], e[3]), (0,255,0), lineThickness)

showimg( img )

在这里插入图片描述
在这里插入图片描述
具体也不知道对不对, 一方面是不知道坐标系是怎样的. 感觉比较有意思记录一下.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!