我们从Python开源项目中,提取了以下5个代码示例,用于说明如何使用cv2.distanceTransform()。
def update(self,frame,events): falloff = self.falloff img = frame.img pts = [denormalize(pt['norm_pos'],frame.img.shape[:-1][::-1],flip_y=True) for pt in events.get('gaze_positions',[]) if pt['confidence']>=self.g_pool.min_data_confidence] overlay = np.ones(img.shape[:-1],dtype=img.dtype) # draw recent gaze postions as black dots on an overlay image. for gaze_point in pts: try: overlay[int(gaze_point[1]),int(gaze_point[0])] = 0 except: pass out = cv2.distanceTransform(overlay,cv2.DIST_L2, 5) # fix for opencv binding inconsitency if type(out)==tuple: out = out[0] overlay = 1/(out/falloff+1) img[:] = np.multiply(img, cv2.cvtColor(overlay,cv2.COLOR_GRAY2RGB), casting="unsafe")
def shadow_image(self, img, pos): if img is None: return None weighted_img = np.ones((img.shape[0], img.shape[1]), np.uint8) x = int(pos.x() / self.scale) y = int(pos.y() / self.scale) weighted_img[y, x] = 0 dist_img = cv2.distanceTransform(weighted_img, distanceType=cv2.cv.CV_DIST_L2, maskSize=5).astype(np.float32) dist_sigma = self.img_size/2.0 dist_img_f = np.exp(-dist_img / dist_sigma) dist_img_f = np.tile(dist_img_f[..., np.newaxis], [1,1,3]) l = 0.25 img_f = img.astype(np.float32) rst_f = (img_f * l + (1-l) * (img_f * dist_img_f + (1-dist_img_f)*255.0)) rst = rst_f.astype(np.uint8) return rst
def get_distanceTransform(mask): img = (255*mask).astype(np.uint8) dist = cv2.distanceTransform(255-img, cv2.cv.CV_DIST_L2, cv2.cv.CV_DIST_MASK_PRECISE) #mask_weights = np.exp(-0.05*dist) dist = 1 - dist/np.max(dist) return dist
def __distance_transform(input, type, mask_size): """Sets the values of pixels in a binary image to their distance to the nearest black pixel. Args: input: A numpy.array. type: Opencv enum. mask_size: The size of the mask. Either 0, 3, or 5. Returns: A black and white numpy.ndarray. """ h, w = input.shape[:2] dst = numpy.zeros((h, w), numpy.float32) cv2.distanceTransform(input, type, mask_size, dst = dst) return numpy.uint8(dst)
def dist_mask(mask, max_dist=10): mask = mask.astype(np.uint8) def get_dist(m): d = cv2.distanceTransform(m, cv2.DIST_L2, maskSize=3) d[d > max_dist] = max_dist return d / max_dist dist = get_dist(mask) - get_dist(1 - mask) # TODO - check in the notebook # TODO - what is the proper power? #pow = 0.5 #dist[dist > 0] = dist[dist > 0] ** pow #dist[dist < 0] = -((-dist[dist < 0]) ** pow) return (1 + dist) / 2 # from 0 to 1