Skip to content

Instantly share code, notes, and snippets.

@blvp
Last active September 8, 2016 15:46
Show Gist options
  • Select an option

  • Save blvp/969d7a318624ce45b842ca922ae03a78 to your computer and use it in GitHub Desktop.

Select an option

Save blvp/969d7a318624ce45b842ca922ae03a78 to your computer and use it in GitHub Desktop.
crop lecture notes that is written on white paper
import argparse as arg
import os
import cv2
import numpy as np
def generate_cropped_by_white(img_path):
img = cv2.imread(img_path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (35, 35), 0)
_, thr = cv2.threshold(blurred, 200, 255,
cv2.THRESH_BINARY + cv2.THRESH_OTSU)
contours, _ = cv2.findContours(thr.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
contour_areas = np.array(map(cv2.contourArea, contours))
max_contour = np.argmax(contour_areas, axis=0)
x, y, w, h = cv2.boundingRect(contours[max_contour])
img = img[y:y + h, x:x + w]
return img, img_path
if __name__ == '__main__':
parser = arg.ArgumentParser(usage="python this.py --images image1.png ~/Downloads/test.png --out ./test_dir")
parser.add_argument('image_paths', metavar='path', type=str, nargs='+', help='path to images separated with space')
parser.add_argument('--out', type=str, help='path to outputdir')
args = parser.parse_args()
for (cropped, orig_path) in map(generate_cropped_by_white, args.image_paths):
file_name = os.path.basename(orig_path)
print "proccess image %s" % file_name
cv2.imwrite(os.path.join(args.out, file_name + '.gen.jpg'), cropped)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment