Extract partitions of images after edge detection

Given a edge detected image like this:

I would like to extract each character into a sub-image, i.e so that each new picture only have one character. Is there a simple way of doing this in Mathematica? I figured since ContourDetect[] gives this:

It appears that mathematica atleast have no problems of finding the actual contours.

img = Import["https://i.sstatic.net/e4dN6.jpg"];


Binarize // MorphologicalTransform // ComponentMeasurements // ImageTrim

boxes = MorphologicalTransform[Binarize@img, "BoundingBoxes", ∞]


trim = ComponentMeasurements[boxes, "BoundingBox"][[All, -1]];

ImageTrim[img, trim]


Combining all steps in a function:

imgPartition = ImageTrim[#,
ComponentMeasurements[
MorphologicalTransform[Binarize @ #, "BoundingBoxes", ∞],
"BoundingBox"][[All, -1]]] &;

imgPartition @ img


same picture

MorphologicalComponents seems like a promising way to go, like High Performance Mark says. So let's try it:

img = Import["https://i.sstatic.net/e4dN6.jpg"];
MorphologicalComponents[img] // Colorize


We see here that there are more non-zero pixels (foreground pixels) than the original image lets on from looking at it. This causes MorphologicalComponents to find spurious components and to merge some components (like the two E characters.) Since those pixels are dark, we can guess that we can remove them using Binarize:

components = MorphologicalComponents[Binarize[img]];
components // Colorize


This is better, but now there is another problem: there are smaller components inside some of the components, like sixes. We can remove these by first using Dilation to make sure that the border of the outer component is closed and then using SelectComponents to remove all components that are enclosed by some other component.

components = MorphologicalComponents[Dilation[Binarize[img], 1]];
components = SelectComponents[components, #EnclosingComponentCount == 0 &];
components // Colorize


Now it looks like we found the right components. ComponentMeasurements can now be used to find the bounding boxes of the components and ImageTrim can be used to extract them from the image:

ComponentMeasurements[{img, components}, "Image"][[All, 2]]