python - 计算边缘像素的梯度线
问题描述
我想计算检测到的轮廓中某些像素的梯度线。检测到的轮廓示例是 检测到的轮廓图。为此,我首先使用以下代码计算图像梯度
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)
上面代码的输出是 输出:渐变线
结果似乎不正确。你能帮我找到正确的方法吗?谢谢
解决方案
您需要使用img_sobelx
和img_sobely
作为向量的两个分量。斜边不是这个向量的斜率,而是幅度。幅度表示梯度有多强,而不是它的方向。
如果您有一个点(px[i],py[i])
,那么该点(px[i]+img_sobelx[i],py[i]+img_sobely[i])
就是您要查找的线上的第二个点。
推荐阅读
- javascript - 对象对象到对象数组 JavaScript
- schema.org - 获取结构化架构中的评分值
- r - 更改 ggplot2 中的颜色背景 - R 按 x 轴上的特定日期
- arrays - System Verilog:用于位零件索引的线输入
- sql-server - SSRS 如何在 SSRS 中制作这个(楼梯视图)
- android - 如何在颤振项目上手动运行 gradle build
- c# - 使用文本/纯文本时不受支持的媒体类型
- javascript - 无法使用 html 提供 javascript 文件 - node.js
- javascript - 使用javascript将内容添加到html中的元素
- java - Quarkus 和 Jackson 奇怪的龙目岛行为