首页 > 解决方案 > 计算边缘像素的梯度线

问题描述

我想计算检测到的轮廓中某些像素的梯度线。检测到的轮廓示例是 检测到的轮廓图。为此,我首先使用以下代码计算图像梯度

img_sobelx = cv2.Sobel(grey_img,cv2.CV_16S,1,0,ksize=3)
img_sobely = cv2.Sobel(grey_img,cv2.CV_16S,0,1,ksize=3)
m = np.hypot(img_sobelx,img_sobelx)

然后我使用以下代码在轮廓中找到一些像素的渐变线注意:要检测轮廓我使用canny edge方法和连接组件

px,py =np.where(img > 0)   # img: is the example image (after detecting the contour)
# pick points from the curve
index = np.array(range(0,py.shape[0],int(py.shape[0]/10)))
for i in index[:-1]:
     #first line
     m1 = m[px[i],py[i]]    #slope
     b1 = py[i] - (m1*px[i]) # intercept
     for j in index[k:]:
          m2 = m[px[j],py[j]]
          b2 = py[j] - (m2*px[j])
          # intersection point
          if (m2-m1) == 0:
               continue
          xi = (b1-b2) / (m2-m1)
          yi = m1 * xi + b1
          start_point = (py[i],px[i])
          end_point = (int(yi),int(xi))
          img= cv2.line(img,start_point,end_point,(255,255,255),1)
          start_point = (py[j],px[j])
          end_point = (int(yi),int(xi))
          img= cv2.line(img,start_point,end_point,(255,255,255),1)

上面代码的输出是 输出:渐变线

结果似乎不正确。你能帮我找到正确的方法吗?谢谢

标签: pythonopencvimage-processingcomputer-vision

解决方案


您需要使用img_sobelximg_sobely作为向量的两个分量。斜边不是这个向量的斜率,而是幅度。幅度表示梯度有多强,而不是它的方向。

如果您有一个点(px[i],py[i]),那么该点(px[i]+img_sobelx[i],py[i]+img_sobely[i])就是您要查找的线上的第二个点。


推荐阅读