# 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
try:
from PIL import Image
except ImportError:
import Image
import pytesseract
from statistics import mean
import re

In [8]:
# COPIED FROM MAIN PROCESSING NOTEBOOK

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

'''
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
# y = results['top'][index]
points.append(results['top'][index])
# y = round(mean(points))
# print(points)

try:
# 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))
else:
radians = math.atan2((y1 - y2), (x1 - x2))
# print(degrees)
# If it's vertical-ish, save this angle
if degrees >= 80 and degrees <= 100:
angles.append(degrees)
# 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

'''
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):
cv2.line(img,(x,0),(x,h),(255,0,0),1)
for y in range(0, h, 100):
cv2.line(img,(0,y),(w,y),(255,0,0),1)
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))
if degrees > 179 and degrees < 181:
y_values.append(bottom)
if y_values:
top = sorted(y_values)[-1]

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

# If the line is (close to) vertical, we'll save the left-most x value
if degrees >= 89 and degrees <= 91:
x_values.append(first)

# 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:
cluster.append(x)

# If not we'll save the current cluster, and start a new one
else:
if cluster:
# Add the current cluster to the list of clusters
clusters.append(cluster)

# 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
clusters.append(cluster)

# 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
best_clusters.pop()

best_clusters.append(cluster)

# If this cluster isn't near the previous one, add it to best clusters
else:
best_clusters.append(cluster)

# 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
else:
start = gutter
else:
# Checking the gap between this cluster and the previous one
if gap:
this_gap = gap
else:

# 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
columns.append(mean(cluster))

# 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
break
#print(gutter)
#print(columns)
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

'''
Save the detected header as a separate image.
'''
# Where to save the image

# Crop the image using header value
# Numpy slicing - roi = im[y1:y2, x1:x2]

# Save the cropped image

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
try:
next_col = columns[index+1]
except IndexError:

# If there's no next column we've reached the end of the image, so do nothing
pass
else:

# Add a little to the margins of the image
if column > 20:
this_col = column - 20
else:
this_col = column

# Crop the image to the dimensions of the column

# 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:
#print(line)
x1,y1,x2,y2 = line[0]
cv2.line(img,(x1,y1),(x2,y2),(0,0,255),8)
#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.

Parameters:
image_name
image_path
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
'''

# Get image dimensions
try:
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...
else:

# 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

# Draw a grid on image (for debugging)
if grid:

# Draw detected column & header lines on image and save the results (for testing)
if markup:

# Draw gutter
cv2.line(img,(gutter,0),(gutter,h),(0,255,0),5)

# Draw columns
for column in columns:
cv2.line(img,(column,0),(column,h),(0,255,0),5)

# Save the annotated image
cv2.imwrite('{}/{}.jpg'.format(output_dir, image_name[:-4]), img)

# Otherwise crop & save columns and header
else:

# 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
# This is just to weed out dodgy images
try:
h, w = img.shape[:2]
except AttributeError:
print('Not a valid image')
new_h = 0
new_w = 0
columns = []
column_positions = ''
else:
if w > 5000:
img = resize(img, h, w)
new_h, new_w = img.shape[:2]
else:
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.
'''
years = df.groupby('year')
for year, files in years:
if int(year) >= start:
print(year)
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)
data_by_year(1950)

In [ ]: