Search code examples
javaimagecollision-detectionjbox2d

How would I detect the edges of an image (transparent background) in Java?


I have my image with a transparent background. I want to find the edges of the image and form a polygon from the outline. There are multiple methods/ways I could do this. I want to do it in Java (its for my game, which is using JBox2d Polygons for collision detection).

I have had some thought about this and am thinking how this would work. I could try detecting all transparent pixels, then invert the selection and only select the pixels that have 1 adjacent transparent pixel. This is all very complicated and I would like some guidence.


Solution

  • There are two aspects to your question.

    1. Edge-detection. If your image has an alpha-channel, then you should be able to choose a suitable threshold and perform edge-detection to find the 'edges' of the transparent/opaque pixels. If it's just a GIF with a 'transparent' color, then it should a bit easier since you're effectively working with a black & white image.

    2. Vectorization. This is where it gets (really) tricky. The field of raster to vector conversion is fertile ground. I would look at how solutions such as Potrace (GPL) are implemented then maybe attempt to build my own off that.

    However, for a game, personally, I wouldn't even try real-time edge/collision detection this way. Since I'm working with sprites, I would use bounding boxes and other raster-based techniques.

    If I really want polygon-based edge/collision detection, then I would probably opt to manually trace edges beforehand and just store them along with each raster image, then perform computations on those (trade space for time). I presume that the images you work with aren't dynamically generated at run-time making pre-computation possible.