我们从Python开源项目中,提取了以下11个代码示例,用于说明如何使用skimage.morphology.label()。
def load_dict_from_file(filepath): if not os.path.isfile(filepath): print("No SpeedSegments database found at file '%s'. Initializing database empty." % (filepath,)) return dict() else: lines = open(filepath, "r").readlines() #lines = [line.strip().split("\t") for line in lines] lines = [line.strip() for line in lines] segments = dict() nb_found = 0 nb_labeled = 0 #segments_found_keys = set() #segments_found = [] for line in lines: seg = SpeedSegment.from_string(line) segments[seg.get_key()] = seg nb_found += 1 nb_labeled += (seg.label is not None) """ for h, w, vals in lines: seg = np.zeros((int(h) * int(w)), dtype=np.bool) for i in range(len(vals)): seg[i] = int(vals[i]) seg = seg.reshape((int(h), int(w))) seg_key = SpeedSegment.segment_image_to_key(seg) segments[seg_key] = seg #segments_found.append(seg) #segments_found_keys.add(seg_key) nb_found += 1 nb_labeled += (seg.label is not None) #return segments_found_keys, segments_found """ print("Loaded SpeedSegments database from file '%s' with %d segments, %d of which are labeled." % (filepath, nb_found, nb_labeled)) return segments
def save(self): with open(self.filename, "w") as f: for key in self.segments: segment = self.segments[key] #sr = segment.arr.astype(np.int32).ravel() #vals = [] #for v in sr: # vals.append(str(v)) #label = segment.label if segment.label is not None else "?" #f.write("%s\t%d\t%d\t%s" % (label, segment.shape[0], segment.shape[1], "".join(vals))) f.write("%s\n" % (segment.to_string(),))
def predict_speed_raw(self): segs = self.split_to_segments() #assert len(segs) > 0 if len(segs) == 0: print("[WARNING] [SpeedOMeter.predict_speed_raw()] length of segs is zero") return 0 result = [] for seg in segs: label = seg.predict_label() result.append(label) return result
def predict_speed(self): labels = self.predict_speed_raw() digits = set("0123456789") result = [] for label in labels: if label is None: return None for c in label: if c in digits: result.append(c) if len(result) == 0: return None else: return int("".join(result))
def segment_speed_image(speed_image_bin): speed_image_labeled, num_labels = morphology.label( speed_image_bin, background=0, connectivity=1, return_num=True ) segments = [] for label in range(1, num_labels+1): (yy, xx) = np.nonzero(speed_image_labeled == label) min_y, max_y = np.min(yy), np.max(yy) min_x, max_x = np.min(xx), np.max(xx) seg_img = speed_image_bin[min_y:max_y+1, min_x:max_x+1] segments.append(SpeedSegment(seg_img)) return segments
def predict_label(self): key = self.get_key() annotated_seg = SpeedSegmentsDatabase.get_instance().get_by_key(key) if annotated_seg is not None: return annotated_seg.label else: return None
def to_string(self): sr = self.arr.astype(np.int32).ravel() vals = [] for v in sr: vals.append(str(v)) label = self.label if self.label is not None else "?" h, w = self.arr.shape return "%s||%d||%d||%s" % (label, h, w, "".join(vals))
def from_string(line): label, h, w, vals = line.split("||") seg_image = np.zeros((int(h) * int(w)), dtype=np.bool) for i in range(len(vals)): seg_image[i] = int(vals[i]) seg_image = seg_image.reshape((int(h), int(w))) if label == "?": label = None seg = SpeedSegment(seg_image, label=label) return seg
def make_train_char_db(ori_img_dir): import pandas as pd import h5py """ ?????????? :param ori_img_dir: ???????? :return: """ even_split_train_path = os.path.join(os.getcwd(), 'evensplit_train_im') if not os.path.exists(even_split_train_path): os.makedirs(even_split_train_path) train_imgs = os.listdir(ori_img_dir) letters = list('02345678abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') answer_data = pd.read_table(os.path.join(os.getcwd(), 'lvy_ans.txt'), sep=':', names=['Index', 'Answer']) # ???? img = np.zeros((len(train_imgs)*4, 1, 35, 35), dtype=np.uint8) label = np.zeros((len(train_imgs)*4), dtype=np.uint32) index = 0 for train_img in train_imgs: ori_train_img = os.path.join(ori_img_dir, train_img) binary_train_img = binary_img(ori_train_img) # ???????? dingge_train_img = ding_ge(binary_train_img) # ??????? # ????? step_train = dingge_train_img.shape[1] / float(4) start_train = [j for j in np.arange(0, dingge_train_img.shape[1], step_train).tolist()] for p, k in enumerate(start_train): print train_img + '_' + str((p+1)) split_train_img = dingge_train_img[:, k:k + step_train] small_img = ding_ge(split_train_img) split_train_resize_img = cv2.resize(small_img, (35, 35)) img[index, 0, :, :] = split_train_resize_img label[index] = letters.index(answer_data['Answer'][int(train_img.split('.')[0])-1][p]) index += 1 cv2.imwrite(os.path.join(even_split_train_path, train_img.split('.')[0] + '_' + str(p+1) + '.png'), split_train_resize_img*255) f = h5py.File(os.path.join(os.getcwd(), 'train_chars_data.h5'), 'w') f.create_dataset('img', data=img) f.create_dataset('label', data=label) f.close()
def skel_to_graph(skel): """ Transform skeleton into its branches and nodes, by counting the number of neighbors of each pixel in the skeleton """ convolve_skel = 3**skel.ndim * ndimage.uniform_filter(skel.astype(np.float)) # 3x3 square mean neighbors = np.copy(skel.astype(np.uint8)) skel = skel.astype(np.bool) neighbors[skel] = convolve_skel[skel] - 1 edges = morphology.label(np.logical_or(neighbors == 2, neighbors ==1), background=0) nodes = morphology.label(np.logical_and(np.not_equal(neighbors, 2), neighbors > 0), background=0) length_edges = np.bincount(edges.ravel()) return nodes, edges, length_edges
def _heatmap_to_rects(self, grid_pred, bb_img): """Convert a heatmap to rectangles / bounding box candidates.""" grid_pred = np.squeeze(grid_pred) # (1, H, W) => (H, W) # remove low activations grid_thresh = grid_pred >= self.heatmap_activation_threshold # find connected components grid_labeled, num_labels = morphology.label( grid_thresh, background=0, connectivity=1, return_num=True ) # for each connected components, # - draw a bounding box around it, # - shrink the bounding box to optimal size # - estimate a score/confidence value bbs = [] for label in range(1, num_labels+1): (yy, xx) = np.nonzero(grid_labeled == label) min_y, max_y = np.min(yy), np.max(yy) min_x, max_x = np.min(xx), np.max(xx) rect = RectangleOnImage(x1=min_x, x2=max_x+1, y1=min_y, y2=max_y+1, shape=grid_labeled) activation = self._rect_to_score(rect, grid_pred) rect_shrunk, activation_shrunk = self._shrink(grid_pred, rect) rect_rs_shrunk = rect_shrunk.on(bb_img) bbs.append((rect_rs_shrunk, activation_shrunk)) return bbs