Advertisement
dan-masek

Untitled

Jun 9th, 2019
302
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.35 KB | None | 0 0
  1. from cv2_41 import cv2
  2. import os
  3. import numpy as np
  4. import time
  5.  
  6. t = time.time()
  7.  
  8. img = cv2.imread('test.jpg')
  9. print "Initial img shape:", img.shape
  10.  
  11. for _ in range(0, 3):
  12.     img = cv2.pyrDown(img)
  13.  
  14. print "Reduced img shape:", img.shape
  15.  
  16. img_super = cv2.ximgproc.createSuperpixelSLIC(img, cv2.ximgproc.MSLIC, 100, 10.0)
  17. img_super.iterate(3)
  18.  
  19. labels = img_super.getLabels() # No need to pre-allocate here
  20.  
  21. superpixel_count = img_super.getNumberOfSuperpixels();
  22. print "Superpixel count:", superpixel_count
  23.  
  24. super_pixelized = np.zeros_like(img)
  25.  
  26. mask = np.zeros(img.shape[:2], np.uint8) # Here it seems to make more sense to pre-alloc and reuse
  27. for label in range(0, superpixel_count):
  28.     cv2.inRange(labels, label, label, dst=mask)
  29.    
  30.     # Find the bounding box of this label
  31.     x,y,w,h = cv2.boundingRect(mask)
  32.    
  33.     # Work only on the rectangular region containing the label
  34.     mask_roi = mask[y:y+h,x:x+w]
  35.     img_roi = img[y:y+h,x:x+w]
  36.    
  37.     # Per-channel mean of the masked pixels (we're usingo BGR, so we drop the useless 4th channel it gives us)
  38.     roi_mean = cv2.mean(img_roi, mask_roi)[:3]
  39.  
  40.     # Set all masked pixels in the ROI of the target image the the mean colour
  41.     super_pixelized[y:y+h,x:x+w][mask_roi != 0] = roi_mean
  42.  
  43. cv2.imwrite("superpix.png", super_pixelized)
  44.  
  45. print "TOTAL TIME:", (time.time() - t)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement