In [27]:
%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

import skimage as ski
import skimage.transform
import skimage.color

from skimage import data
from skimage.filters import threshold_otsu,threshold_adaptive
from skimage.segmentation import clear_border
from skimage.measure import label, regionprops
from skimage.morphology import closing, square
from skimage.color import label2rgb

In [122]:
image = ski.io.imread('test_img.bmp')
image=ski.transform.resize(image,(900,1600))
image_gray=ski.color.rgb2gray(image)
def imshow(img):
    im=ski.color.gray2rgb(img)
    plt.imshow(im)
plt.imshow(image)


Out[122]:
<matplotlib.image.AxesImage at 0x1d031a964a8>

In [121]:
# apply threshold
thresh = threshold_otsu(image_gray)
# thresh = threshold_adaptive(image_gray,51)
thresh = image_gray > thresh
# thresh = ski.color.rgb2gray(thresh)
imshow(thresh)
bw = closing(thresh, square(3))
# imshow(bw)
# # remove artifacts connected to image border
cleared = clear_border(bw)
# imshow(cleared)



In [88]:
# label image regions
label_image = label(thresh)
imshow(label_image)
# image_label_overlay = label2rgb(label_image, image=image_gray)



In [102]:
fig, ax = plt.subplots(figsize=(10, 6))
ax.imshow(ski.color.gray2rgb(label_image))
# label_image=thresh
for region in regionprops(label_image):
    # take regions with large enough areas
    if region.area >= 50:
        # draw rectangle around segmented coins
        print(region.bbox)
        minr, minc,_, maxr, maxc,_ = list(region.bbox)
        rect = mpatches.Rectangle((minc, minr), maxc - minc, maxr - minr,
                                  fill=False, edgecolor='red', linewidth=2)
        ax.add_patch(rect)

# ax.set_axis_off()
plt.tight_layout()
plt.show()


(0, 0, 0, 900, 1600, 3)
(609, 774, 0, 628, 776, 3)
(619, 905, 0, 651, 1008, 2)
(622, 1004, 0, 646, 1054, 2)
(627, 845, 0, 645, 874, 1)
(661, 1169, 0, 667, 1190, 1)

In [ ]: