Yeah, this time I will introduce about character segmentation in details[Code] from the previous entry.
First of all,you should load this tester image for workshop.
image.jpg (11.77 kb)
OK, this workshop works on Python language with Python Image Library.
http://www.pythonware.com/products/pil/index.htm
There are 5 parts in this workshop.
1. Preprocessing -> prepare image before do the main process.
2. Find histograms in both directions -> to be used in step 3.
3. Find pair of concave up and down points -> to find segmentation points.
4. Segmentation.
5. Show Results.
Recall from the previous entry.
In Preprocessing, we need to load the image in grayscale image. Next, clean the image. Then, convert to a binary image.
# load and convert image to a grayscale image.
im = Image.open('image.jpg').convert("L")
(width, height) = im.size
# use median filter size 11x11 to clean image
mim = im.filter(ImageFilter.MedianFilter(11))
# extract foreground from background by using threshold value.
# using threshold = 8, then use median filter to clean image again.
cim = mim.point(lambda i: i*8,"F").convert("1").filter(ImageFilter.MedianFilter(11))
We will get the result like this. [Use cim.show() to show an image]
Next, we have to find histograms in horizontal and vertical lines.
#main process part
# load image to 2d
pix = cim.load()
#find histograms in both directions
hhist = []
s = 0
for h in range(height):
for w in range(width):
if(pix[w,h]==0):
s+=1
hhist.append(s)
s = 0
vhist = []
s = 0
for w in range(width):
for h in range(height):
if(pix[w,h]==0):
s+=1
vhist.append(s)
s = 0
Then, we have to find cutting point from the image by seeing from histogram value that goes up from 0 to upper and goes down from more than 0 to 0.
#find pair of concave up and down points
hup = [] #keep concave up index [horizontal]
hdown = [] #keep concave down index [horizontal]
s = len(hhist)
for x in range(1,s):
if(hhist[x-1]>0 and hhist[x]==0):
hdown.append(x-1)
if(hhist[x-1]==0 and hhist[x]>0):
hup.append(x)
vup = [] #keep concave up index [vertical]
vdown = [] #keep concave down index [vertical]
s = len(vhist)
for x in range(1,s):
if(vhist[x-1]>0 and vhist[x]==0):
vdown.append(x-1)
if(vhist[x-1]==0 and vhist[x]>0):
vup.append(x)
Finally, we will segment an image and then show the result of all characters. We have to create a box for crop an image (left,upper,right,lower) that upper and lower will use values from hup and hdown respectively.
#segmentation
# we know that we have only 1 line so, hup and hdown are not change.
# if we want to show all segmented images, it will change in vup and vdown indexes.
for i in range(len(vup)):
box = (vup[i],hup[0],vdown[i],hdown[0])
seg = cim.crop(box)
#show result
seg.show()
Now, we will know about the concept of image segmentation that is not hard for implement. It may expand your thought to develop a more complicated segmentation ^^.
489ffe6a-6b94-4b85-9f1b-f79ee57a8af2|1|5.0