Advertisement
Guest User

Untitled

a guest
Jul 17th, 2017
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.96 KB | None | 0 0
  1. import os, sys
  2. import numpy as np
  3. from scipy import ndimage as ndi
  4. from scipy.misc import imsave
  5. import matplotlib.pyplot as plt
  6.  
  7. from skimage.filters import sobel, threshold_local
  8. from skimage.morphology import watershed
  9. from skimage import io
  10.  
  11.  
  12. def open_image(name):
  13.     filename = os.path.join(os.getcwd(), name)
  14.     return io.imread(filename, as_grey=True)
  15.  
  16.  
  17. def adaptive_threshold(image):
  18.  
  19.     # Create threshold image
  20.     # Offset is not desirable for these images
  21.     block_size = 701
  22.     threshold_img = threshold_local(image, block_size)
  23.  
  24.     # Binarize the image with the threshold image
  25.     binary_adaptive = image < threshold_img
  26.  
  27.     # Convert the mask (which has dtype bool) to dtype int
  28.     # This is required for the code in `segmentize` (below) to work
  29.     binary_adaptive = binary_adaptive.astype(int)  
  30.  
  31.     # Return the binarized image
  32.     return binary_adaptive
  33.    
  34.    
  35. def segmentize(image):
  36.     # make segmentation using edge-detection and watershed
  37.     edges = sobel(image)
  38.     markers = np.zeros_like(image)
  39.     foreground, background = 1, 2
  40.     markers[image == 0] = background
  41.     markers[image == 1] = foreground
  42.  
  43.     ws = watershed(edges, markers)
  44.  
  45.     return ndi.label(ws == foreground)
  46.  
  47.  
  48. def find_segment(segments, index):
  49.     segment = np.where(segments == index)
  50.     shape = segments.shape
  51.  
  52.     minx, maxx = max(segment[0].min() - 1, 0), min(segment[0].max() + 1, shape[0])  
  53.     miny, maxy = max(segment[1].min() - 1, 0), min(segment[1].max() + 1, shape[1])
  54.  
  55.     im = segments[minx:maxx, miny:maxy] == index
  56.  
  57.     return (np.sum(im), np.invert(im))
  58.  
  59.  
  60. def run(f):
  61.     print('Processing:', f)
  62.  
  63.     image = open_image(f)
  64.     processed = adaptive_threshold(image)
  65.     segments = segmentize(processed)
  66.  
  67.     print('Segments detected:', segments[1])
  68.  
  69.     seg = []
  70.     for s in range(1, segments[1]):
  71.         seg.append(find_segment(segments[0], s))
  72.  
  73.     seg.sort(key=lambda s: -s[0])
  74.  
  75.      # Get the directory name (if a full path is given)
  76.     folder = r'C:\Users\yourname\Desktop\sketch2\data'
  77.  
  78.     # Get the file name
  79.     filenm = os.path.basename(f)
  80.  
  81.     # If it doesn't already exist, create a new dir "segments"
  82.     # to save the PNGs
  83.     segments_folder = os.path.join(folder,filenm[:-4]+"_segments")
  84.     os.path.isdir(segments_folder) or os.mkdir(segments_folder)
  85.  
  86.     # Save the segments to the "segments" directory
  87.     for i in range(len(seg)):
  88.          # Create an MxNx4 array (RGBA)
  89.         seg_rgba = np.zeros((seg[i][1].shape[0],seg[i][1].shape[1],4),dtype=np.bool)
  90.  
  91.         # Fill R, G and B with copies of the image
  92.         for c in range(3):
  93.             seg_rgba[:,:,c] = seg[i][1]
  94.  
  95.         # For A (alpha), use the invert of the image (so background is 0=transparent)
  96.         seg_rgba[:,:,3] = ~seg[i][1]
  97.  
  98.         # Save image
  99.         imsave(os.path.join(segments_folder, filenm[:-4] + '_' + str(i) + '.png'), seg_rgba)
  100.  
  101. for f in sys.argv[1:]:
  102.     run(f)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement