def clustering(path, amount, threshold, expected, ccore, **kwargs): metric = kwargs.get('metric', distance_metric(type_metric.EUCLIDEAN)) sample = read_sample(path) bsas_instance = bsas(sample, amount, threshold, ccore=ccore, metric=metric) bsas_instance.process() clusters = bsas_instance.get_clusters() representatives = bsas_instance.get_representatives() obtained_length = 0 obtained_cluster_length = [] for cluster in clusters: obtained_length += len(cluster) obtained_cluster_length.append(len(cluster)) assertion.eq(len(sample), obtained_length) assertion.eq(len(expected), len(clusters)) assertion.eq(len(expected), len(representatives)) assertion.ge(amount, len(clusters)) dimension = len(sample[0]) for rep in representatives: assertion.eq(dimension, len(rep)) expected.sort() obtained_cluster_length.sort() assertion.eq(expected, obtained_cluster_length)
def visualizing(path, amount, threshold, ccore): sample = read_sample(path) bsas_instance = bsas(sample, amount, threshold, ccore=ccore) bsas_instance.process() bsas_visualizer.show_clusters(sample, bsas_instance.get_clusters(), bsas_instance.get_representatives())
def setup(self, **keywords): """ Setup the algorithms """ self._init_() for key in keywords.keys(): setattr(self, key, keywords[key]) if self.method == "bsas": self.obj = bsas(self.data_list, self.maximum_clusters, self.threshold1, ccore=self.ccore) if self.method == "mbsas": self.obj = mbsas(self.data_list, self.maximum_clusters, self.threshold1, ccore=self.ccore) if self.method == "ttsas": self.obj = ttsas(self.data_list, self.threshold1, self.threshold2, ccore=self.ccore) if self.method == "clarans": self.obj = clarans(self.data_list, self.n_clusters, self.numlocal, self.maxneighbor) return
def detect(self,frame): # This function uses the BSAS function in the pyclustering package # in https://github.com/annoviko/pyclustering/. Thereafter, we use # blob detection from OpenCV package to extract each marker's center. self.cms=[] self.image_ROIs=[] self.keypoints=[] img_gray=cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) ret,img_thresh = cv2.threshold(img_gray,100,255,cv2.THRESH_BINARY) self.nonzro_samples = cv2.findNonZero(img_thresh) if self.nonzro_samples is None: return None else: self.nonzro_samples=self.nonzro_samples.reshape(-1, 2).astype('float32') bsas_instance = bsas(self.nonzro_samples, self.max_clusters, self.threshold) bsas_instance.process() clusters = bsas_instance.get_clusters() self.ROIs=np.zeros((len(clusters),4)) for i,cluster in enumerate(clusters): current_batch=self.nonzro_samples[cluster] self.cms.append(np.sum(current_batch,axis=0)/current_batch.shape[0]) row_max=np.max(current_batch[:,1],axis=0)+6 row_min=np.min(current_batch[:,1],axis=0)-6 col_max=np.max(current_batch[:,0],axis=0)+6 col_min=np.min(current_batch[:,0],axis=0)-6 self.ROIs[i,:]=[row_min,row_max,col_min,col_max] for roi in self.ROIs.astype('int32'): self.image_ROIs.append(img_gray.copy()[roi[0]:roi[1],roi[2]:roi[3]]) marker_points=[] for i,roi in enumerate(self.image_ROIs): keys_in_roi=self.blubDetector.detect(roi) for key in keys_in_roi: marker_points.append([key.pt[0]+self.ROIs.astype('float32')[i,2],key.pt[1]+self.ROIs.astype('float32')[i,0]]) return np.array(marker_points)
def clustering(path, amount, threshold, expected, ccore, **kwargs): metric = kwargs.get('metric', distance_metric(type_metric.EUCLIDEAN)); sample = read_sample(path); bsas_instance = bsas(sample, amount, threshold, ccore=ccore, metric=metric); bsas_instance.process(); clusters = bsas_instance.get_clusters(); representatives = bsas_instance.get_representatives(); obtained_length = 0; obtained_cluster_length = []; for cluster in clusters: obtained_length += len(cluster); obtained_cluster_length.append(len(cluster)); assertion.eq(len(sample), obtained_length); assertion.eq(len(expected), len(clusters)); assertion.eq(len(expected), len(representatives)); assertion.ge(amount, len(clusters)); dimension = len(sample[0]); for rep in representatives: assertion.eq(dimension, len(rep)); expected.sort(); obtained_cluster_length.sort(); assertion.eq(expected, obtained_cluster_length);
def process_bsas(self, img_thresh): bsas_instance = bsas(self.nonzro_samples, self.max_clusters, self.threshold) bsas_instance.process() clusters = bsas_instance.get_clusters() #Calculate the center of the clusters and the Regions of Interests self.ROIs = np.zeros((len(clusters), 4)) for i, cluster in enumerate(clusters): current_batch = self.nonzro_samples[cluster] self.cms.append( np.sum(current_batch, axis=0) / current_batch.shape[0]) row_max = np.max(current_batch[:, 1], axis=0) + 6 row_min = np.min(current_batch[:, 1], axis=0) - 6 col_max = np.max(current_batch[:, 0], axis=0) + 6 col_min = np.min(current_batch[:, 0], axis=0) - 6 self.ROIs[i, :] = [row_min, row_max, col_min, col_max] for roi in self.ROIs.astype('int32'): self.image_ROIs.append(img_thresh.copy()[roi[0]:roi[1], roi[2]:roi[3]]) #Return The Results marker_points = [] for i, roi in enumerate(self.image_ROIs): keys_in_roi = self.blubDetector.detect(roi) for key in keys_in_roi: #Calculate the global coordinate of marker points. #The points are returned in (X(Col),Y(Row)) coordinate. marker_points.append([key.pt[0]+self.ROIs.astype('float32')\ [i,2],key.pt[1]+self.ROIs.astype('float32')[i,0]]) return 0, np.array(marker_points)
def run(self): #self.gray = cv2.cvtColor(self.frame, cv2.COLOR_BGR2GRAY) ret, img = cv2.threshold(cv2.cvtColor(self.frame, cv2.COLOR_GRAY2BGR), 180, 255, cv2.THRESH_BINARY) sample = cv2.findNonZero(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)).reshape( -1, 2) print(len(sample)) bsas_instance = bsas(sample, self.max_clusters, self.threshold) bsas_instance.process() clusters = bsas_instance.get_clusters() representatives = bsas_instance.get_representatives() self.cls = [] self.bnd = [] for cluster in clusters: sum = np.array([0, 0], dtype=np.float32) pts = [] for i in cluster: pts.append(list(sample[i])) sum += sample[i] cls_pts = np.vstack( (pts[np.where( np.array(pts)[:, 0] == np.max(np.array(pts)[:, 0]))[0][0]], pts[np.where( np.array(pts)[:, 0] == np.min(np.array(pts)[:, 0]))[0][0]], pts[np.where( np.array(pts)[:, 1] == np.max(np.array(pts)[:, 1]))[0][0]], pts[np.where( np.array(pts)[:, 1] == np.min(np.array(pts)[:, 1]))[0][0]])) self.bnd.append([ np.min(cls_pts[:, 0]), np.min(cls_pts[:, 1]), np.max(cls_pts[:, 0]) - np.min(cls_pts[:, 0]), np.max(cls_pts[:, 1]) - np.min(cls_pts[:, 1]) ]) sum = sum / len(cluster) self.cls.append(sum) self.cls = np.array(self.cls).reshape(-1, 2) print(len(self.cls)) #self.log.append(self.LED.reshape(1, -1)) if self.camCounter > 1000: self.videoStream.release() #np.savetxt('log.csv', self.log) #else: #self.videoStream.write(cv2.cvtColor(self.frame, cv2.COLOR_GRAY2BGR)) self.camCounter = self.camCounter + 1
def template_clustering(path, amount, threshold, **kwargs): metric = kwargs.get('metric', distance_metric(type_metric.EUCLIDEAN_SQUARE)); ccore = kwargs.get('ccore', False); draw = kwargs.get('draw', True); sample = read_sample(path); print("Sample: ", path); bsas_instance = bsas(sample, amount, threshold, ccore=ccore, metric=metric); bsas_instance.process(); clusters = bsas_instance.get_clusters(); representatives = bsas_instance.get_representatives(); if draw is True: bsas_visualizer.show_clusters(sample, clusters, representatives);
def template_clustering(path, amount, threshold, **kwargs): metric = kwargs.get('metric', distance_metric(type_metric.EUCLIDEAN_SQUARE)) ccore = kwargs.get('ccore', False) draw = kwargs.get('draw', True) sample = read_sample(path) print("Sample: ", path) bsas_instance = bsas(sample, amount, threshold, ccore=ccore, metric=metric) bsas_instance.process() clusters = bsas_instance.get_clusters() representatives = bsas_instance.get_representatives() if draw is True: bsas_visualizer.show_clusters(sample, clusters, representatives)
def detect(self, frame): self.cms = [] self.image_ROIs = [] self.keypoints = [] img_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) ret, img_thresh = cv2.threshold(img_gray, 100, 255, cv2.THRESH_TOZERO) #Find the clusters self.nonzro_samples = cv2.findNonZero(img_thresh) if self.nonzro_samples is None: return None else: self.nonzro_samples = self.nonzro_samples.reshape( -1, 2).astype('float32') bsas_instance = bsas(self.nonzro_samples, self.max_clusters, self.threshold) bsas_instance.process() clusters = bsas_instance.get_clusters() #Calculate the center of the clusters and the Regions of Interests self.ROIs = np.zeros((len(clusters), 4)) for i, cluster in enumerate(clusters): current_batch = self.nonzro_samples[cluster] self.cms.append( np.sum(current_batch, axis=0) / current_batch.shape[0]) row_max = np.max(current_batch[:, 1], axis=0) + 6 row_min = np.min(current_batch[:, 1], axis=0) - 6 col_max = np.max(current_batch[:, 0], axis=0) + 6 col_min = np.min(current_batch[:, 0], axis=0) - 6 self.ROIs[i, :] = [row_min, row_max, col_min, col_max] for roi in self.ROIs.astype('int32'): self.image_ROIs.append(img_thresh.copy()[roi[0]:roi[1], roi[2]:roi[3]]) #Return The Results marker_points = [] for i, roi in enumerate(self.image_ROIs): keys_in_roi = self.blubDetector.detect(roi) for key in keys_in_roi: #Calculate the global coordinate of marker points. The points are returned in (X(Col),Y(Row)) coordinate. marker_points.append([ key.pt[0] + self.ROIs.astype('float32')[i, 2], key.pt[1] + self.ROIs.astype('float32')[i, 0] ]) return np.array(marker_points)
def Clustering(images): i = 0 data_bsas = [] for img in images: i += 1 #img = NormalizeHist(img) img = cv2.medianBlur(img, 5) array = np.asarray(img) temp = [] for subarray in array: for element in subarray: if (element[0] + element[1] + element[2]) / 3 > 10: temp.append(element) temp = np.asarray(temp) arr = (temp.astype(float)) / 255.0 img_hsv = colors.rgb_to_hsv(arr[..., :3]) lu1 = img_hsv[..., 0].flatten() list = plt.hist(lu1 * 360, bins=360, range=(0.0, 360.0)) toshow = [] sum = 0 for element in list[0]: sum += element #""" for element in list[0]: if 100 * element / sum > 0: toshow.append(1) else: toshow.append(0) #""" #for element in list[0]: #toshow.append(100 * element / sum) #for element in list[0]: #toshow.append(int(element)) name = 'C:/results/' + str(i) + ' plot' plt.savefig(name) #plt.show() plt.cla() data_bsas.append(toshow) ComputeDistance(data_bsas) #""" from pyclustering.cluster.bsas import bsas, bsas_visualizer from pyclustering.utils import read_sample from pyclustering.samples.definitions import SIMPLE_SAMPLES max_clusters = 3 threshold = 1.0 bsas_instance = bsas(data_bsas, max_clusters, threshold, 'euclidean') bsas_instance.process() clusters = bsas_instance.get_clusters() representatives = bsas_instance.get_representatives() print (clusters)
def run(self): #self.gray = cv2.cvtColor(self.frame, cv2.COLOR_BGR2GRAY) ret, img = cv2.threshold(cv2.cvtColor(self.frame, cv2.COLOR_GRAY2BGR), 230, 255, cv2.THRESH_BINARY) sample = cv2.findNonZero(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)).reshape( -1, 2) bsas_instance = bsas(sample, self.max_clusters, self.threshold) bsas_instance.process() clusters = bsas_instance.get_clusters() representatives = bsas_instance.get_representatives() self.cls = [] self.bnd = [] for cluster in clusters: sum = np.array([0, 0], dtype=np.float32) pts = [] for i in cluster: pts.append(list(sample[i])) sum += sample[i] cls_pts = np.vstack( (pts[np.where( np.array(pts)[:, 0] == np.max(np.array(pts)[:, 0]))[0][0]], pts[np.where( np.array(pts)[:, 0] == np.min(np.array(pts)[:, 0]))[0][0]], pts[np.where( np.array(pts)[:, 1] == np.max(np.array(pts)[:, 1]))[0][0]], pts[np.where( np.array(pts)[:, 1] == np.min(np.array(pts)[:, 1]))[0][0]])) self.bnd.append([ np.min(cls_pts[:, 0]), np.min(cls_pts[:, 1]), np.max(cls_pts[:, 0]) - np.min(cls_pts[:, 0]), np.max(cls_pts[:, 1]) - np.min(cls_pts[:, 1]) ]) for i in range(len(self.bnd)): img = self.frame[(self.bnd[i][1] - 6):self.bnd[i][1] + self.bnd[i][3] + 6, self.bnd[i][0] - 6:(self.bnd[i][0] + 6 + self.bnd[i][2])] img = cv2.medianBlur(img, 5) cv2.imwrite('deb.jpg', img) keypoints = self.detector.detect(img) for key in keypoints: print( list( np.array(key.pt) + np.array([self.bnd[i][0], self.bnd[i][1]]))) self.cls.append( list( np.array(key.pt) + np.array([self.bnd[i][0], self.bnd[i][1]]))) self.cls = np.array(self.cls).reshape(-1, 2) print("%%%%%%%%%%%%%%") #self.log.append(self.LED.reshape(1, -1)) if self.camCounter == 1000: for _ in range(10): print("RELEASED") self.videoStream.release() #np.savetxt('log.csv', self.log) #else: #self.videoStream.write(cv2.cvtColor(self.frame, cv2.COLOR_GRAY2BGR)) self.camCounter = self.camCounter + 1
def visualizing(path, amount, threshold, ccore): sample = read_sample(path); bsas_instance = bsas(sample, amount, threshold, ccore=ccore); bsas_instance.process(); bsas_visualizer.show_clusters(sample, bsas_instance.get_clusters(), bsas_instance.get_representatives());