让我们看一下这个 C# 实现,
... ...
// 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,每个 y 增量递增指针递offset
。如果rect
大于图像,我们将指针递增到图像缓冲区之外。如果rect
只是移出图像边界,但不要太大,我们将读取与我们正在使用的坐标不对应的像素。
问题 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
( 范围内定义(移动到新的坐标系。
通常,霍夫变换由左上角像素中的原点定义。但原则上如何定义坐标系并不重要,这只是修改了线的参数化。为每个输入像素绘制的正弦曲线将不同,但对于与图像中的线对应的参数集,仍将显示局部最大值。