Page 235 - The Definitive Guide to Building Java Robots
P. 235
Preston_5564C06.fm Page 216 Friday, September 23, 2005 5:13 AM
216 CHAPTER 6 ■ VISION
Code Objective
The code objective here is to use the Hough transform to find the lines in an image.
Code Discussion
Our algorithm will follow the next sequence of steps:
1. Smooth the image. We do this to give us better transitions for the edges and less noise.
2. Find the edges of the image. We do this to give us the most potential lines.
3. Threshold the edges. We do this to separate softer edges into hard black-and-white edges.
4. Create an accumulator array of angles and distances (polar coordinates) for lines. This
is a way of counting all possible lines. We use polar coordinates because the standard
line equation, y = mx + b, has problems with vertical lines (that is, an infinite slope).
5. Move through the image pixel by pixel, looking for edge points.
6. When there is a hit, cycle through all possible lines at that point and increment the
accumulator vote total by 1 for each angle and distance, while solving for the equation
p = x * cos(theta) + y * sin(theta).
7. Convert the polar coordinates with the most votes back to Cartesian coordinates as
representations of lines. (See Example 6-28 and Figure 6-24.)
Example 6-28. getHoughLines.java
public BufferedImage getHoughLines(BufferedImage srcImg) {
double hough_thresh = .25;
// since all points are being traversed, most lines will be found by
// only moving through 90 degrees
// also i only care about grid lines
int angle_range = 90;
// angular resolution
int aRes = 1;
int h = srcImg.getHeight();
int w = srcImg.getWidth();
// maximum radius of image is diagonal
int pMax = (int) Math.sqrt((w * w) + (h * h));
int[][] acc = new int[pMax][angle_range]; // create accumulator
// pre-process image
srcImg = smooth(srcImg);
srcImg = sobelGradMag(srcImg);
srcImg = threshold(srcImg, 127, 255);