Process images by year

Creates individual CSV files for each year that contain image dimensions and computed number of columns for each file.

Use on SWAN to run column detection across all of the images.

This notebook generates CSV files for each year with summary results.

Fields in the CSV files:

  • directory
  • name
  • path
  • referenceCode
  • startDate
  • endDate
  • year
  • width – width of the image
  • height – height of the image
  • columns – number of columns
  • column_positions – comma-separated string of x values of columns in pixels
In [7]:
import numpy as np
import pandas as pd
import cv2
import math
import statistics
from tqdm import tqdm
import os
from IPython.display import display, HTML
    from PIL import Image
except ImportError:
    import Image
import pytesseract
from statistics import mean
import re
In [8]:

def find_lines(img):
    Find straight lines in an image.
    Returns a list of lines.
    These settings have been arrived at after much trial and error.
    # Convert to grayscale
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    # Theshold image (convert to black and white)
    retval, th = cv2.threshold(gray,125,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
    # cv2.imwrite('data/th.jpg',th)
    # Use median blur to get rid of a lot of the text
    median = cv2.medianBlur(th, 11)
    # cv2.imwrite('data/median.jpg',median)
    # Try to strengthen the remaining lines
    kernel = np.ones((5,5),np.uint8)
    opened = cv2.morphologyEx(median, cv2.MORPH_OPEN, kernel, iterations=1)
    # cv2.imwrite('data/opened.jpg',opened)

    # Find the edges of the remaining shapes
    edges = cv2.Canny(opened,50,150,apertureSize=3)
    # cv2.imwrite('data/edges.jpg',edges)
    # Find straight lines in the edges
    # Note that the minLineLength and maxLineGap values can have a dramatic effect on the number of lines detected.
    # Note too that what looks to the human eye as a single straight line,
    # can actually be a series of short line with tiny gaps between them,
    # so while increasing the minLineLength reduces noise from text, it can also filter out columns.
    lines = cv2.HoughLinesP(image=edges,rho=1,theta=np.pi/180, threshold=200,lines=np.array([]), minLineLength=100,maxLineGap=100)
    return lines

def find_header(img):
    Locate the page header, and return the y position of the bottom.
    Note that in this case using OCR seemed easier than trying to sort/cluster lines.
    # Image dimensions
    (h, w) = img.shape[:2]
    points = []
    # The header will always be at the top, so crop off the top of the image, rather than OCRing the whole thing
    cropped = img[0:round(h/4), 0:round(w-(w/4))]
    # I should probably do some image preprocessing here (see row detection notebook)
    # Get OCR results
    results = pytesseract.image_to_data(cropped, output_type=pytesseract.Output.DICT)
    # Loop through the OCR results looking for specific words that appear in the header
    for index, word in enumerate(results['text']):
        # These are the words that appear in the header
        # If we find one, add its 'top' value to our list of points
        if'Shares|Quotations|Buyers|Sellers|Business|Done|Closing prices|Sales', word, flags=re.IGNORECASE) and results['height'][index] < 50:
            # y = results['top'][index]
    # y = round(mean(points))
    # print(points)
        # Sort points and get the first
        y = sorted(points)[0]
    except IndexError:
        # If we can't find a header return 0
        y = 0
    # Return y value of header
    return y

def check_for_skew(lines):
    Check for skewing by looking at the near vertical lines detected in the image.
    angles = []
    # Loop through detected lines
    for line in lines:
        # Get coords of line
        for x1,y1,x2,y2 in line:
            # Ignore short lines and lines in header
            if abs(y1 - y2) > 150 and x1 > 300:
                # Get the angle of the line
                if y2 > y1:
                    radians = math.atan2((y2 - y1), (x2 - x1))
                    radians = math.atan2((y1 - y2), (x1 - x2))
                degrees = math.degrees(radians)
                # print(degrees)
                # If it's vertical-ish, save this angle
                if degrees >= 80 and degrees <= 100:
    # Get the media of the saved angles
    angle = statistics.median(angles) - 90
    # print(angle)
    return angle

def deskew(img, angle):
    Deskew image by rotating it by the supplied angle.
    # Get image dimensions
    (h, w) = img.shape[:2]
    # Get the centre of the image
    center = (w // 2, h // 2)
    # Rotate image by angle
    M = cv2.getRotationMatrix2D(center, angle, 1.0)
    rotated = cv2.warpAffine(img, M, (w, h),flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)
    # Return the rotated image
    return rotated

def add_grid(img):
    Draws a 100 x 100px grid on image.
    Can be useful in interpreting column detection results.
    h, w = img.shape[:2]
    for x in range(0, w, 100):
    for y in range(0, h, 100):
    return img

def find_top(lines):
    Use horizontal lines near the top of the page to provide an approximation of the header height.
    Used to crop page to ignore lines in header area.
    More accurate header location is found using Tesseract.
    top = 0
    y_values = []
    for line in lines:
        for x1,y1,x2,y2 in line:
            bottom = y1 if y1 > y2 else y2
            if bottom < 1000:
                radians = math.atan2((y1 - y2), (x1 - x2))
                degrees = math.degrees(radians)
                if degrees > 179 and degrees < 181:
    if y_values:
        top = sorted(y_values)[-1]
    return top           

def find_columns(lines, h, w):
    Identifies most likely column values from within the set of straight lines in an image.
    This could do with some cleaning up, but it's working well at the moment, so I don't really want to fiddle any more.
    Note that this does depend on some knowledge of the images to define ranges of expected values.
    x_values = []
    # Get the approximate position of the header so we can ignore lines above this
    column_top = find_top(lines)

    # Find the x values of vertical lines
    for line in lines:
        for x1,y1,x2,y2 in line:
            # Find the top
            top = y1 if y1 < y2 else y2
            # Ignore column lines at the top & bottom of the image
            if top > column_top and top < (h - 600):

                # Find the leftmost point
                first = x1 if x1 < x2 else x2
                # Find the angle of the line
                radians = math.atan2((y1 - y2), (x1 - x2))
                degrees = abs(math.degrees(radians))
                # If the line is (close to) vertical, we'll save the left-most x value
                if degrees >= 89 and degrees <= 91:
    # Sort the x_values
    x_values = sorted(x_values)
    # Cluster together values within the specified distance
    clusters = []
    start = 0
    # Lines less than this distance apart will be clustered
    distance = 10
    cluster = []
    # Loop through x values
    for x in x_values:
        # If the x value is less than the specified distance from the previous point,
        # we'll add it to the current cluster
        if x < start + distance:
        # If not we'll save the current cluster, and start a new one
            if cluster:
                # Add the current cluster to the list of clusters
            # Start a new cluster at the current point
            cluster = [x]
        # Set the current position
        start = x
        # Add the last cluster once we've finished the loop

    # Now we have a list of clustered x values
    # We'll compare nearby clusters and keep the ones with the most values (most likely to be columns)
    best_clusters = [[0]]
    # Loop through clusters
    for cluster in clusters:
        # If the current cluster is within 200px of the previous one
        if cluster[0] < best_clusters[-1][-1] + 200:
            # Check to see which cluster contains the most values
            # If it's the current one we'll add it to our best clusters
            if len(cluster) > len(best_clusters[-1]):
                # Remove the previous cluster from best clusters
                # Add this one
        # If this cluster isn't near the previous one, add it to best clusters
    # Now we have our best candidates for columns in best clusters
    # We'll do some further filtering by checking the clusters against our expectations of column positions
    # The pixel values used below are based on trial and error with the Stock Exchange images
    # Obviously if you were using this on other images you'd want to adjust them accordingly
    columns = []
    start = 0
    gutter = 0
    gap = None
    # Loop through our best clusters
    for cluster in best_clusters:
        # If the leftmost point in this cluster is less than 600 then it's the gutter
        if cluster and cluster[0] < 600:
            # Set the gutter value to a mean of the clustered points
            gutter = mean(cluster)
            # Sometimes the gutter isn't detected, so we'll set a reasonable start position
            if gutter < 100:
                start = 100
                start = gutter
            # Checking the gap between this cluster and the previous one
            if gap:
                this_gap = gap
                # Current gap is the leftmost point of this cluster minus the previous column position
                this_gap = cluster[0] - start
            # This range represents approximate min/max column widths
            # We'll look for columns at 100 px intervals starting from the max value until we hit the min value
            for width in reversed(range(900, 2000, 100)):
                # Try to make sure columns are roughly the same width
                if (cluster[0] - start) > (this_gap - 600) and (cluster[0] - start) < (this_gap + 600):
                    # If cluster falls within expected values, we'll assume it's a column
                    if cluster and cluster[0] > (start + width) and cluster[0] < (w - 600) and this_gap < 2600:
                        # Save mean of clustered values as column
                        # Set the next start value to value of the last point in cluster
                        start = cluster[-1]
                        gap = this_gap
                        # Don't look for any more columns in this cluster
    return (gutter, columns)

def resize(img, h, w):
    Resize image to a max width of 5000 px.
    # Find the scale to use, based on max width
    scale = 5000 / float(w)
    # Resize the image
    resized = cv2.resize(img, None, fx=scale, fy=scale, interpolation = cv2.INTER_AREA)
    return resized

def save_header(img, header, w, image_name, output_dir):
    Save the detected header as a separate image.
    # Where to save the image
    header_dir = os.path.join(output_dir, 'headers')
    # Crop the image using header value
    # Numpy slicing - roi = im[y1:y2, x1:x2]
    header_img = img[0:header+20, 0:w]
    # Save the cropped image
    cv2.imwrite('{}/{}-header.jpg'.format(header_dir, image_name[:-4]), header_img)

def save_columns(img, columns, header, h, image_name, output_dir):
    Save each detected column as a separate image.
    Note that the columns list should include the gutter at the beginning and the image width at the end.
    # Where to save the images
    col_dir = os.path.join(output_dir, 'columns')
    # Loop through the column values
    for index, column in enumerate(columns):
        # Get the value of the next column to use as the width of the cropped column
            next_col = columns[index+1]
        except IndexError:
            # If there's no next column we've reached the end of the image, so do nothing
            # Add a little to the margins of the image
            if column > 20:
                this_col = column - 20
                this_col = column
            # Crop the image to the dimensions of the column
            col_img = img[header-20:h, this_col:next_col]
            # Save the cropped image, using the undex value to denote column order
            cv2.imwrite('{}/{}-col-{}.jpg'.format(col_dir, image_name[:-4], index+1), col_img)
def display_lines(image_name, output_dir, img, lines):
    For testing / debugging - shows ALL the detected lines
    for line in lines:
        x1,y1,x2,y2 = line[0]
    #cv2.imwrite('{}/{}-lines.jpg'.format(output_dir, image_name[:-4]), img)

def process_image(image_name, image_path, output_dir='test', markup=False, grid=False):
    Detect columns and header in the supplied image.
        output_dir (must exist)
        markup – if True, draw the results on the image, if False crop and save the detected regions.
        grid – if True, draw a grid on the image
    img = cv2.imread(image_path)
    # Get image dimensions
        h, w = img.shape[:2]
    # Weed out dodgy images
    except AttributeError:
        print('Not a valid image: {}'.format(image_path))
    # If it looks ok, then proceed...
        # To standardise things a little, we'll resize images with a width greater than 5000
        if w > 5000:
            img = resize(img, h, w)
            # Get the new dimensions
            h, w = img.shape[:2]
        # Detect stratight lines in the image
        lines = find_lines(img)
        # Use the detected lines to check for skew
        # I'm not actually sure if these deskewing steps are useful
        angle = check_for_skew(lines)
        # If image seems to be skewed, then deskew!
        if angle != 0:
            # print('Deskewing')
            img = deskew(img, angle)
            # Once deskewed we have to redo line detection because positions will have changed
            lines = find_lines(img)
        #display_lines(image_name, output_dir, img, lines)
        # Filter the detected lines to identify columns
        gutter, columns = find_columns(lines, h, w)
        # Find the bottom of the header
        header = find_header(img)
        # Draw a grid on image (for debugging)
        if grid:
            img = add_grid(img)
        # Draw detected column & header lines on image and save the results (for testing)
        if markup:
            # Draw gutter 
            # Draw columns
            for column in columns:
            # Draw header
            cv2.line(img,(0, header),(w, header),(255,0,0),3)
            # Save the annotated image
            cv2.imwrite('{}/{}.jpg'.format(output_dir, image_name[:-4]), img)
        # Otherwise crop & save columns and header
            # Crop and save header
            save_header(img, header, w, image_name, output_dir)
            # Add gutter and page width to the columns list
            columns = [gutter] + columns + [w] 
            # Crop and save columns
            save_columns(img, columns, header, h, image_name, output_dir)


def get_image_params(image_path):
    Opens an image and looks for columns.
    Returns image dimensions and number of columns as Pandas Sesries.
    # Changed to point to absolute path
    img = cv2.imread(os.path.join(os.sep, 'webdav', image_path))
    # This is just to weed out dodgy images
        h, w = img.shape[:2]
    except AttributeError:
        print('Not a valid image')
        new_h = 0
        new_w = 0
        columns = []
        column_positions = ''
        if w > 5000:
            img = resize(img, h, w)
            new_h, new_w = img.shape[:2]
            new_h = h
            new_w = w
        lines = find_lines(img)
        angle = check_for_skew(lines)
        if angle != 0:
            img = deskew(img, angle)
            lines = find_lines(img)
        gutter, columns = find_columns(lines, new_h, new_w)
        columns.insert(0, gutter)
        column_positions = ','.join([str(c) for c in columns])
    return pd.Series([new_h, new_w, len(columns), column_positions])
In [9]:
def data_by_year(start=1901):
    Split the big file list up by year, add image/column details, then save each year as a new CSV.
    df = pd.read_csv('files_with_dates.csv')
    years = df.groupby('year')
    for year, files in years:
        if int(year) >= start:
            files[['width', 'height', 'columns', 'column_positions']] = files.progress_apply(lambda x: get_image_params(x['path']), axis=1)
            files.to_csv('{}.csv'.format(year), index=False)
In [ ]:
tqdm.pandas(desc='Images', leave=False)
In [ ]: