Guest User

ImgClusterDemo

a guest
May 10th, 2013
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.48 KB | None | 0 0
  1. import cv2
  2. import numpy as np
  3. from sklearn import preprocessing
  4. import sklearn.cluster
  5.  
  6.  
  7. DEFAULT_PARAMS = {
  8.     #good features to track parmas
  9.     "maxCorners":100,
  10.     "qualityLevel":0.001,
  11.     "minDistance":1,
  12.  
  13.  
  14.     "filter_depth":2, #distance to expand pyramids
  15.  
  16.     #optic flow LK params
  17.     "winSize":10,
  18.     "patchSize":10,
  19.  
  20.  
  21.     "corner_block_min":2,
  22.     "corner_block_max":10,
  23.  
  24.     "open_windows":False,
  25.  
  26.     "tracked_noise":10,
  27.     "ransac":10,
  28.  
  29.     "resamples":3,
  30.  
  31.     "threshold_abs":0,
  32.     "threshold_rel":0.1,
  33.     "num_peaks" :10000,
  34.  
  35.  
  36.     "random_comparison_projection":False,
  37.     "projection_seed":2,
  38. }
  39.  
  40.  
  41. def featureVectors(img, img_dict, coords, params=DEFAULT_PARAMS):
  42.     if coords.shape == (2,):
  43.         single =True
  44.         N = 1
  45.         coords = np.array([coords.astype(np.int16)])
  46.     else:
  47.         single = False
  48.         N = coords.shape[0]
  49.  
  50.     #lazy build corner images when needed
  51.     if not "corner_stack" in img_dict:
  52.         img_dict["corner_stack"] = []
  53.  
  54.         for block_size in range(params["corner_block_min"], params["corner_block_max"]):
  55.  
  56.             img_dict["corner_stack"].append(
  57.                 cv2.cornerMinEigenVal(
  58.                     src=img,
  59.                     blockSize=block_size,
  60.                 )
  61.             )
  62.  
  63.     n_features = 1 + len(img_dict["corner_stack"])
  64.     result = np.zeros( (N, n_features))
  65.  
  66.     cursor = 0
  67.  
  68.     #add coordinate of sample
  69.     #result = coord.copy()
  70.     #add intensite of point
  71.     result[:, cursor] = img[coords[:,1], coords[:,0]]
  72.     cursor += 1
  73.  
  74.     for corner_img in img_dict["corner_stack"]:
  75.         result[:, cursor] = corner_img[coords[:,1], coords[:,0]]
  76.         cursor += 1
  77.  
  78.     if single:
  79.         return result[0]
  80.     return result
  81.  
  82.  
  83. def all_features(cv_img, dtype=None):
  84.  
  85.     all =  np.vstack(np.mgrid[:cv_img.shape[1],:cv_img.shape[0]].T)
  86.  
  87.     if dtype == None:
  88.         return all.astype(np.float32)
  89.     elif dtype==np.int32:
  90.         return all.astype(np.int32)
  91.  
  92.  
  93. class Clusterer:
  94.     def __init__(self, img, clusters = 8, params=DEFAULT_PARAMS):
  95.  
  96.         img_dict = {}
  97.         #print all_features(img, params)
  98.         Xraw = featureVectors(img, img_dict, all_features(img, dtype=np.int32), params)
  99.  
  100.         self.scaler = preprocessing.Scaler().fit(Xraw)
  101.         X = self.scaler.transform(Xraw)
  102.  
  103.         self.clusters = clusters
  104.  
  105.         self.cluster = sklearn.cluster.MiniBatchKMeans(
  106.             k=self.clusters,
  107.             init='k-means++',
  108.             max_iter=100,
  109.             batch_size=100,
  110.             verbose=0,
  111.             compute_labels=True,
  112.             random_state=None,
  113.             tol=0.0,
  114.             max_no_improvement=10,
  115.             init_size=None,
  116.             n_init=3,
  117.             chunk_size=None
  118.         )
  119.  
  120.         self.cluster.fit(X)
  121.  
  122.     def label(self, img, windowname="labels", params=DEFAULT_PARAMS):
  123.         label_img = np.zeros(img.shape, dtype=np.uint8)
  124.         img_dict = {}
  125.         counts = np.zeros(self.clusters)
  126.  
  127.         coords = all_features(img, dtype=np.int32)
  128.         f = featureVectors(img, img_dict, coords, params)
  129.         fx = self.scaler.transform(f)
  130.         labels = self.cluster.predict(fx)
  131.  
  132.         label_img[coords[:,1], coords[:, 0]] = labels[:] * (255/self.clusters)
  133.  
  134.         if "open_windows" in params:
  135.             cv2.imshow(windowname, label_img)
  136.  
  137.         for label in range(self.clusters):
  138.             counts[label] = np.count_nonzero(labels==label)
  139.  
  140.         return (label_img, counts)
  141.  
  142.     def labelOnly(self, img, groups, windowname="labels", update=False, params=DEFAULT_PARAMS):
  143.         label_img = np.zeros(img.shape, dtype=np.uint8)
  144.         img_dict = {}
  145.  
  146.         coords = all_features(img, dtype=np.int32)
  147.         f = featureVectors(img, img_dict, coords, params)
  148.         fx = self.scaler.transform(f)
  149.  
  150.         if update:
  151.             self.cluster.partial_fit(fx)
  152.  
  153.         labels = self.cluster.predict(fx)
  154.  
  155.         for group_index, group in enumerate(groups):
  156.             indeces = np.where(labels[:] == group)
  157.             label_img[coords[indeces,1], coords[indeces, 0]] = ((group_index+1) * (255/(len(groups)+1)))
  158.  
  159.         if "open_windows" in params:
  160.             cv2.imshow(windowname, label_img)
  161.  
  162.         return label_img
  163.  
  164.  
  165.  
  166. def cluster_behaviour_demo():
  167.     img1 = cv2.pyrDown(cv2.imread("/home/tom/development/hw/git/ros/sonar_processing/training_data/cleaned_sauce/frame0108.jpg", flags=cv2.CV_LOAD_IMAGE_GRAYSCALE))
  168.     img2 = cv2.pyrDown(cv2.imread("/home/tom/development/hw/git/ros/sonar_processing/training_data/cleaned_sauce/frame0109.jpg", flags=cv2.CV_LOAD_IMAGE_GRAYSCALE))
  169.  
  170.     combined = np.hstack([img1, img2])[:-10,:]
  171.  
  172.     cv2.imshow("raw", combined)
  173.  
  174.     clusterer = Clusterer(combined)
  175.  
  176.     (fully_labelled, counts)= clusterer.label(combined, windowname="cluster")
  177.  
  178.     selection =  counts.argsort()[0:4] #get 3 smallest
  179.  
  180.     labelled = clusterer.labelOnly(combined, selection)
  181.  
  182.     print "pre skel", np.unique(labelled)
  183.  
  184.  
  185. if __name__ == "__main__":
  186.     cluster_behaviour_demo()
  187.  
  188.  
  189.     print "press escape or something on a focused openCV window to exit"
  190.     cv2.waitKey()
Advertisement
Add Comment
Please, Sign In to add comment