Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import matplotlib.pyplot as plt
- import matplotlib.patches as mpatches
- import numpy as np
- from skimage.filters import threshold_otsu
- from skimage.segmentation import clear_border
- from skimage.measure import label, regionprops
- from skimage.morphology import opening, closing, square
- from skimage.color import label2rgb
- from skimage.color import rgb2gray
- image = rgb2gray(plt.imread('strongi.jpg'))[100:-100, 100:-100]
- # apply threshold
- thresh = threshold_otsu(image)
- #closing
- bw = closing(image > thresh, square(3))
- #opening
- bww = opening(bw, square(3))
- # remove artifacts connected to image border
- cleared = clear_border(bww)
- # label image regions
- cmap = plt.get_cmap("tab20")
- cmaps=np.array([cmap(i) for i in range(cmap.N)])
- label_image = label(cleared)
- image_label_overlay = label2rgb(label_image,colors=cmaps, image=image)
- fig, ax = plt.subplots(figsize=(8, 6))
- ax.imshow(image_label_overlay)
- for region in regionprops(label_image):
- # take regions with large enough areas
- if region.area >= 100:
- # draw rectangle around segmented coins
- minr, minc, maxr, maxc = region.bbox
- rect = mpatches.Rectangle((minc, minr), maxc - minc, maxr - minr,
- fill=False, edgecolor='g', linewidth=3)
- ax.add_patch(rect)
- ax.set_axis_off()
- plt.savefig('plot_label.jpg',dpi=100)
- plt.show()
- properties=regionprops(label_image)
- area=np.array([prop.area for prop in properties])
- label=np.array([prop.label for prop in properties])
- centroid=np.array([prop.centroid for prop in properties])
- area[area>100]
- #array([1457, 2554, 3155, 1579, 1315, 2929, 3919, 2849, 3943, 3706])
- label[area>100]
- #array([ 4, 6, 7, 8, 9, 16, 19, 20, 24, 26])
- centroid[area>100]
- """
- array([[ 77.65339739, 299.37062457],
- [132.5082224 , 149.93970243],
- [137.55847861, 250.30174326],
- [144.00379987, 78.81697277],
- [157.08745247, 316.88365019],
- [221.82963469, 184.11266644],
- [242.8532789 , 86.42817045],
- [242.07827308, 292.95998596],
- [299.91732184, 188.02967284],
- [323.8440367 , 273.36022666]])
- """
- img_c = plt.imread('strongi.jpg')[100:-100, 100:-100]
- sabos=[]
- for region in regionprops(label_image):
- if region.area >= 100:
- minr, minc, maxr, maxc = region.bbox
- sabo = img_c[minr:maxr,minc:maxc,:]
- sabos.append(sabo)
- from mpl_toolkits.axes_grid1 import ImageGrid
- fig = plt.figure(figsize=(8, 6))
- grid = ImageGrid(fig, 111,
- nrows_ncols=(2, 5),
- axes_pad=0.2,
- share_all=True,
- )
- for i in range(len(sabos)):
- grid[i].imshow(sabos[i])
- grid[i].axis('off')
- grid[i].set_title('label='+str(label[area>100][i])+'')
- plt.savefig('plot_label_cactus.jpg',dpi=123)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement