让我们看一下这个 C# 实现 https://github.com/andrewkirillov/AForge.NET/blob/a9453dad025d1fbffab165293cedc976187da535/Sources/Imaging/HoughLineTransformation.cs#L457,
... ...
// get source image size
int width = image.Width;
int height = image.Height;
int halfWidth = width / 2;
int halfHeight = height / 2;
// make sure the specified rectangle recides with the source image
rect.Intersect( new Rectangle( 0, 0, width, height ) );
int startX = -halfWidth + rect.Left;
int startY = -halfHeight + rect.Top;
int stopX = width - halfWidth - ( width - rect.Right );
int stopY = height - halfHeight - ( height - rect.Bottom );
int offset = image.Stride - rect.Width;
// calculate Hough map's width
int halfHoughWidth = (int) Math.Sqrt( halfWidth * halfWidth + halfHeight * halfHeight );
int houghWidth = halfHoughWidth * 2;
houghMap = new short[houghHeight, houghWidth];
// do the job
unsafe
{
byte* src = (byte*) image.ImageData.ToPointer( ) +
rect.Top * image.Stride + rect.Left;
// for each row
for ( int y = startY; y < stopY; y++ )
{
// for each pixel
for ( int x = startX; x < stopX; x++, src++ )
{
if ( *src != 0 )
{
// for each Theta value
for ( int theta = 0; theta < houghHeight; theta++ )
{
int radius = (int) Math.Round( cosMap[theta] * x - sinMap[theta] * y ) + halfHoughWidth;
if ( ( radius < 0 ) || ( radius >= houghWidth ) )
continue;
houghMap[theta, radius]++;
}
}
}
src += offset;
}
}
... ... ...
Q.1. rect.Intersect(new Rectangle( 0, 0, width, height));
- 为什么这条线很重要?
Q.2. 为什么使用修改值rect
在下面的代码中:
int startX = -halfWidth + rect.Left;
int startY = -halfHeight + rect.Top;
int stopX = width - halfWidth - ( width - rect.Right );
int stopY = height - halfHeight - ( height - rect.Bottom );
Q.3. 为什么 y 和 x 循环从负点开始?
Q.1.
这条线只是确保边界矩形完全位于图像内部。如果你要跳过这个,并且rect
(部分)在图像之外,您最终会索引超出范围。
请注意,像素访问是通过指针完成的,每个 x 增量将指针增加 1,并且offset
对于每个 y 增量。如果rect
比图像大,我们会将指针增加到图像缓冲区之外。如果rect
只是移出图像边界,但不是太大,我们会读取与我们正在使用的坐标不对应的像素。
Q.2.
注意
int stopX = width - halfWidth - ( width - rect.Right );
int stopY = height - halfHeight - ( height - rect.Bottom );
可以简化为
int stopX = - halfWidth + rect.Right;
int stopY = - halfHeight + rect.Bottom;
该代码定义了图像中间坐标系的原点。这段代码移动了边界框(最初定义在 [0,width
) 和 [0,height
) ) 到新的坐标系。
通常霍夫变换是用左上角像素中的原点定义的。但原则上,坐标系如何定义并不重要,这只是修改直线的参数化。为每个输入像素绘制的正弦曲线将有所不同,但与图像中的线条相对应的参数集仍会出现局部最大值。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)