user
Task

Implement the Hough transform, which is used as part of feature extraction with digital images.

It is a tool that makes it far easier to identify straight lines in the source image, whatever their orientation.

The transform maps each point in the target image, 

(
ρ
,
θ
)
{\displaystyle {\displaystyle (\rho ,\theta )}}
, to the average color of the pixels on the corresponding line of the source image (in 

(
x
,
y
)
{\displaystyle {\displaystyle (x,y)}}
-space, where the line corresponds to points of the form 

x
cos
⁡
θ
+
y
sin
⁡
θ
=
ρ
{\displaystyle {\displaystyle x\cos \theta +y\sin \theta =\rho }}
). The idea is that where there is a straight line in the original image, it corresponds to a bright (or dark, depending on the color of the background field) spot; by applying a suitable filter to the results of the transform, it is possible to extract the locations of the lines in the original image.

Sample PNG image to use for the Hough transform.

The target space actually uses polar coordinates, but is conventionally plotted on rectangular coordinates for display. There's no specification of exactly how to map polar coordinates to a flat surface for display, but a convenient method is to use one axis for 

θ
{\displaystyle {\displaystyle \theta }}
 and the other for 

ρ
{\displaystyle {\displaystyle \rho }}
, with the center of the source image being the origin.

There is also a spherical Hough transform, which is more suited to identifying planes in 3D data.
assistant
(formerly Perl 6)
The `GD` module the output palette to 255 colors, so only transform darker pixels in the image.

**Translation of**: Perl

```
use GD;

my $filename = 'pentagon.ppm';
my $in = open($filename, :r, :enc<iso-8859-1>);
my ($type, $dim, $depth) = $in.lines[^3];
my ($xsize,$ysize) = split ' ', $dim;

my ($width, $height) = 460, 360;
my $image = GD::Image.new($width, $height);

my @canvas = [255 xx $width] xx $height;

my $rmax = sqrt($xsize**2 + $ysize**2);
my $dr   = 2 * $rmax / $height;
my $dth  = π / $width;

my $pixel = 0;
my %cstore;
for $in.lines.ords -> $r, $g, $b {
    $pixel++;
    next if $r > 130;

    my $x =       $pixel % $xsize;
    my $y = floor $pixel / $xsize;

    (^$width).map: -> $k {
        my $th = $dth*$k;
        my $r = ($x*cos($th) + $y*sin($th));
        my $iry = ($height/2 + ($r/$dr).round(1)).Int;
        my $c = '#' ~ (@canvas[$iry][$k]--).base(16) x 3;
        %cstore{$c} = $image.colorAllocate($c) if %cstore{$c}:!exists;
        $image.pixel($k, $iry, %cstore{$c});
    }
}

my $png_fh = $image.open("hough-transform.png", "wb");
$image.output($png_fh, GD_PNG);
$png_fh.close;

```

See Hough Transform (offsite .png image)