Search code examples
javaimagej

How to flip an image horizontally with an ImageJ-Plugin?


I want to develop a Java-Plugin for ImageJ that flips an image horizontally. But my code flips only half of the picture. Maybe, there is something wrong with the construction or the output of the image copy?

public class flipHorizontal implements PlugInFilter {

public int setup (String arg, ImagePlus imp)
{
    return DOES_ALL;
}

public void run (ImageProcessor ip)
{
    int height=ip.getHeight();
    int width=ip.getWidth();

    ImageProcessor copy = ip;


    for (int x=0; x<width; x++) {

        for (int y=0; y<height; y++) {
            int p=ip.getPixel(width-x-1,y);
            copy.putPixel(x,y,p);
        }
    }
  }
}

Solution

  • Your logic is wrong. What you get is normal: you're not processing half of your image but flipping horizontally once half of your image and twice the other half (if I'm not mistaken).

    Anyway, if you want to flip horizontally by manipulating pixels yourself directly, as in your code sample, then instead of going to width, you need to go to half the width (width/2).

    You then need to actually invert the two pixels from "left" and "right"

    Here's an horizontal flip that works:

        for (int x = 0; x < w / 2; x++) {
            for (int y = 0; y < h; y++) {
                final int l = tmp.getRGB( w - (x + 1), y);
                final int r = tmp.getRGB( x, y);
                tmp.setRGB( x, y, l );
                tmp.setRGB( w - (x + 1), y, r );
            }
        }
    

    There may be "off-by-one" errors in the code above but you should get the idea.