Categorize different images
Question: I have a number of images from Chinese genealogies, and I would like to be
able to programatically categorize them. Generally speaking, one type of image
has primarily line-by-line text, while the other type may be in a grid or
chart format.

Example photos

  * 'Desired' type: <http://www.flickr.com/photos/63588871@N05/8138563082/>

  * 'Other' type: <http://www.flickr.com/photos/63588871@N05/8138561342/in/photostream/>

Question: Is there a (relatively) simple way to do this? I have experience
with Python, but little knowledge of image processing. Direction to other
resources is appreciated as well.

Thanks!


Answer: Assuming that at least some of the grid lines are exactly or almost exactly
vertical, a fairly simple approach might work.

I used [PIL](http://www.pythonware.com/products/pil/) to find all the columns
in the image where more than half of the pixels were darker than some
threshold value.

## Code

    
    
    import Image, ImageDraw # PIL modules
    
    withlines = Image.open('withgrid.jpg')
    nolines   = Image.open('nogrid.jpg')
    
    def findlines(image):
        w,h, = image.size
        s = w*h
        im = image.point(lambda i: 255 * (i < 60))   # threshold
        d = im.getdata()      # faster than per-pixel operations
    
        linecolumns = []
    
        for col in range(w):
            black = sum( (d[x] for x in range(col, s, w)) )//255
            if black > 450:
                linecolumns += [col]
    
        # return an image showing the detected lines
        im2 = image.convert('RGB')
        draw = ImageDraw.Draw(im2)        
        for col in linecolumns:
            draw.line( (col,0,col,h-1), fill='#f00', width = 1)
    
        return im2
    
    findlines(withlines).show()
    findlines(nolines).show()
    

## Results

showing detected vertical lines in red for illustration

![image 1](http://i.stack.imgur.com/1TDXH.jpg)![enter image description
here](http://i.stack.imgur.com/IRjDm.jpg)

As you can see, four of the grid lines are detected, and, with some processing
to ignore the left and right sides and the center of the book, there should be
no false positives on the desired type.

This means that you could use the above code to detect black columns, discard
those that are near to the edge or the center. If any black columns remain,
classify it as the "other" undesired class of pictures.

