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 * A filter to perform auto-equalization on an image. 024 */ 025public class EqualizeFilter extends WholeImageFilter { 026 027 private int[][] lut; 028 029 public EqualizeFilter() { 030 } 031 032 protected int[] filterPixels( int width, int height, int[] inPixels, Rectangle transformedSpace ) { 033 Histogram histogram = new Histogram(inPixels, width, height, 0, width); 034 035 int i, j; 036 037 if (histogram.getNumSamples() > 0) { 038 float scale = 255.0f / histogram.getNumSamples(); 039 lut = new int[3][256]; 040 for (i = 0; i < 3; i++) { 041 lut[i][0] = histogram.getFrequency(i, 0); 042 for (j = 1; j < 256; j++) 043 lut[i][j] = lut[i][j-1] + histogram.getFrequency(i, j); 044 for (j = 0; j < 256; j++) 045 lut[i][j] = (int)Math.round(lut[i][j]*scale); 046 } 047 } else 048 lut = null; 049 050 i = 0; 051 for (int y = 0; y < height; y++) 052 for (int x = 0; x < width; x++) { 053 inPixels[i] = filterRGB(x, y, inPixels[i]); 054 i++; 055 } 056 lut = null; 057 058 return inPixels; 059 } 060 061 private int filterRGB(int x, int y, int rgb) { 062 if (lut != null) { 063 int a = rgb & 0xff000000; 064 int r = lut[Histogram.RED][(rgb >> 16) & 0xff]; 065 int g = lut[Histogram.GREEN][(rgb >> 8) & 0xff]; 066 int b = lut[Histogram.BLUE][rgb & 0xff]; 067 068 return a | (r << 16) | (g << 8) | b; 069 } 070 return rgb; 071 } 072 073 public String toString() { 074 return "Colors/Equalize"; 075 } 076}