Page 210 - The Definitive Guide to Building Java Robots
P. 210
Preston_5564C06.fm Page 191 Friday, September 23, 2005 5:13 AM
CHAPTER 6 ■ VISION 191
Code Discussion
This is the simplest kind of comparison. If the image’s greyscale pixel value is within a certain
range, then color it white. If it’s not in that range, color it black. You can see the output of
Example 6-14 in Figure 6-11.
The parameters for this method are of course the source image, the minimum value for the
threshold, the maximum value, and then a Boolean to return either the actual color or a binary
representation.
Example 6-14. threshold()
// gets threshold
public BufferedImage threshold(BufferedImage srcImg, int min, int max,
boolean transparent) {
// get h & w
int h = srcImg.getHeight();
int w = srcImg.getWidth();
// new image for processing
BufferedImage dstImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
for (int y = 0; y < h; ++y) {
for (int x = 0; x < w; ++x) {
// get color
int srcPixel = srcImg.getRGB(x, y);
// get grey of color
int colorValue = getGrey(srcPixel);
// compare to threshold & convert to binary
if (colorValue >= min && colorValue <= max) {
if (transparent) {
dstImg.setRGB(x, y, srcPixel);
} else{
dstImg.setRGB(x, y, Color.WHITE.getRGB());
}
} else {
dstImg.setRGB(x, y, Color.BLACK.getRGB());
}
}
}
return dstImg;
}