Automatic cropping of collimated digital X-ray images
There is a software package ImageJ which can be used to what you are asking. Depending on your capability and the complexity of what you are doing you can either write a Macro in the program to crop images or you can extend the program in Java and write a custom plugin to do what you describe.

I used this program for years it is a very strong program.