Skip to content

Instantly share code, notes, and snippets.

@jakekara
Created September 5, 2019 13:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jakekara/ec9930687dc4366ed73e3d1ca1b343e8 to your computer and use it in GitHub Desktop.
Save jakekara/ec9930687dc4366ed73e3d1ca1b343e8 to your computer and use it in GitHub Desktop.
Simple approach to crop the margins of an image
import numpy as np
import cv2
# use the crop_image() function at the bottom. The rest are pretty much helpers.
# works well enough with William Blake illuminated books that I didn't have to
# try anything more sophisticated
def read_image(path):
return cv2.cvtColor(cv2.imread(path), cv2.COLOR_RGB2BGR)
def crop_line(img, x,y,w, h):
return img[y:y+h, x:x+w]
def crop_horizontal_line(img, x, y, width, thickness=1):
return crop_line(img, x, y, width, thickness)
def crop_vertical_line(img, x, y, height, thickness=1):
return crop_line(img, x, y, thickness, height)
def crop_border(img, x1, y1, x2, y2, thickness=1):
width = x2 - x1
height = y2 - y1
top = crop_horizontal_line(img, x1, y1, width, thickness=thickness)
bottom = crop_horizontal_line(img, x1, y1 + height, width, thickness=thickness)
left = crop_vertical_line(img, x1, y1, height, thickness=thickness)
right = crop_vertical_line(img, x1 + width, y1, height, thickness=thickness)
return {
"top": top.std(),
"bottom": bottom.std(),
"left": left.std(),
"right": right.std(),
#"img": img[y1:y1+height, x1:x1+width]
}
def find_image(img, thresh=20):
w = img.shape[1]
h = img.shape[0]
x1 = int(w / 2) - 50
x2 = int(w / 2) + 50
y1 = int(h / 2) - 50
y2 = int(h / 2) + 50
while True:
devs = crop_border(img, x1, y1, x2, y2)
#print (x1, y1, x2, y2, w, h)
#print (devs)
changed = False
if devs["top"] > thresh:
if y1 - 1 >= 0:
y1 -= 1
changed = True
if devs["bottom"] > thresh:
if y2 + 1 < h:
y2 = min(h, y2 + 1)
changed = True
if devs["left"] > thresh:
if x1 - 1 >= 0:
x1 = max(0, x1 - 1)
changed = True
if devs["right"] > thresh:
if x2 + 1 < w:
x2 = min(w, x2 + 1)
changed = True
if not changed:
break
#print (x1,x2)
return {"x":x1, "y":y1, "w":x2 - x1,"h": y2 - y1}
def crop_image(img, thresh=20):
d = find_image(img, thresh=thresh)
return img[d["y"]:d["y"]+d["h"],d["x"]:d["x"] + d["w"]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment