python 霍夫直线变换_Python数字图像处理之霍夫线变换实现详解

Python数字图像处理之霍夫线变换实现详解

来源:中文源码网    浏览: 次    日期:2018年9月2日

【下载文档:  Python数字图像处理之霍夫线变换实现详解.txt 】

(友情提示:右键点上行txt文档名->目标另存为)

Python数字图像处理之霍夫线变换实现详解 在图片处理中,霍夫变换主要是用来检测图片中的几何形状,包括直线、圆、椭圆等。

在skimage中,霍夫变换是放在tranform模块内,本篇主要讲解霍夫线变换。

对于平面中的一条直线,在笛卡尔坐标系中,可用y=mx+b来表示,其中m为斜率,b为截距。但是如果直线是一条垂直线,则m为无穷大,所有通常我们在另一坐标系中表示直线,即极坐标系下的r=xcos(theta)+ysin(theta)。即可用(r,theta)来表示一条直线。其中r为该直线到原点的距离,theta为该直线的垂线与x轴的夹角。如下图所示。对于一个给定的点(x0,y0), 我们在极坐标下绘出所有通过它的直线(r,theta),将得到一条正弦曲线。如果将图片中的所有非0点的正弦曲线都绘制出来,则会存在一些交点。所有经过这个交点的正弦曲线,说明都拥有同样的(r,theta), 意味着这些点在一条直线上。发上图所示,三个点(对应图中的三条正弦曲线)在一条直线上,因为这三个曲线交于一点,具有相同的(r, theta)。霍夫线变换就是利用这种方法来寻找图中的直线。

函数:skimage.transform.hough_line(img)

返回三个值:

h: 霍夫变换累积器

theta: 点与x轴的夹角集合,一般为0-179度

distance: 点到原点的距离,即上面的所说的r.

例:

import skimage.transform as st

import numpy as np

import matplotlib.pyplot as plt

# 构建测试图片

image = np.zeros((100, 100)) #背景图

idx = np.arange(25, 75) #25-74序列

image[idx[::-1], idx] = 255 # 线条\

image[idx, idx] = 255 # 线条/

# hough线变换

h, theta, d = st.hough_line(image)

#生成一个一行两列的窗口(可显示两张图片).

fig, (ax0, ax1) = plt.subplots(1, 2, figsize=(8, 6))

plt.tight_layout()

#显示原始图片

ax0.imshow(image, plt.cm.gray)

ax0.set_title('Input image')

ax0.set_axis_off()

#显示hough变换所得数据

ax1.imshow(np.log(1 + h))

ax1.set_title('Hough transform')

ax1.set_xlabel('Angles (degrees)')

ax1.set_ylabel('Distance (pixels)')

ax1.axis('image')

从右边那张图可以看出,有两个交点,说明原图像中有两条直线。

如果我们要把图中的两条直线绘制出来,则需要用到另外一个函数:

skimage.transform.hough_line_peaks(hspace, angles, dists)

用这个函数可以取出峰值点,即交点,也即原图中的直线。

返回的参数与输入的参数一样。我们修改一下上边的程序,在原图中将两直线绘制出来。

import skimage.transform as st

import numpy as np

import matplotlib.pyplot as plt

# 构建测试图片

image = np.zeros((100, 100)) #背景图

idx = np.arange(25, 75) #25-74序列

image[idx[::-1], idx] = 255 # 线条\

image[idx, idx] = 255 # 线条/

# hough线变换

h, theta, d = st.hough_line(image)

#生成一个一行三列的窗口(可显示三张图片).

fig, (ax0, ax1,ax2) = plt.subplots(1, 3, figsize=(8, 6))

plt.tight_layout()

#显示原始图片

ax0.imshow(image, plt.cm.gray)

ax0.set_title('Input image')

ax0.set_axis_off()

#显示hough变换所得数据

ax1.imshow(np.log(1 + h))

ax1.set_title('Hough transform')

ax1.set_xlabel('Angles (degrees)')

ax1.set_ylabel('Distance (pixels)')

ax1.axis('image')

#显示检测出的线条

ax2.imshow(image, plt.cm.gray)

row1, col1 = image.shape

for _, angle, dist in zip(*st.hough_line_peaks(h, theta, d)):

y0 = (dist - 0 * np.cos(angle)) / np.sin(angle)

y1 = (dist - col1 * np.cos(angle)) / np.sin(angle)

ax2.plot((0, col1), (y0, y1), '-r')

ax2.axis((0, col1, row1, 0))

ax2.set_title('Detected lines')

ax2.set_axis_off()

注意,绘制线条的时候,要从极坐标转换为笛卡尔坐标,公式为:skimage还提供了另外一个检测直线的霍夫变换函数,概率霍夫线变换:

skimage.transform.probabilistic_hough_line(img, threshold=10, line_length=5,line_gap=3)

参数:

img: 待检测的图像。

threshold: 阈值,可先项,默认为10

line_length: 检测的最短线条长度,默认为50

line_gap: 线条间的最大间隙。增大这个值可以合并破碎的线条。默认为10

返回:

lines: 线条列表, 格式如((x0, y0), (x1, y0)),标明开始点和结束点。

下面,我们用canny算子提取边缘,然后检测哪些边缘是直线?

import skimage.transform as st

import matplotlib.pyplot as plt

from skimage import data,feature

#使用Probabilistic Hough Transform.

image = data.camera()

edges = feature.canny(image, sigma=2, low_threshold=1, high_threshold=25)

lines = st.probabilistic_hough_line(edges, threshold=10, line_length=5,line_gap=3)

# 创建显示窗口.

fig, (ax0, ax1, ax2) = plt.subplots(1, 3, figsize=(16, 6))

plt.tight_layout()

#显示原图像

ax0.imshow(image, plt.cm.gray)

ax0.set_title('Input image')

ax0.set_axis_off()

#显示canny边缘

ax1.imshow(edges, plt.cm.gray)

ax1.set_title('Canny edges')

ax1.set_axis_off()

#用plot绘制出所有的直线

ax2.imshow(edges * 0)

for line in lines:

p0, p1 = line

ax2.plot((p0[0], p1[0]), (p0[1], p1[1]))

row2, col2 = image.shape

ax2.axis((0, col2, row2, 0))

ax2.set_title('Probabilistic Hough')

ax2.set_axis_off()

plt.show()

总结

以上就是本文关于Python数字图像处理之霍夫线变换实现详解的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

亲,试试微信扫码分享本页! *^_^*

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
霍夫变换Hough Transform)是一种图像处理算法,用于检测在二维平面上的物体形状,特别是直线或圆形。 在图像处理中,霍夫变换主要用于直线检测。直线可以表示为 y = mx + b 的形式,其中 m 是斜率,b 是截距。霍夫变换的目标是从图像中找到直线的参数 m 和 b。 霍夫变换的基本思想是将图像中的每个点转换为一个参数空间(霍夫空间)中的曲线,这个曲线表示所有可能的直线通过这个点的位置。在霍夫空间中,每个曲线都表示一条直线。因此,找到在霍夫空间中交叉的曲线对应的参数,就可以确定图像中的直线。 以下是 Java 实现霍夫变换代码示例: ``` import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; public class HoughTransform { public static void main(String[] args) throws Exception { BufferedImage image = ImageIO.read(new File("input.png")); int width = image.getWidth(); int height = image.getHeight(); // 设置霍夫空间的参数范围 int minTheta = -90; int maxTheta = 90; int thetaRange = maxTheta - minTheta; int maxRho = (int) Math.sqrt(width * width + height * height); int rhoRange = 2 * maxRho; // 创建霍夫空间 int[][] houghSpace = new int[rhoRange][thetaRange]; // 遍历图像中的每个点 for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { int pixel = image.getRGB(x, y); if (pixel != 0) { // 像素不是黑色 // 在霍夫空间中增加点对应的曲线 for (int thetaIndex = 0; thetaIndex < thetaRange; thetaIndex++) { double theta = Math.toRadians(minTheta + thetaIndex); int rho = (int) (x * Math.cos(theta) + y * Math.sin(theta)); rho += maxRho; houghSpace[rho][thetaIndex]++; } } } } // 查找霍夫空间中的峰值 int maxCount = 0; int maxRhoIndex = 0; int maxThetaIndex = 0; for (int rhoIndex = 0; rhoIndex < rhoRange; rhoIndex++) { for (int thetaIndex = 0; thetaIndex < thetaRange; thetaIndex++) { if (houghSpace[rhoIndex][thetaIndex] > maxCount) { maxCount = houghSpace[rhoIndex][thetaIndex]; maxRhoIndex = rhoIndex; maxThetaIndex = thetaIndex; } } } // 计算最大峰值对应的直线参数 double maxTheta = Math.toRadians(minTheta + maxThetaIndex); int maxRho = maxRhoIndex - maxRho; int x1 = 0; int y1 = (int) (maxRho / Math.sin(maxTheta)); int x2 = (int) (maxRho / Math.cos(maxTheta)); int y2 = 0; // 在图像中绘制直线 for (int x = 0; x < width; x++) { int y = (int) ((maxRho - x * Math.cos(maxTheta)) / Math.sin(maxTheta)); if (y >= 0 && y < height) { image.setRGB(x, y, 0xFF0000); } } for (int y = 0; y < height; y++) { int x = (int) ((maxRho - y * Math.sin(maxTheta)) / Math.cos(maxTheta)); if (x >= 0 && x < width) { image.setRGB(x, y, 0xFF0000); } } // 保存输出图像 ImageIO.write(image, "png", new File("output.png")); } } ``` 这段代码读取一个输入图像,执行霍夫变换,并在输出图像中绘制检测到的直线。注意,这只是一个简单的示例,实际使用时可能需要进行更多的参数调整和优化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值