In [46]:
path = '/Users/ginoprasad/Downloads/logo.png'
In [47]:
from matplotlib.pyplot import imshow
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
import scipy.ndimage
In [64]:
img = Image.open(path)
rgba = np.array(img.convert("RGBA"))
In [66]:
img
Out[66]:
Distance Transform for Cropping¶
In [59]:
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)
In [63]:
imshow(distance_transform)
Out[63]:
<matplotlib.image.AxesImage at 0x7f80000e7d30>
In [118]:
distance_threshold = 223
In [119]:
crop = np.expand_dims(distance_transform < 225, 2)
imshow(crop)
plt.figure()
imshow(crop * rgba)
Out[119]:
<matplotlib.image.AxesImage at 0x7f8000b9d1c0>
Making Background Region Transparent¶
In [120]:
transparent = crop * rgba
transparent[...,:3] += (255 * (1 - crop)).astype(np.uint8)
imshow(transparent)
Out[120]:
<matplotlib.image.AxesImage at 0x7f800027a610>
Cropping Out Background¶
In [121]:
bounding_box = skimage.measure.regionprops(crop.astype(int))[0].slice
bounding_box = bounding_box[:-1] + (slice(0, 4, None),)
bounding_box
Out[121]:
(slice(32, 481, None), slice(32, 481, None), slice(0, 4, None))
In [122]:
imshow(transparent[bounding_box])
Out[122]:
<matplotlib.image.AxesImage at 0x7f80101d02b0>
In [124]:
processed = Image.fromarray(transparent[bounding_box])
processed.save('/Users/ginoprasad/Downloads/cropped_logo.png')
processed
Out[124]:
In [ ]: