# -*- coding: UTF-8 -*- import numpy as np from scipy import ndimage def find_miny(mat,val = 1): (n,m) = mat.shape for i in range(0,n): for j in range(0,m): if mat[i,j] == val: return i return None def find_minx(mat,val = 1): (n,m) = mat.shape for j in range(0,m): for i in range(0,n): if mat[i,j] == val: return j return None def find_maxy(mat,val = 1): (n,m) = mat.shape for i in range(n-1,-1,-1): for j in range(m-1,-1,-1): if mat[i,j] == val: return i return None def find_maxx(mat,val = 1): (n,m) = mat.shape for j in range(m-1,-1,-1): for i in range(n-1,-1,-1): if mat[i,j] == val: return j return None def calc_image_crop(img, val = 255): minx = find_minx(img,val) maxx = find_maxx(img,val) miny = find_miny(img,val) maxy = find_maxy(img,val) return (minx,maxx,miny,maxy) def crop_image(img,val = 255): (minx,maxx,miny,maxy) = calc_image_crop(img,val) return img[miny:maxy,minx:maxx] def crop_image_prefilled(img,val = 255): (minx,maxx,miny,maxy) = calc_image_crop(img,val) img_filled = ndimage.binary_fill_holes(img) return img_filled[miny:maxy,minx:maxx] def dimension_rate(img): (n,m) = img.shape return float(m)/float(n) def image_to_mask(img,threshold = 128): m = img >= threshold return 1*m