import ij.*; import ij.plugin.filter.PlugInFilter; import ij.process.*; import java.awt.*; /** This example plugin filter inverts an Image that can be in any of the four data types supported by ImageJ: unsigned byte, unsigned short, float and RGB. */ public class Inverter_ implements PlugInFilter { public int setup(String arg, ImagePlus imp) { return DOES_ALL+DOES_STACKS+SUPPORTS_MASKING; } public void run(ImageProcessor ip) { if (ip instanceof ByteProcessor) invert8BitImage(ip); else if (ip instanceof ShortProcessor) invert16BitImage(ip); else if (ip instanceof FloatProcessor) invert32BitImage(ip); else if (ip instanceof ColorProcessor) invertRGBImage(ip); } public void invert8BitImage(ImageProcessor ip) { byte[] pixels = (byte[])ip.getPixels(); int width = ip.getWidth(); Rectangle r = ip.getRoi(); int offset, i; for (int y=r.y; y<(r.y+r.height); y++) { offset = y*width; for (int x=r.x; x<(r.x+r.width); x++) { i = offset + x; pixels[i] = (byte)(255-pixels[i]); } } } public void invert16BitImage(ImageProcessor ip) { short[] pixels = (short[])ip.getPixels(); int width = ip.getWidth(); Rectangle r = ip.getRoi(); ip.resetMinAndMax(); int max = (int)ip.getMax(); int offset, i; for (int y=r.y; y<(r.y+r.height); y++) { offset = y*width; for (int x=r.x; x<(r.x+r.width); x++) { i = offset + x; pixels[i] = (short)(max-pixels[i]&0xffff); } } } public void invert32BitImage(ImageProcessor ip) { float[] pixels = (float[])ip.getPixels(); int width = ip.getWidth(); Rectangle r = ip.getRoi(); ip.resetMinAndMax(); double max = ip.getMax(); int offset, i; for (int y=r.y; y<(r.y+r.height); y++) { offset = y*width; for (int x=r.x; x<(r.x+r.width); x++) { i = offset + x; pixels[i] = (float)(max-pixels[i]); } } } public void invertRGBImage(ImageProcessor ip) { int[] pixels = (int[])ip.getPixels(); int width = ip.getWidth(); Rectangle rect = ip.getRoi(); ip.resetMinAndMax(); double max = ip.getMax(); int offset, i, c, r, g, b; for (int y=rect.y; y<(rect.y+rect.height); y++) { offset = y*width; for (int x=rect.x; x<(rect.x+rect.width); x++) { i = offset + x; c = pixels[i]; r = (c&0xff0000)>>16; g = (c&0x00ff00)>>8; b = (c&0x0000ff); r = 255-r; g = 255-g; b = 255-b; pixels[i] = ((r&0xff)<<16) + ((g&0xff)<<8) + (b&0xff); } } } }