001/* 002Copyright 2006 Jerry Huxtable 003 004Licensed under the Apache License, Version 2.0 (the "License"); 005you may not use this file except in compliance with the License. 006You may obtain a copy of the License at 007 008 http://www.apache.org/licenses/LICENSE-2.0 009 010Unless required by applicable law or agreed to in writing, software 011distributed under the License is distributed on an "AS IS" BASIS, 012WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013See the License for the specific language governing permissions and 014limitations under the License. 015*/ 016 017package com.jhlabs.image; 018 019import java.awt.*; 020import java.awt.image.*; 021 022/** 023 * Given a binary image, this filter performs binary erosion, setting all removed pixels to the given 'new' color. 024 */ 025public class ErodeFilter extends BinaryFilter { 026 027 private int threshold = 2; 028 029 public ErodeFilter() { 030 newColor = 0xffffffff; 031 } 032 033 /** 034 * Set the threshold - the number of neighbouring pixels for dilation to occur. 035 * @param threshold the new threshold 036 * @see #getThreshold 037 */ 038 public void setThreshold(int threshold) { 039 this.threshold = threshold; 040 } 041 042 /** 043 * Return the threshold - the number of neighbouring pixels for dilation to occur. 044 * @return the current threshold 045 * @see #setThreshold 046 */ 047 public int getThreshold() { 048 return threshold; 049 } 050 051 protected int[] filterPixels( int width, int height, int[] inPixels, Rectangle transformedSpace ) { 052 int[] outPixels = new int[width * height]; 053 054 for (int i = 0; i < iterations; i++) { 055 int index = 0; 056 057 if (i > 0) { 058 int[] t = inPixels; 059 inPixels = outPixels; 060 outPixels = t; 061 } 062 for (int y = 0; y < height; y++) { 063 for (int x = 0; x < width; x++) { 064 int pixel = inPixels[y*width+x]; 065 if (blackFunction.isBlack(pixel)) { 066 int neighbours = 0; 067 068 for (int dy = -1; dy <= 1; dy++) { 069 int iy = y+dy; 070 int ioffset; 071 if (0 <= iy && iy < height) { 072 ioffset = iy*width; 073 for (int dx = -1; dx <= 1; dx++) { 074 int ix = x+dx; 075 if (!(dy == 0 && dx == 0) && 0 <= ix && ix < width) { 076 int rgb = inPixels[ioffset+ix]; 077 if (!blackFunction.isBlack(rgb)) 078 neighbours++; 079 } 080 } 081 } 082 } 083 084 if (neighbours >= threshold) { 085 if (colormap != null) 086 pixel = colormap.getColor((float)i/iterations); 087 else 088 pixel = newColor; 089 } 090 } 091 outPixels[index++] = pixel; 092 } 093 } 094 } 095 096 return outPixels; 097 } 098 099 public String toString() { 100 return "Binary/Erode..."; 101 } 102 103} 104