How to crop an ImagePlus object

Hi all,

I am using ImageJ in a project and am having some trouble cropping and using the cropped image.

I would like to crop an ImagePlus object and then have just the cropped region to work with rather than the original image still. Here is the where I am struggling:

println(imp.getWidth(), im.getHeight();
ImageProcessor temp = imp.getProcessor();
temp.setRoi(X1, Y1, X2-X1, Y2-Y1);
temp.crop();
imp.setProcessor(temp);
println(imp.getWidth(), im.getHeight();

Here’s the output:

3744 2560
3744 2560

I understand that this isn’t actually changing the ImagePlus object and is just changing the ImageProcessor, but I’m not sure how to access a modified version of the ImagePlus object who’s ImageProcessor I am changing.

Thank you in advance for your input!

Hi @Grayson_Harrington,

Not sure what language you’re using, I’m going to assume java, since there’s a java tag.

You can just create a new ImagePlus from your ImageProcessor:

ImagePlus croppedImp = new ImagePlus("my cropped image", temp );

Check out the api for ImagePlus.

Post back if you’re still having trouble.
John

PS. double check for typos - you hava imp in some places and im in others.

Hi @bogovicj,

Thank you for your quick reply!

I should have mentioned it, but I did try that before and no changes occurred.

    println(imp.getWidth(), imp.getHeight());
    ImageProcessor temp = imp.getProcessor();
    
    println();
    println(X1, Y1);
    println(X2-X1, Y2-Y1);
    println();

    temp.setRoi(X1, Y1, X2-X1, Y2-Y1);
    temp.crop();

    imp = new ImagePlus("cropped image", temp);
    println(imp.getWidth(), imp.getHeight());
    exit();

and the output:

4864 2576

95 1358
4356 298

4864 2576

FYI: I am using Processing, a Java-based language. I am accessing the ImageJ functions and classes from a jar file (v. 1.50g)

1 Like

@Grayson_Harrington,

No worries.
I didn’t check what crop does… from here:

ImageProcessor crop()
Returns a new processor containing an image that corresponds to the current ROI.

which means:

cropped_processor = temp.crop()
imp = new ImagePlus("cropped image", cropped_processor);

// or
imp = new ImagePlus("cropped image", temp.crop());

should do it for you.

John

1 Like

That did it! Thank you!

1 Like