6
$\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$
0

2 Answers 2

8
$\begingroup$
img = Import["https://i.sstatic.net/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

$\endgroup$
0
9
$\begingroup$

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 

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

$\endgroup$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.