Skip to content

Instantly share code, notes, and snippets.

@postylem
Created October 26, 2019 23:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save postylem/3e15e0009bce563f86e888c26ad0eefe to your computer and use it in GitHub Desktop.
Save postylem/3e15e0009bce563f86e888c26ad0eefe to your computer and use it in GitHub Desktop.
from skimage.measure import regionprops, label
def crop_image(x, threshold=230, plot=True):
'''
finds large connected components using skimage.measure.label,
and displays them with matplotlib.pyplot.
'''
im = train_images[x]
mask = np.where(im > threshold, 1, 0)
# now get label_im, a version of the thresholded image, but
# where insted of being 1 or 0, each connected component
# has a different integer value "label"
label_im = label(mask, connectivity=2) # could also be 1-connectivity...
# this is useful: skimage.measure.regionprops will let us measure area
regions = regionprops(label_im)
if plot == True:
print('Image number',x,'... True answer',train_y[x])
fig, axs = plt.subplots(1,2)
axs[0].imshow(im,cmap=plt.cm.gray_r)
axs[1].imshow(label_im,cmap=plt.cm.magma_r)
plt.show()
for region in regions:
if region['Area'] < 50:
continue
miny, minx, maxy, maxx = region['BoundingBox']
# get centre
cx, cy = int((minx+maxx)/2), int((miny+maxy)/2)
plt.figure(figsize=(1, 1))
# if bounding box will go outside image, then shift
if cx < 14:
shift = 14 - cx
cx += shift
if cy < 14:
shift = 14 - cy
cy += shift
# show the found numerals (just by cropping label_im)
if plot == True:
plt.imshow(label_im[cy-14:cy+14, cx-14:cx+14],cmap=plt.cm.gray_r)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment