4
$\begingroup$

Given a edge detected image like this: Image after edge detection

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:

Contour Detected

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

Thanks in advance!

$\endgroup$
7
$\begingroup$
img = Import["https://i.stack.imgur.com/e4dN6.jpg"];

Binarize // MorphologicalTransform // ComponentMeasurements // ImageTrim

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

enter image description here

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

ImageTrim[img, trim]

enter image description here

Combining all steps in a function:

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

imgPartition @ img

same picture

| improve this answer | |
$\endgroup$
8
$\begingroup$

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

img = Import["https://i.stack.imgur.com/e4dN6.jpg"];
MorphologicalComponents[img] // Colorize

Mathematica graphics

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

Mathematica graphics

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

Mathematica graphics

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]]

Mathematica graphics

| improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.