Beispiel #1
0
def load_and_transform3d(ex, joint_info, learning_phase, rng):
    # Get the random number generators for the different augmentations to make it reproducibile
    appearance_rng = util.new_rng(rng)
    background_rng = util.new_rng(rng)
    geom_rng = util.new_rng(rng)
    partial_visi_rng = util.new_rng(rng)

    output_side = FLAGS.proc_side
    output_imshape = (output_side, output_side)

    if 'sailvos' in ex.image_path.lower():
        # This is needed in order not to lose precision in later operations.
        # Background: In the Sailvos dataset (GTA V), some world coordinates
        # are crazy large (several kilometers, i.e. millions of millimeters, which becomes
        # hard to process with the limited simultaneous dynamic range of float32).
        # They are stored in float64 but the processing is done in float32 here.
        ex.world_coords -= ex.camera.t
        ex.camera.t[:] = 0

    box = ex.bbox
    if 'surreal' in ex.image_path.lower():
        # Surreal images are flipped wrong in the official dataset release
        box = box.copy()
        box[0] = 320 - (box[0] + box[2])

    # Partial visibility
    if 'surreal' in ex.image_path.lower() and 'surmuco' not in FLAGS.dataset:
        partial_visi_prob = 0.5
    elif 'h36m' in ex.image_path.lower() and 'many' in FLAGS.dataset:
        partial_visi_prob = 0.5
    else:
        partial_visi_prob = FLAGS.partial_visibility_prob

    use_partial_visi_aug = ((learning_phase == TRAIN or FLAGS.test_aug)
                            and partial_visi_rng.rand() < partial_visi_prob)
    if use_partial_visi_aug:
        box = util.random_partial_subbox(boxlib.expand_to_square(box),
                                         partial_visi_rng)

    # Geometric transformation and augmentation
    crop_side = np.max(box[2:])
    center_point = boxlib.center(box)
    if ((learning_phase == TRAIN and FLAGS.geom_aug) or
        (learning_phase != TRAIN and FLAGS.test_aug and FLAGS.geom_aug)):
        center_point += util.random_uniform_disc(
            geom_rng) * FLAGS.shift_aug / 100 * crop_side

    # The homographic reprojection of a rectangle (bounding box) will not be another rectangle
    # Hence, instead we transform the side midpoints of the short sides of the box and
    # determine an appropriate zoom factor by taking the projected distance of these two points
    # and scaling that to the desired output image side length.
    if box[2] < box[3]:
        # Tall box: take midpoints of top and bottom sides
        delta_y = np.array([0, box[3] / 2])
        sidepoints = center_point + np.stack([-delta_y, delta_y])
    else:
        # Wide box: take midpoints of left and right sides
        delta_x = np.array([box[2] / 2, 0])
        sidepoints = center_point + np.stack([-delta_x, delta_x])

    cam = ex.camera.copy()
    cam.turn_towards(target_image_point=center_point)
    cam.undistort()
    cam.square_pixels()
    cam_sidepoints = cameralib.reproject_image_points(sidepoints, ex.camera,
                                                      cam)
    crop_side = np.linalg.norm(cam_sidepoints[0] - cam_sidepoints[1])
    cam.zoom(output_side / crop_side)
    cam.center_principal_point(output_imshape)

    if FLAGS.geom_aug and (learning_phase == TRAIN or FLAGS.test_aug):
        s1 = FLAGS.scale_aug_down / 100
        s2 = FLAGS.scale_aug_up / 100
        zoom = geom_rng.uniform(1 - s1, 1 + s2)
        cam.zoom(zoom)
        r = np.deg2rad(FLAGS.rot_aug)
        cam.rotate(roll=geom_rng.uniform(-r, r))

    world_coords = ex.univ_coords if FLAGS.universal_skeleton else ex.world_coords
    metric_world_coords = ex.world_coords

    if learning_phase == TRAIN and geom_rng.rand() < 0.5:
        cam.horizontal_flip()
        # Must reorder the joints due to left and right flip
        camcoords = cam.world_to_camera(world_coords)[
            joint_info.mirror_mapping]
        metric_world_coords = metric_world_coords[joint_info.mirror_mapping]
    else:
        camcoords = cam.world_to_camera(world_coords)

    imcoords = cam.world_to_image(metric_world_coords)

    # Load and reproject image
    image_path = util.ensure_absolute_path(ex.image_path)
    origsize_im = improc.imread_jpeg(image_path)
    if 'surreal' in ex.image_path.lower():
        # Surreal images are flipped wrong in the official dataset release
        origsize_im = origsize_im[:, ::-1]

    interp_str = (FLAGS.image_interpolation_train if learning_phase == TRAIN
                  else FLAGS.image_interpolation_test)
    antialias = (FLAGS.antialias_train
                 if learning_phase == TRAIN else FLAGS.antialias_test)
    interp = getattr(cv2, 'INTER_' + interp_str.upper())
    im = cameralib.reproject_image(origsize_im,
                                   ex.camera,
                                   cam,
                                   output_imshape,
                                   antialias_factor=antialias,
                                   interp=interp)

    # Color adjustment
    if re.match('.*mupots/TS[1-5]/.+', ex.image_path):
        im = improc.adjust_gamma(im, 0.67, inplace=True)
    elif '3dhp' in ex.image_path and re.match('.+/(TS[1-4])/', ex.image_path):
        im = improc.adjust_gamma(im, 0.67, inplace=True)
        im = improc.white_balance(im, 110, 145)
    elif 'panoptic' in ex.image_path.lower():
        im = improc.white_balance(im, 120, 138)

    # Background augmentation
    if hasattr(ex, 'mask') and ex.mask is not None:
        bg_aug_prob = 0.2 if 'sailvos' in ex.image_path.lower(
        ) else FLAGS.background_aug_prob
        if (FLAGS.background_aug_prob
                and (learning_phase == TRAIN or FLAGS.test_aug)
                and background_rng.rand() < bg_aug_prob):
            fgmask = improc.decode_mask(ex.mask)
            if 'surreal' in ex.image_path:
                # Surreal images are flipped wrong in the official dataset release
                fgmask = fgmask[:, ::-1]
            fgmask = cameralib.reproject_image(fgmask,
                                               ex.camera,
                                               cam,
                                               output_imshape,
                                               antialias_factor=antialias,
                                               interp=interp)
            im = augmentation.background.augment_background(
                im, fgmask, background_rng)

    # Occlusion and color augmentation
    im = augmentation.appearance.augment_appearance(im, learning_phase,
                                                    FLAGS.occlude_aug_prob,
                                                    appearance_rng)
    im = tfu.nhwc_to_std(im)
    im = improc.normalize01(im)

    # Joints with NaN coordinates are invalid
    is_joint_in_fov = ~np.logical_or(
        np.any(imcoords < 0, axis=-1),
        np.any(imcoords >= FLAGS.proc_side, axis=-1))
    joint_validity_mask = ~np.any(np.isnan(camcoords), axis=-1)

    rot_to_orig_cam = ex.camera.R @ cam.R.T
    rot_to_world = cam.R.T

    return dict(image=im,
                intrinsics=np.float32(cam.intrinsic_matrix),
                image_path=ex.image_path,
                coords3d_true=np.nan_to_num(camcoords).astype(np.float32),
                coords2d_true=np.nan_to_num(imcoords).astype(np.float32),
                rot_to_orig_cam=rot_to_orig_cam.astype(np.float32),
                rot_to_world=rot_to_world.astype(np.float32),
                cam_loc=cam.t.astype(np.float32),
                joint_validity_mask=joint_validity_mask,
                is_joint_in_fov=np.float32(is_joint_in_fov))
Beispiel #2
0
def load_and_transform3d(ex, joint_info, learning_phase, rng=None):
    appearance_rng = util.new_rng(rng)
    background_rng = util.new_rng(rng)
    geom_rng = util.new_rng(rng)
    partial_visi_rng = util.new_rng(rng)

    output_side = FLAGS.proc_side
    output_imshape = (output_side, output_side)

    box = ex.bbox
    if FLAGS.partial_visibility:
        box = util.random_partial_subbox(boxlib.expand_to_square(box), partial_visi_rng)

    crop_side = np.max(box[2:])
    center_point = boxlib.center(box)
    if ((learning_phase == TRAIN and FLAGS.geom_aug) or
            (learning_phase != TRAIN and FLAGS.test_aug and FLAGS.geom_aug)):
        center_point += util.random_uniform_disc(geom_rng) * FLAGS.shift_aug / 100 * crop_side

    if box[2] < box[3]:
        delta_y = np.array([0, box[3] / 2])
        sidepoints = center_point + np.stack([-delta_y, delta_y])
    else:
        delta_x = np.array([box[2] / 2, 0])
        sidepoints = center_point + np.stack([-delta_x, delta_x])

    cam = ex.camera.copy()
    cam.turn_towards(target_image_point=center_point)
    cam.undistort()
    cam.square_pixels()
    world_sidepoints = ex.camera.image_to_world(sidepoints)
    cam_sidepoints = cam.world_to_image(world_sidepoints)
    crop_side = np.linalg.norm(cam_sidepoints[0] - cam_sidepoints[1])
    cam.zoom(output_side / crop_side)
    cam.center_principal_point(output_imshape)

    if FLAGS.geom_aug and (learning_phase == TRAIN or FLAGS.test_aug):
        s1 = FLAGS.scale_aug_down / 100
        s2 = FLAGS.scale_aug_up / 100
        r = FLAGS.rot_aug * np.pi / 180
        zoom = geom_rng.uniform(1 - s1, 1 + s2)
        cam.zoom(zoom)
        cam.rotate(roll=geom_rng.uniform(-r, r))

    world_coords = ex.univ_coords if FLAGS.universal_skeleton else ex.world_coords
    metric_world_coords = ex.world_coords

    if learning_phase == TRAIN and geom_rng.rand() < 0.5:
        cam.horizontal_flip()
        camcoords = cam.world_to_camera(world_coords)[joint_info.mirror_mapping]
        metric_world_coords = metric_world_coords[joint_info.mirror_mapping]
    else:
        camcoords = cam.world_to_camera(world_coords)

    imcoords = cam.world_to_image(metric_world_coords)

    image_path = util.ensure_absolute_path(ex.image_path)
    origsize_im = improc.imread_jpeg(image_path)

    interp_str = (FLAGS.image_interpolation_train
                  if learning_phase == TRAIN else FLAGS.image_interpolation_test)
    antialias = (FLAGS.antialias_train if learning_phase == TRAIN else FLAGS.antialias_test)
    interp = getattr(cv2, 'INTER_' + interp_str.upper())
    im = cameralib.reproject_image(
        origsize_im, ex.camera, cam, output_imshape, antialias_factor=antialias, interp=interp)

    if re.match('.+/mupots/TS[1-5]/.+', ex.image_path):
        im = improc.adjust_gamma(im, 0.67, inplace=True)
    elif '3dhp' in ex.image_path and re.match('.+/(TS[1-4])/', ex.image_path):
        im = improc.adjust_gamma(im, 0.67, inplace=True)
        im = improc.white_balance(im, 110, 145)

    if (FLAGS.background_aug_prob and hasattr(ex, 'mask') and ex.mask is not None and
            background_rng.rand() < FLAGS.background_aug_prob and
            (learning_phase == TRAIN or FLAGS.test_aug)):
        fgmask = improc.decode_mask(ex.mask)
        fgmask = cameralib.reproject_image(
            fgmask, ex.camera, cam, output_imshape, antialias_factor=antialias, interp=interp)
        im = augmentation.background.augment_background(im, fgmask, background_rng)

    im = augmentation.appearance.augment_appearance(im, learning_phase, appearance_rng)
    im = tfu.nhwc_to_std(im)
    im = improc.normalize01(im)

    # Joints with NaN coordinates are invalid
    is_joint_in_fov = ~np.logical_or(np.any(imcoords < 0, axis=-1),
                                     np.any(imcoords >= FLAGS.proc_side, axis=-1))
    joint_validity_mask = ~np.any(np.isnan(camcoords), axis=-1)

    rot_to_orig_cam = ex.camera.R @ cam.R.T
    rot_to_world = cam.R.T
    inv_intrinsics = np.linalg.inv(cam.intrinsic_matrix)

    return (
        ex.image_path, im, np.nan_to_num(camcoords).astype(np.float32),
        np.nan_to_num(imcoords).astype(np.float32), inv_intrinsics.astype(np.float32),
        rot_to_orig_cam.astype(np.float32), rot_to_world.astype(np.float32),
        cam.t.astype(np.float32), joint_validity_mask,
        np.float32(is_joint_in_fov), ex.activity_name, ex.scene_name)
def make_efficient_example(ex,
                           new_image_path,
                           further_expansion_factor=1,
                           image_adjustments_3dhp=False,
                           min_time=None):
    """Make example by storing the image in a cropped and resized version for efficient loading"""

    is3d = hasattr(ex, 'world_coords')
    w, h = (improc.image_extents(util.ensure_absolute_path(ex.image_path))
            if isinstance(ex.image_path, str) else
            (ex.image_path.shape[1], ex.image_path.shape[0]))
    full_box = boxlib.full_box(imsize=[w, h])

    if is3d:
        old_camera = ex.camera
        new_camera = ex.camera.copy()
        new_camera.turn_towards(target_image_point=boxlib.center(ex.bbox))
        new_camera.undistort()
    else:
        old_camera = cameralib.Camera.create2D()
        new_camera = old_camera.copy()

    reprojected_box = reproject_box(ex.bbox,
                                    old_camera,
                                    new_camera,
                                    method='side_midpoints')
    reprojected_full_box = reproject_box(full_box,
                                         old_camera,
                                         new_camera,
                                         method='corners')
    expanded_bbox = (get_expanded_crop_box(
        reprojected_box, reprojected_full_box, further_expansion_factor)
                     if further_expansion_factor > 0 else reprojected_box)
    scale_factor = min(1.2, 256 / np.max(reprojected_box[2:]) * 1.5)
    new_camera.shift_image(-expanded_bbox[:2])
    new_camera.scale_output(scale_factor)

    reprojected_box = reproject_box(ex.bbox,
                                    old_camera,
                                    new_camera,
                                    method='side_midpoints')
    dst_shape = improc.rounded_int_tuple(scale_factor * expanded_bbox[[3, 2]])

    new_image_abspath = util.ensure_absolute_path(new_image_path)
    if not (util.is_file_newer(new_image_abspath, min_time)
            and improc.is_image_readable(new_image_abspath)):
        im = improc.imread_jpeg(ex.image_path) if isinstance(
            ex.image_path, str) else ex.image_path
        #host_im, cuda_im = get_memory(im.shape)
        im = np.power((im.astype(np.float32) / 255), 2.2)
        #cuda_im.upload(host_im)
        new_im = cameralib.reproject_image(im,
                                           old_camera,
                                           new_camera,
                                           dst_shape,
                                           antialias_factor=2,
                                           interp=cv2.INTER_CUBIC)
        new_im = np.clip(new_im, 0, 1)

        if image_adjustments_3dhp:
            # enhance the 3dhp images to reduce the green tint and increase brightness
            new_im = (new_im**(1 / 2.2 * 0.67) * 255).astype(np.uint8)
            new_im = improc.white_balance(new_im, 110, 145)
        else:
            new_im = (new_im**(1 / 2.2) * 255).astype(np.uint8)
        util.ensure_path_exists(new_image_abspath)
        imageio.imwrite(new_image_abspath, new_im, quality=95)
        assert improc.is_image_readable(new_image_abspath)

    new_ex = copy.deepcopy(ex)
    new_ex.bbox = reprojected_box
    new_ex.image_path = new_image_path
    if is3d:
        new_ex.camera = new_camera
    else:
        new_ex.coords = cameralib.reproject_image_points(
            new_ex.coords, old_camera, new_camera)

    if hasattr(ex, 'mask') and ex.mask is not None:
        if isinstance(ex.mask, str):
            mask = improc.imread_jpeg(util.ensure_absolute_path(ex.mask))
            host_mask, cuda_mask = get_memory(mask.shape)
            np.divide(mask.astype(np.float32), 255, out=host_mask)
            cuda_mask.upload(host_mask)
            mask_reproj = cameralib.reproject_image(
                cuda_mask,
                ex.camera,
                new_camera,
                dst_shape,
                antialias_factor=2).download()
            mask_reproj = 255 * (mask_reproj[..., 0] > 32 / 255).astype(
                np.uint8)
            new_ex.mask = get_connected_component_with_highest_iou(
                mask_reproj, reprojected_box)
        else:
            new_ex.mask = ex.mask
    return new_ex