Python skimage.draw.circle() Examples

The following are 30 code examples of skimage.draw.circle(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module skimage.draw , or try the search function .
Example #1
Source File: layer.py    From uchroma with GNU Lesser General Public License v3.0 6 votes vote down vote up
def circle(self, row: int, col: int, radius: float,
               color: ColorType, fill: bool=False, alpha=1.0) -> 'Layer':
        """
        Draw a circle centered on the specified row and column,
        with the given radius.

        :param row: Center row of circle
        :param col: Center column of circle
        :param radius: Radius of circle
        :param color: Color to draw with
        :param fill: True if the circle should be filled

        :return: This frame instance
        """
        if fill:
            rr, cc = draw.circle(row, col, round(radius), shape=self.matrix.shape)
            self._draw(rr, cc, color, alpha)

        else:
            rr, cc, aa = draw.circle_perimeter_aa(row, col, round(radius), shape=self.matrix.shape)
            self._draw(rr, cc, color, aa)

        return self 
Example #2
Source File: run_ovary_egg-segmentation.py    From pyImSegm with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def create_circle_center(img_shape, centers, radius=10):
    """ create initialisation from centres as small circles

    :param img_shape:
    :param [[int, int]] centers:
    :param int radius:
    :return:
    """
    mask_circle = np.zeros(img_shape, dtype=int)
    mask_perimeter = np.zeros(img_shape, dtype=int)
    center_circles = list()
    for i, pos in enumerate(centers):
        rr, cc = draw.circle(int(pos[0]), int(pos[1]), radius,
                             shape=img_shape[:2])
        mask_circle[rr, cc] = i + 1
        rr, cc = draw.circle_perimeter(int(pos[0]), int(pos[1]), radius,
                                       shape=img_shape[:2])
        mask_perimeter[rr, cc] = i + 1
        center_circles.append(np.array([rr, cc]).transpose())
    return center_circles, mask_circle, mask_perimeter 
Example #3
Source File: test_subpixelrefinement_generator.py    From pyxem with GNU General Public License v3.0 6 votes vote down vote up
def create_spot(self):
        z1, z1a = np.zeros((128, 128)), np.zeros((128, 128))
        z2, z2a = np.zeros((128, 128)), np.zeros((128, 128))

        rr, cc = draw.circle(30, 90, radius=4, shape=z1.shape)  # 30 is y!
        z1[rr, cc], z2[rr, cc] = 1, 1
        rr2, cc2 = draw.circle(100, 60, radius=4, shape=z2.shape)
        z2[rr2, cc2] = 1
        rr, cc = draw.circle(30, 90 + 3, radius=4, shape=z1.shape)  # 30 is y!
        z1a[rr, cc], z2a[rr, cc] = 1, 1
        rr2, cc2 = draw.circle(100 - 2, 60, radius=4, shape=z2.shape)
        z2a[rr2, cc2] = 1

        # marks centers for local com and local_gaussian_method
        z1[30, 90], z2[30, 90], z2[100, 60] = 2, 2, 2
        z1a[30, 93], z2a[30, 93], z2a[98, 60] = 10, 10, 10

        dp = ElectronDiffraction2D(
            np.asarray([[z1, z1a], [z2, z2a]])
        )  # this needs to be in 2x2
        return dp 
Example #4
Source File: uv_map_generator_unit_test.py    From densebody_pytorch with GNU General Public License v3.0 6 votes vote down vote up
def visualize(folder, imagenames, mesh_2d, joints_2d):
    i = 0
    for name, mesh, joints in zip(imagenames, mesh_2d, joints_2d):
        shutil.copyfile(name,
            '/im_gt_{}.png'.format(folder, i)
        )
        im = imread(name)
        shape = im.shape[0:2]
        height = im.shape[0]
        for p2d in mesh:
            im[height - p2d[1], p2d[0]] = [127,127,127]
            
        for j2d in joints:
            rr, cc = circle(height - j2d[1], j2d[0], 2, shape)
            im[rr, cc] = [255, 0, 0]
            
        imsave('{}/im_mask_{}.png'.format(folder, i), im)
        i += 1 
Example #5
Source File: create_UV_maps.py    From densebody_pytorch with GNU General Public License v3.0 6 votes vote down vote up
def visualize(folder, imagenames, mesh_2d, joints_2d, root=None):
    i = 0
    for name, mesh, joints in zip(imagenames, mesh_2d, joints_2d):
        print(name)
        shutil.copyfile(root + name,
            '/im_gt_{}.png'.format(folder, i)
        )
        im = imread(name)
        shape = im.shape[0:2]
        height = im.shape[0]
        for p2d in mesh:
            im[height - p2d[1], p2d[0]] = [127,127,127]
            
        for j2d in joints:
            rr, cc = circle(height - j2d[1], j2d[0], 2, shape)
            im[rr, cc] = [255, 0, 0]
            
        imwrite('{}/im_mask_{}.png'.format(folder, i), im)
        i += 1 
Example #6
Source File: heatmap.py    From deep-high-resolution-net.TensorFlow with MIT License 6 votes vote down vote up
def decode_pose(images, net_output, threshold=0.001):
    # key point class: 1:visible, 2: invisible, 3: not marked
    prediction = decode_output(net_output, threshold=threshold)

    batch_size, size_ver, size_hor, keypoints_number = net_output.shape
    kp_ver = prediction[:, ::3]
    kp_hor = prediction[:, 1::3]
    kp_class = prediction[:, 2::3]

    for b in range(batch_size):
        point_hor = kp_hor[b]
        point_ver = kp_ver[b]
        point_class = kp_class[b]
        images[b, :, :, :] = draw_lines_on_img(images[b], point_ver, point_hor, point_class)
        for i in range(len(point_class)):
            if point_class[i] != 3:
                rr, cc = draw.circle(point_ver[i], point_hor[i], 10, (256, 192))
                images[b, rr, cc, :] = 0

    return images 
Example #7
Source File: pose_utils.py    From everybody_dance_now_pytorch with GNU Affero General Public License v3.0 6 votes vote down vote up
def draw_pose_from_cords(pose_joints, img_size, radius=2, draw_joints=True):
    colors = np.zeros(shape=img_size + (3, ), dtype=np.uint8)
    mask = np.zeros(shape=img_size, dtype=bool)

    if draw_joints:
        for f, t in LIMB_SEQ:
            from_missing = pose_joints[f][0] == MISSING_VALUE or pose_joints[f][1] == MISSING_VALUE
            to_missing = pose_joints[t][0] == MISSING_VALUE or pose_joints[t][1] == MISSING_VALUE
            if from_missing or to_missing:
                continue
            yy, xx, val = line_aa(pose_joints[f][0], pose_joints[f][1], pose_joints[t][0], pose_joints[t][1])
            colors[yy, xx] = np.expand_dims(val, 1) * 255
            mask[yy, xx] = True

    for i, joint in enumerate(pose_joints):
        if pose_joints[i][0] == MISSING_VALUE or pose_joints[i][1] == MISSING_VALUE:
            continue
        yy, xx = circle(joint[0], joint[1], radius=radius, shape=img_size)
        colors[yy, xx] = COLORS[i]
        mask[yy, xx] = True

    return colors, mask 
Example #8
Source File: Dataset.py    From PReMVOS with MIT License 6 votes vote down vote up
def add_clicks(self, inputs, c):
    out_imgs = None

    for input in inputs:
      img = input[:, :, :3]
      # Radius of the point to be diplayed
      r=3
      pts = np.where(input[:,:,3] == 0)
      pts_zipped = list(zip(pts[0], pts[1]))
      if len(pts[0]) > 0:
        for pt in pts_zipped:
          if r < pt[0] < img.shape[0] - r and r < pt[1] < img.shape[1] - r:
            rr, cc = circle(pt[0], pt[1], 5, img.shape)
            img[rr, cc, :] = [np.max(img), np.min(img), np.min(img)] if c == 'r' \
                else [np.min(img), np.min(img), np.max(img)]

      img = img[np.newaxis, :, :, :]
      if out_imgs is None:
        out_imgs = img
      else:
        out_imgs = np.concatenate((out_imgs, img), axis = 0)

    return out_imgs.astype(np.float32) 
Example #9
Source File: volume.py    From luna16 with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def process_failure(name):
    name = name.replace("mask","truth")
    name2 = name.replace("truth","")
    image,_,_ = image_read_write.load_itk_image(name2)
    #image_cropped = image[:,120:420,60:460]
    image_mask = np.zeros(image.shape)
    center = 256
    cc,rr = circle(center+20,center,160)
    image_mask[:,cc,rr] = 1
    image[image>threshold]=0
    image[image!=0]=1
    image = image*image_mask
    #image_cropped[image_cropped>threshold]=0
    #image_cropped[image_cropped!=0]=1

    kernel20 = np.zeros((15,15))
    cc,rr = circle(7,7,8)
    kernel20[cc,rr]=1
    image = binary_closing(image, [kernel20],1)
    #image[:,:,:]=0
    #image[:,120:420,60:460]=image_cropped
    truth,_,_ = image_read_write.load_itk_image(name)
    print evaluator.calculate_dice(image,truth,name)
    image = np.array(image,dtype=np.int8)
    #LoadImages.save_itk(image,name) 
Example #10
Source File: enhancer_gan.py    From ImageEnhancer with MIT License 6 votes vote down vote up
def _corrupt(self, source):
        """ corrupt the input with specific corruption method
            :param source: original data set
            :return: corrupted data set, if noise type is not defined, the original data set will return
        """
        if self.corrupt_type is None:
            return source
        noised = np.zeros((np.shape(source)[0],) + self.shape['in'])
        for i, raw in enumerate(source):
            if self.corrupt_type == 'GSN':
                noised[i] = random_noise(raw, 'gaussian', var=self.corrupt_ratio)
            elif self.corrupt_type == 'MSN':
                noised[i] = random_noise(raw, 'pepper', amount=self.corrupt_ratio)
            elif self.corrupt_type == 'SPN':
                noised[i] = random_noise(raw, 's&p', amount=self.corrupt_ratio)
            elif self.corrupt_type == 'GSB':
                noised[i] = gaussian(raw, sigma=self.corrupt_ratio, multichannel=True)
            elif self.corrupt_type == 'GRY':
                noised[i] = gray2rgb(rgb2gray(raw))
            elif self.corrupt_type == 'BLK':
                rad = int(self.corrupt_ratio)
                row = random.randint(rad, self.shape['in'][0] - rad - 1)
                col = random.randint(rad, self.shape['in'][1] - rad - 1)
                noised[i] = np.copy(raw)
                noised[i][circle(row, col, self.corrupt_ratio)] = 0
            elif self.corrupt_type == 'ZIP':
                noised[i] = rescale(raw, 0.5, mode='constant')
        return noised 
Example #11
Source File: pose_utils.py    From Human-Pose-Transfer with MIT License 6 votes vote down vote up
def draw_pose_from_cords(pose_joints, img_size, radius=2, draw_joints=True):
    colors = np.zeros(shape=img_size + (3,), dtype=np.uint8)
    mask = np.zeros(shape=img_size, dtype=bool)

    if draw_joints:
        for f, t in LIMB_SEQ:
            from_missing = pose_joints[f][0] == MISSING_VALUE or pose_joints[f][1] == MISSING_VALUE
            to_missing = pose_joints[t][0] == MISSING_VALUE or pose_joints[t][1] == MISSING_VALUE
            if from_missing or to_missing:
                continue
            yy, xx, val = line_aa(pose_joints[f][0], pose_joints[f][1], pose_joints[t][0], pose_joints[t][1])
            colors[yy, xx] = np.expand_dims(val, 1) * 255
            mask[yy, xx] = True

    for i, joint in enumerate(pose_joints):
        if pose_joints[i][0] == MISSING_VALUE or pose_joints[i][1] == MISSING_VALUE:
            continue
        yy, xx = circle(joint[0], joint[1], radius=radius, shape=img_size)
        colors[yy, xx] = COLORS[i]
        mask[yy, xx] = True

    return colors, mask 
Example #12
Source File: snr_source.py    From VIP with MIT License 6 votes vote down vote up
def _snr_approx(array, source_xy, fwhm, centery, centerx):
    """
    array - frame convolved with top hat kernel
    """
    sourcex, sourcey = source_xy
    rad = dist(centery, centerx, sourcey, sourcex)
    ind_aper = draw.circle(sourcey, sourcex, fwhm/2.)
    # noise : STDDEV in convolved array of 1px wide annulus (while
    # masking the flux aperture) * correction of # of resolution elements
    ind_ann = draw.circle_perimeter(int(centery), int(centerx), int(rad))
    array2 = array.copy()
    array2[ind_aper] = mad(array[ind_ann])  # mask
    n2 = (2 * np.pi * rad) / fwhm - 1
    noise = array2[ind_ann].std() * np.sqrt(1+(1/n2))
    # signal : central px minus the mean of the pxs (masked) in 1px annulus
    signal = array[sourcey, sourcex] - array2[ind_ann].mean()
    snr_value = signal / noise
    return sourcey, sourcex, snr_value 
Example #13
Source File: Util.py    From PReMVOS with MIT License 5 votes vote down vote up
def visualise_clicks(images, click_maps, c):
  out_imgs = None
  if not isinstance(c, str):
    c=c.decode('utf-8')
  for idx in range(len(images)):
    img = images[idx]
    click_map = click_maps[idx]
    # Radius of the point to be diplayed
    r=3
    pts = np.where(click_map == 0)
    pts_zipped = zip(pts[0], pts[1])
    if len(pts[0]) > 0:
      for pt in pts_zipped:
        if r < pt[0] < img.shape[0] - r and r < pt[1] < img.shape[1] - r:
          rr, cc = circle(pt[0], pt[1], 5, img.shape)
          img[rr, cc, :] = [np.max(img), np.min(img), np.min(img)] if c == 'r' \
            else [np.min(img), np.min(img), np.max(img)]

    if len(list(img.shape)) == 3:
      img = img[np.newaxis, :, :, :]
    if out_imgs is None:
      out_imgs = img
    else:
      out_imgs = np.concatenate((out_imgs, img), axis = 0)

  return out_imgs.astype(np.float32) 
Example #14
Source File: dataset.py    From deep-high-resolution-net.TensorFlow with MIT License 5 votes vote down vote up
def mytest():
    tfrecord_file = '../dataset/train.tfrecords'

    filename_queue = tf.train.string_input_producer([tfrecord_file], num_epochs=None)
    image_name, image, keypoints_ver, keypoints_hor, keypoints_class = decode_tfrecord(filename_queue)

    with tf.Session() as sess:
        init_op = tf.global_variables_initializer()
        sess.run(init_op)
        coord = tf.train.Coordinator()
        threads = tf.train.start_queue_runners(coord=coord)
        try:
            # while not coord.should_stop():
            for i in range(10):
                img_name, img, point_ver, point_hor, point_class = sess.run([image_name, image, keypoints_ver,
                                                                             keypoints_hor, keypoints_class])

                print(img_name, point_hor, point_ver, point_class)

                for i in range(len(point_class)):
                    if point_class[i] > 0:
                        rr, cc = draw.circle(point_ver[i], point_hor[i], 10, (256, 192))
                        img[rr, cc, :] = 0

                io.imshow(img)
                io.show()

        except tf.errors.OutOfRangeError:
            print('Done reading')
        finally:
            coord.request_stop() 
Example #15
Source File: generate_pose_map_add_mask.py    From Human-Pose-Transfer with MIT License 5 votes vote down vote up
def key_point_to_mask(key_points, img_size, radius=6):
    new_points = expand_key_points(key_points, radius)
    mask = np.zeros(shape=img_size, dtype=bool)

    for i, joint in enumerate(list(key_points) + new_points):
        if KEY_POINT_MISSING_VALUE in joint:
            continue
        yy, xx = circle(joint[0], joint[1], radius=radius, shape=img_size)
        mask[yy, xx] = True
    mask = dilation(mask, square(radius + 3))
    mask = erosion(mask, square(radius + 3))
    return mask 
Example #16
Source File: dataset.py    From deep-high-resolution-net.TensorFlow with MIT License 5 votes vote down vote up
def draw_points_on_img(img, point_ver, point_hor, point_class):
    for i in range(len(point_class)):
        if point_class[i] != 3:
            rr, cc = draw.circle(point_ver[i], point_hor[i], 10, (256, 192))
            #draw.set_color(img, [rr, cc], [0., 0., 0.], alpha=5)
            img[rr, cc, :] = 0
    #io.imshow(img)
    #io.show()

    return img 
Example #17
Source File: enhancer.py    From ImageEnhancer with MIT License 5 votes vote down vote up
def _corrupt(self, source):
        """ corrupt the input with specific corruption method
            :param source: original data set
            :return: corrupted data set, if noise type is not defined, the original data set will return
        """
        if self.corrupt_type is None:
            return source
        noised = np.zeros((np.shape(source)[0],) + self.shape['in'])
        for i, raw in enumerate(source):
            if self.corrupt_type == 'GSN':
                noised[i] = random_noise(raw, 'gaussian', var=self.corrupt_ratio)
            elif self.corrupt_type == 'MSN':
                noised[i] = random_noise(raw, 'pepper', amount=self.corrupt_ratio)
            elif self.corrupt_type == 'SPN':
                noised[i] = random_noise(raw, 's&p', amount=self.corrupt_ratio)
            elif self.corrupt_type == 'GSB':
                noised[i] = gaussian(raw, sigma=self.corrupt_ratio, multichannel=True)
            elif self.corrupt_type == 'GRY':
                noised[i] = gray2rgb(rgb2gray(raw))
            elif self.corrupt_type == 'BLK':
                rad = int(self.corrupt_ratio)
                row = random.randint(rad, self.shape['in'][0] - rad - 1)
                col = random.randint(rad, self.shape['in'][1] - rad - 1)
                noised[i] = np.copy(raw)
                noised[i][circle(row, col, self.corrupt_ratio)] = 0
            elif self.corrupt_type == 'ZIP':
                noised[i] = rescale(raw, 0.5, mode='constant')
        return noised 
Example #18
Source File: Util.py    From TrackR-CNN with MIT License 5 votes vote down vote up
def visualise_clicks(images, click_maps, c):
  out_imgs = None
  if not isinstance(c, str):
    c=c.decode('utf-8')
  for idx in range(len(images)):
    img = images[idx]
    click_map = click_maps[idx]
    # Radius of the point to be diplayed
    r=3
    pts = np.where(click_map == 0)
    pts_zipped = zip(pts[0], pts[1])
    if len(pts[0]) > 0:
      for pt in pts_zipped:
        if r < pt[0] < img.shape[0] - r and r < pt[1] < img.shape[1] - r:
          rr, cc = circle(pt[0], pt[1], 5, img.shape)
          img[rr, cc, :] = [np.max(img), np.min(img), np.min(img)] if c == 'r' \
            else [np.min(img), np.min(img), np.max(img)]

    if len(list(img.shape)) == 3:
      img = img[np.newaxis, :, :, :]
    if out_imgs is None:
      out_imgs = img
    else:
      out_imgs = np.concatenate((out_imgs, img), axis = 0)

  return out_imgs.astype(np.float32) 
Example #19
Source File: line_dataset.py    From DSACLine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def draw_points(self, points, data, inliers=None):
		'''
		Draw 2D points for a batch of images.

		points -- 2D points, array shape (Nx2xM) where 
			N is the number of images in the batch
			2 is the number of point dimensions (x, y)
			M is the number of points
		data -- batch of images to draw to
		inliers -- soft inlier score for each point, 
			if given and score < 0.5 point will be drawn green, red otherwise
		'''

		n = points.shape[0] # number of images
		m = points.shape[2] # number of points

		for i in range (0, n):
			for j in range(0, m):

				clr = (0.2, 0.2, 0.2) # draw predicted points as dark circles
				if inliers is not None and inliers[i, j] > 0.5:
					clr = (0.7, 0.7, 0.7) # draw inliers as light circles
					
				r = int(points[i, 0, j] * self.imgH)
				c = int(points[i, 1, j] * self.imgW)
				rr, cc = circle(r, c, 2)
				set_color(data[i], (rr, cc), clr)

		return data 
Example #20
Source File: optimize_1_3.py    From ceviche with MIT License 5 votes vote down vote up
def operator_blur(rho, radius=2):
    """Blur operator implemented via two-dimensional convolution
    """
    rr, cc = circle(radius, radius, radius+1)
    kernel = np.zeros((2*radius+1, 2*radius+1), dtype=np.float)
    kernel[rr, cc] = 1
    kernel=kernel/kernel.sum()
    # For whatever reason HIPS autograd doesn't support 'same' mode, so we need to manually crop the output
    return conv(rho, kernel, mode='full')[radius:-radius,radius:-radius] 
Example #21
Source File: optimize_mode_converter.py    From ceviche with MIT License 5 votes vote down vote up
def operator_blur(rho, radius=2):
    """Blur operator implemented via two-dimensional convolution
    """
    rr, cc = circle(radius, radius, radius+1)
    kernel = np.zeros((2*radius+1, 2*radius+1), dtype=np.float)
    kernel[rr, cc] = 1
    kernel=kernel/kernel.sum()
    # For whatever reason HIPS autograd doesn't support 'same' mode, so we need to manually crop the output
    return conv(rho, kernel, mode='full')[radius:-radius,radius:-radius] 
Example #22
Source File: test_descriptors.py    From pyImSegm with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_ray_features_circle_down_edge(self):
        seg = np.zeros((400, 600), dtype=bool)
        x, y = draw.circle(200, 250, 150, shape=seg.shape)
        seg[x, y] = True
        points = [(200, 250), (150, 200), (250, 200), (250, 300)]

        for i, point in enumerate(points):
            ray_dist_raw = compute_ray_features_segm_2d(seg, point, edge='down',
                                                        angle_step=ANGULAR_STEP)
            ray_dist, shift = shift_ray_features(ray_dist_raw)
            points_rt = reconstruct_ray_features_2d(point, ray_dist, shift)
            p_fig = export_ray_results(seg, point, points_rt, ray_dist_raw, ray_dist,
                                       'circle-full_edge-down-%i.png' % i)
            self.assertTrue(os.path.exists(p_fig))

        # insert white interior
        x, y = draw.circle(200, 250, 120, shape=seg.shape)
        seg[x, y] = False

        for i, point in enumerate(points):
            ray_dist_raw = compute_ray_features_segm_2d(seg, point, edge='down',
                                                        angle_step=ANGULAR_STEP)
            ray_dist, shift = shift_ray_features(ray_dist_raw)
            points_rt = reconstruct_ray_features_2d(point, ray_dist, shift)
            p_fig = export_ray_results(seg, point, points_rt, ray_dist_raw, ray_dist,
                                       'circle-inter_edge-down-%i.png' % i)
            self.assertTrue(os.path.exists(p_fig)) 
Example #23
Source File: run_create_annotation.py    From pyImSegm with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def draw_circle(pos_center, radius, img_shape):
    """ create empty image and draw a circle with specific radius

    :param [int, int] pos_center:
    :param int radius:
    :param [int, int] img_shape:
    :return ndarray:
    """
    im = np.zeros(img_shape)
    x, y = draw.circle(pos_center[0], pos_center[1], radius, shape=im.shape[:2])
    im[x, y] = True
    return im 
Example #24
Source File: pose_utils.py    From Human-Pose-Transfer with MIT License 5 votes vote down vote up
def produce_ma_mask(kp_array, img_size, point_radius=4):
    from skimage.morphology import dilation, erosion, square
    mask = np.zeros(shape=img_size, dtype=bool)
    limbs = [[2, 3], [2, 6], [3, 4], [4, 5], [6, 7], [7, 8], [2, 9], [9, 10],
             [10, 11], [2, 12], [12, 13], [13, 14], [2, 1], [1, 15], [15, 17],
             [1, 16], [16, 18], [2, 17], [2, 18], [9, 12], [12, 6], [9, 3], [17, 18]]
    limbs = np.array(limbs) - 1
    for f, t in limbs:
        from_missing = kp_array[f][0] == MISSING_VALUE or kp_array[f][1] == MISSING_VALUE
        to_missing = kp_array[t][0] == MISSING_VALUE or kp_array[t][1] == MISSING_VALUE
        if from_missing or to_missing:
            continue

        norm_vec = kp_array[f] - kp_array[t]
        norm_vec = np.array([-norm_vec[1], norm_vec[0]])
        norm_vec = point_radius * norm_vec / np.linalg.norm(norm_vec)

        vetexes = np.array([
            kp_array[f] + norm_vec,
            kp_array[f] - norm_vec,
            kp_array[t] - norm_vec,
            kp_array[t] + norm_vec
        ])
        yy, xx = polygon(vetexes[:, 0], vetexes[:, 1], shape=img_size)
        mask[yy, xx] = True

    for i, joint in enumerate(kp_array):
        if kp_array[i][0] == MISSING_VALUE or kp_array[i][1] == MISSING_VALUE:
            continue
        yy, xx = circle(joint[0], joint[1], radius=point_radius, shape=img_size)
        mask[yy, xx] = True

    mask = dilation(mask, square(5))
    mask = erosion(mask, square(5))
    return mask 
Example #25
Source File: mixed_len_generator.py    From CSGNet with MIT License 5 votes vote down vote up
def draw_circle(self, center: List, radius: int):
        """
        Draw a circle
        :param center: center of the circle
        :param radius: radius of the circle
        :return:
        """
        arr = np.zeros(self.canvas_shape, dtype=bool)
        xp = [center[0] + radius, center[0], center[0], center[0] - radius]
        yp = [center[1], center[1] + radius, center[1] - radius, center[1]]

        rr, cc = draw.circle(*center, radius=radius, shape=self.canvas_shape)
        arr[cc, rr] = True
        return arr 
Example #26
Source File: predict.py    From Convolutional-Pose-Machine-tf with GNU Lesser General Public License v3.0 5 votes vote down vote up
def joints_plot_image(joints, weight, img, radius=3, thickness=2):
    """ Plot the joints on image

    :param joints:      (np.array)Assuming input of shape (num, joint_num, dim)
    :param img:         (image)Assuming input of shape (num, w, h, c)
    :param weight:      (np.array)Assuming input of shape (num, joint_num)
    :param radius:      (int)Radius
    :param thickness:   (int)Thickness
    :return:            set of RGB image (num, w, h, c)
    """
    assert len(joints.shape) == 3 and len(img.shape) == 4 and len(weight.shape) == 2
    assert joints.shape[0] == img.shape[0] == weight.shape[0]
    colors = [(241, 242, 224), (196, 203, 128), (136, 150, 0), (64, 77, 0),
              (201, 230, 200), (132, 199, 129), (71, 160, 67), (32, 94, 27),
              (130, 224, 255), (7, 193, 255), (0, 160, 255), (0, 111, 255),
              (220, 216, 207), (174, 164, 144), (139, 125, 96), (100, 90, 69),
              (252, 229, 179), (247, 195, 79), (229, 155, 3), (155, 87, 1),
              (231, 190, 225), (200, 104, 186), (176, 39, 156), (162, 31, 123),
              (210, 205, 255), (115, 115, 229), (80, 83, 239), (40, 40, 198)]
    ret = np.zeros(img.shape, np.uint8)
    assert len(joints.shape) == 3 and len(img.shape) == 4
    assert img.shape[-1] == 3
    ret = img.copy()
    for num in range(joints.shape[0]):
        for jnum in range(joints.shape[1]):
            if weight[num, jnum] == 1:
                rr, cc = draw.circle(
                    int(joints[num, jnum, 0]), int(joints[num, jnum, 1]), radius)
                ret[num, rr, cc] = colors[jnum]
    for num in range(joints.shape[0]):
        for lnk in range(len(LINKS)):
            if weight[num, LINKS[lnk][0]] == 1 and weight[num, LINKS[lnk][1]] == 1:
                rr, cc = draw.line(int(joints[num, LINKS[lnk][0], 0]), int(joints[num, LINKS[lnk][0], 1]),
                                int(joints[num, LINKS[lnk][1], 0]), int(joints[num, LINKS[lnk][1], 1]))
                ret[num, rr, cc] = colors[lnk]
    return ret 
Example #27
Source File: Util.py    From MOTSFusion with MIT License 5 votes vote down vote up
def visualise_clicks(images, click_maps, c):
  out_imgs = None
  if not isinstance(c, str):
    c=c.decode('utf-8')
  for idx in range(len(images)):
    img = images[idx]
    click_map = click_maps[idx]
    # Radius of the point to be diplayed
    r=3
    pts = np.where(click_map == 0)
    pts_zipped = zip(pts[0], pts[1])
    if len(pts[0]) > 0:
      for pt in pts_zipped:
        if r < pt[0] < img.shape[0] - r and r < pt[1] < img.shape[1] - r:
          rr, cc = circle(pt[0], pt[1], 5, img.shape)
          img[rr, cc, :] = [np.max(img), np.min(img), np.min(img)] if c == 'r' \
            else [np.min(img), np.min(img), np.max(img)]

    if len(list(img.shape)) == 3:
      img = img[np.newaxis, :, :, :]
    if out_imgs is None:
      out_imgs = img
    else:
      out_imgs = np.concatenate((out_imgs, img), axis = 0)

  return out_imgs.astype(np.float32) 
Example #28
Source File: pose_utils.py    From everybody_dance_now_pytorch with GNU Affero General Public License v3.0 5 votes vote down vote up
def produce_ma_mask(kp_array, img_size, point_radius=4):
    from skimage.morphology import dilation, erosion, square
    mask = np.zeros(shape=img_size, dtype=bool)
    limbs = [[2,3], [2,6], [3,4], [4,5], [6,7], [7,8], [2,9], [9,10],
              [10,11], [2,12], [12,13], [13,14], [2,1], [1,15], [15,17],
               [1,16], [16,18], [2,17], [2,18], [9,12], [12,6], [9,3], [17,18]]
    limbs = np.array(limbs) - 1
    for f, t in limbs:
        from_missing = kp_array[f][0] == MISSING_VALUE or kp_array[f][1] == MISSING_VALUE
        to_missing = kp_array[t][0] == MISSING_VALUE or kp_array[t][1] == MISSING_VALUE
        if from_missing or to_missing:
            continue

        norm_vec = kp_array[f] - kp_array[t]
        norm_vec = np.array([-norm_vec[1], norm_vec[0]])
        norm_vec = point_radius * norm_vec / np.linalg.norm(norm_vec)


        vetexes = np.array([
            kp_array[f] + norm_vec,
            kp_array[f] - norm_vec,
            kp_array[t] - norm_vec,
            kp_array[t] + norm_vec
        ])
        yy, xx = polygon(vetexes[:, 0], vetexes[:, 1], shape=img_size)
        mask[yy, xx] = True

    for i, joint in enumerate(kp_array):
        if kp_array[i][0] == MISSING_VALUE or kp_array[i][1] == MISSING_VALUE:
            continue
        yy, xx = circle(joint[0], joint[1], radius=point_radius, shape=img_size)
        mask[yy, xx] = True

    mask = dilation(mask, square(5))
    mask = erosion(mask, square(5))
    return mask 
Example #29
Source File: layer.py    From uchroma with GNU Lesser General Public License v3.0 5 votes vote down vote up
def ellipse(self, row: int, col: int, radius_r: float, radius_c: float,
                color: ColorType, fill: bool=False, alpha: float=1.0) -> 'Layer':
        """
        Draw an ellipse centered on the specified row and column,
        with the given radiuses.

        :param row: Center row of ellipse
        :param col: Center column of ellipse
        :param radius_r: Radius of ellipse on y axis
        :param radius_c: Radius of ellipse on x axis
        :param color: Color to draw with
        :param fill: True if the circle should be filled

        :return: This frame instance
        """
        if fill:
            rr, cc = draw.ellipse(row, col, math.floor(radius_r), math.floor(radius_c),
                                  shape=self.matrix.shape)
            self._draw(rr, cc, color, alpha)

        else:
            rr, cc = draw.ellipse_perimeter(row, col, math.floor(radius_r), math.floor(radius_c),
                                            shape=self.matrix.shape)
            self._draw(rr, cc, color, alpha)

        return self 
Example #30
Source File: data_washing.py    From densebody_pytorch with GNU General Public License v3.0 5 votes vote down vote up
def _visualize(self, img_name, im, joints):
        shape = im.shape[0:2]
        height = im.shape[0]
        # for p2d in mesh:
        #    im[height - p2d[1], p2d[0]] = [127,127,127]
            
        for j2d in joints:
            rr, cc = circle(height - j2d[1], j2d[0], 2, shape)
            im[rr, cc] = [1., 0., 0.]
            
        imsave(img_name, im)
        
    # add Gaussian noise