Last active
November 27, 2021 21:00
-
-
Save anglilian/af0b4a5c6a4caeee64ad019c66a8efff to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def white_band(img, side): | |
""" | |
Determine best position to crop image | |
Parameters: | |
img (array): Binarised and skew corrected image | |
type (str) : Side of image to crop (top, bottom, center, left or right) | |
Returns: | |
(int): Position on image to crop | |
""" | |
h, w, c = img.shape | |
pixel_size = 1 | |
if side in ["top", "bottom"]: | |
# Calculate white pixels at each slice | |
hist = np.sum(img/255, axis=1)[:, 0] | |
y = np.add.reduceat(hist, np.arange(0, len(hist), pixel_size)) | |
x = np.arange(0, len(hist),pixel_size) | |
# Select indices to analyse image at specific area | |
if side == "top": | |
ind = x[x<h*0.2] | |
elif side == "bottom": | |
ind = x[x>h*0.8] | |
elif side == "center": | |
# Calculate white pixels at each slice | |
hist = np.sum(img/255, axis=0)[:, 0] | |
y = np.add.reduceat(hist, np.arange(0, len(hist), pixel_size)) | |
x = np.arange(0, len(hist), pixel_size) | |
# Select indices to analyse image at specific area | |
ind = x[np.logical_and(x<w*0.7, x>w*0.3)] | |
elif side in ["right", "left"]: | |
# Calculate white pixels at each slice | |
hist = np.sum(img/255, axis=0)[:, 0] | |
y = np.add.reduceat(hist, np.arange(0, len(hist), pixel_size)) | |
x = np.arange(0, len(hist),pixel_size) | |
# Select indices to analyse image at specific area | |
if side == "left": | |
ind = x[x<w*0.2] | |
elif side == "right": | |
ind = x[x>w*0.8] | |
else: | |
raise ValueError('Wrong side input') | |
grd = np.gradient(y[ind]) | |
grd[np.logical_and(grd<np.std(grd)/2, grd>-np.std(grd)/2)] = 0 # Flatten noise within half sd | |
nonzero = np.where(np.diff(grd)!=0)[0] # Determine largest white band | |
crop = np.mean([nonzero[np.argmax(np.diff(nonzero))+1], | |
nonzero[np.argmax(np.diff(nonzero))]]) # Center of white band | |
return round(crop+ind[0]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment