path = '/Users/ginoprasad/Downloads/logo.png'
from matplotlib.pyplot import imshow
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
import scipy.ndimage
img = Image.open(path)
rgba = np.array(img.convert("RGBA"))
img
zeros = np.ones_like(np.array(rgba)[...,0])
center = np.array(zeros.shape) // 2
zeros[center[0],center[1]] = 0
distance_transform = scipy.ndimage.distance_transform_edt(zeros)
imshow(distance_transform)
<matplotlib.image.AxesImage at 0x7f80000e7d30>
distance_threshold = 223
crop = np.expand_dims(distance_transform < 225, 2)
imshow(crop)
plt.figure()
imshow(crop * rgba)
<matplotlib.image.AxesImage at 0x7f8000b9d1c0>
transparent = crop * rgba
transparent[...,:3] += (255 * (1 - crop)).astype(np.uint8)
imshow(transparent)
<matplotlib.image.AxesImage at 0x7f800027a610>
bounding_box = skimage.measure.regionprops(crop.astype(int))[0].slice
bounding_box = bounding_box[:-1] + (slice(0, 4, None),)
bounding_box
(slice(32, 481, None), slice(32, 481, None), slice(0, 4, None))
imshow(transparent[bounding_box])
<matplotlib.image.AxesImage at 0x7f80101d02b0>
processed = Image.fromarray(transparent[bounding_box])
processed.save('/Users/ginoprasad/Downloads/cropped_logo.png')
processed