예제 #1
0
def show_polygons_on_image(masks, 
                           img, 
                           alpha=0.4, 
                           output_file=None):
    """show masks on image

    Args:
        masks (list): list of coordinate
        img (np.array): original image
        alpha (int): compress
        output_file (str): save path
    """
    color_list = list(wwtool.COLORS.keys())
    img_h, img_w, _ = img.shape

    foreground = wwtool.generate_image(img_h, img_w, (0, 0, 0))
    for idx, mask in enumerate(masks):
        mask = np.array(mask).reshape(1, -1, 2)
        cv2.fillPoly(foreground, mask, (wwtool.COLORS[color_list[idx % 20]][2], wwtool.COLORS[color_list[idx % 20]][1], wwtool.COLORS[color_list[idx % 20]][0]))

    heatmap = wwtool.show_grayscale_as_heatmap(foreground / 255.0, show=False, return_img=True)
    beta = (1.0 - alpha)
    fusion = cv2.addWeighted(heatmap, alpha, img, beta, 0.0)

    if output_file is not None:
        cv2.imwrite(output_file, fusion)
    else:
        wwtool.show_image(fusion, save_name=None)

    return fusion
예제 #2
0
    def __airbus_ship_parse__(self, label_file, image_file):
        """
        (xmin, ymin, xmax, ymax)
        """
        image_file_name = os.path.splitext(os.path.basename(image_file))[0]
        save_image = wwtool.generate_image(800, 800, color=(0, 0, 0))
        img = cv2.imread(image_file)
        img_height, img_width, _ = img.shape

        image_objects = airbus_ship_parse.airbus_ship_parse(os.path.basename(image_file))
        objects = []
        objects_small_save = []
        total_object_num = len(image_objects)
        small_object_num = 0
        large_object_num = 0
        total_object_num = 0
        for image_object in image_objects:
            object_struct = {}
            object_struct_small = {}
            xmin, ymin, xmax, ymax = image_object['bbox']
            bbox_w = xmax - xmin
            bbox_h = ymax - ymin

            if bbox_w * bbox_h <= self.small_object_area:
                continue

            total_object_num += 1
            if bbox_h * bbox_w <= small_size:
                small_object_num += 1
            if bbox_h * bbox_w >= large_object_size:
                large_object_num += 1

            object_struct['bbox'] = [xmin, ymin, bbox_w, bbox_h]
            object_struct['segmentation'] = wwtool.bbox2pointobb([xmin, ymin, xmax, ymax])
            object_struct['label'] = 1

            object_struct_small = object_struct.copy()
            object_struct_small['bbox'] = [xmin, ymin, xmax, ymax]
            object_struct_small['label'] = 'ship'
            
            objects_small_save.append(object_struct_small)
            objects.append(object_struct)
        
        if total_object_num > self.max_object_num_per_image:
            self.max_object_num_per_image = total_object_num

        if just_keep_small or generate_small_dataset:
            if small_object_num >= total_object_num * small_object_rate and large_object_num < 1 and len(objects_small_save) > 0:
                # print(os.path.join(dst_image_path, image_file_name + '.png'))
                save_image[0:img_height, 0:img_width, :] = img
                cv2.imwrite(os.path.join(dst_image_path, image_file_name + '.png'), save_image)
                anno_file = os.path.join(dst_label_path, image_file_name + '.txt')
                wwtool.simpletxt_dump(objects_small_save, anno_file)
                return objects
            else:
                return []
        else:
            return objects
예제 #3
0
파일: parse.py 프로젝트: whughw/wwtool
    def generate_sub_mask_anno(self, mask_image, category=(1, 3)):
        height, width, _ = mask_image.shape
        sub_mask_anno = wwtool.generate_image(height, width, color=0)
        gray_mask_image = mask_image[:, :, 0]
        
        if isinstance(category, (list, tuple)):
            keep_bool = np.logical_or(gray_mask_image == category[0], gray_mask_image == category[1])
        else:
            keep_bool = (gray_mask_image == category)

        sub_mask_anno[keep_bool] = 1

        return sub_mask_anno
예제 #4
0
def split_image(img,
                subsize=1024,
                gap=200,
                mode='keep_all',
                expand_boundary=True):
    img_height, img_width = img.shape[0], img.shape[1]

    start_xs = np.arange(0, img_width, subsize - gap)
    if mode == 'keep_all':
        start_xs[-1] = img_width - subsize if img_width - start_xs[
            -1] <= subsize else start_xs[-1]
    elif mode == 'drop_boundary':
        if img_width - start_xs[-1] < subsize - gap:
            start_xs = np.delete(start_xs, -1)
    start_xs[-1] = np.maximum(start_xs[-1], 0)

    start_ys = np.arange(0, img_height, subsize - gap)
    if mode == 'keep_all':
        start_ys[-1] = img_height - subsize if img_height - start_ys[
            -1] <= subsize else start_ys[-1]
    elif mode == 'drop_boundary':
        if img_height - start_ys[-1] < subsize - gap:
            start_ys = np.delete(start_ys, -1)
    start_ys[-1] = np.maximum(start_ys[-1], 0)

    subimages = dict()

    for start_x in start_xs:
        for start_y in start_ys:
            end_x = np.minimum(start_x + subsize, img_width)
            end_y = np.minimum(start_y + subsize, img_height)
            if expand_boundary:
                subimage = wwtool.generate_image(subsize,
                                                 subsize,
                                                 color=(0, 0, 0))
                subimage[0:end_y - start_y, 0:end_x - start_x,
                         ...] = img[start_y:end_y, start_x:end_x, ...]
            else:
                subimage = img[start_y:end_y, start_x:end_x, ...]
            coordinate = (start_x, start_y)
            subimages[coordinate] = subimage

    return subimages
예제 #5
0
파일: rotation.py 프로젝트: whughw/wwtool
import numpy as np
import wwtool
import mmcv

if __name__ == '__main__':
    thetaobbs = [[400, 400, 300, 150, 45 * np.pi / 180],
                 [600, 600, 300, 200, 135 * np.pi / 180]]
    pointobbs = [wwtool.thetaobb2pointobb(thetaobb) for thetaobb in thetaobbs]

    img = wwtool.generate_image(1024, 1024)
    img_origin = img.copy()
    wwtool.imshow_rbboxes(img, thetaobbs, win_name='origin')

    rotation_angle = 45
    rotation_anchor = [img.shape[0] // 2, img.shape[1] // 2]

    rotated_img = mmcv.imrotate(img_origin, rotation_angle)

    rotated_pointobbs = [
        wwtool.rotate_pointobb(pointobb, rotation_angle * np.pi / 180,
                               rotation_anchor) for pointobb in pointobbs
    ]

    rotated_thetaobbs = [
        wwtool.pointobb2thetaobb(rotated_pointobb)
        for rotated_pointobb in rotated_pointobbs
    ]
    wwtool.imshow_rbboxes(rotated_img, rotated_thetaobbs, win_name='rotated')
예제 #6
0
    def __sn6_parse__(self, label_file, image_file):
        """
        (xmin, ymin, xmax, ymax)
        """
        objects = []
        if self.groundtruth:
            image_file_name = os.path.splitext(os.path.basename(image_file))[0]

            image_name_postfix = image_file_name + '.tif'
            if imageset == 'val':
                if image_name_postfix in valset_image_names:
                    pass
                else:
                    return []

            if imageset == 'train':
                if image_name_postfix in valset_image_names:
                    return []
                else:
                    pass

            save_image = wwtool.generate_image(800, 800, color=(0, 0, 0))
            img = cv2.imread(image_file)
            img_height, img_width, _ = img.shape

            image_name = os.path.basename(image_file).split(
                'SN6_{}_AOI_11_Rotterdam_{}_'.format(
                    imageset_file_name, data_source))[1].split('.tif')[0]
            masks = sn6_parse.sn6_parse(image_name)
            objects_small_save = []
            total_object_num = len(masks)
            small_object_num = 0
            large_object_num = 0
            total_object_num = 0
            for mask in masks:
                object_struct = {}
                object_struct_small = {}
                xmin, ymin, xmax, ymax = wwtool.pointobb2bbox(
                    mask['segmentation'])
                bbox_w = xmax - xmin
                bbox_h = ymax - ymin

                total_object_num += 1
                if bbox_h * bbox_w <= small_size:
                    small_object_num += 1
                if bbox_h * bbox_w >= large_object_size:
                    large_object_num += 1

                object_struct['bbox'] = [xmin, ymin, bbox_w, bbox_h]
                object_struct['segmentation'] = mask['segmentation']
                object_struct['label'] = 1

                object_struct_small = object_struct.copy()
                object_struct_small['bbox'] = [xmin, ymin, xmax, ymax]
                object_struct_small['label'] = 'building'

                objects_small_save.append(object_struct_small)
                objects.append(object_struct)

            if total_object_num > self.max_object_num_per_image:
                self.max_object_num_per_image = total_object_num

            if just_keep_small or generate_small_dataset:
                if small_object_num >= total_object_num * small_object_rate and large_object_num < 1 and len(
                        objects_small_save) > 0:
                    # print(os.path.join(dst_image_path, image_file_name + '.png'))
                    save_image[0:img_height, 0:img_width, :] = img
                    cv2.imwrite(
                        os.path.join(dst_image_path, image_file_name + '.png'),
                        save_image)
                    anno_file = os.path.join(dst_label_path,
                                             image_file_name + '.txt')
                    wwtool.simpletxt_dump(objects_small_save, anno_file)
                    return objects
                else:
                    return []
            else:
                return objects
        else:
            obj_struct = {}
            obj_struct['segmentation'] = [0, 0, 0, 0, 0, 0, 0, 0]
            obj_struct['bbox'] = [0, 0, 0, 0]
            obj_struct['label'] = 0

            objects.append(obj_struct)

            return objects
예제 #7
0
image_file = '/data/buildchange/v0/shanghai/images/L18_106968_219320.jpg'
mask_file = '/data/buildchange/v0/shanghai/anno_v2/L18_106968_219320.png'

image_file_name = os.path.splitext(os.path.basename(image_file))[0]

rgb_img = cv2.imread(image_file)
mask_parser = wwtool.MaskParse()

objects = mask_parser(mask_file, category=(1, 3))

gt_masks = []
for obj in objects:
    mask = obj['segmentation']
    gt_masks.append([mask])

img = wwtool.generate_image(2048, 2048, (0, 0, 0))

COLORS = {'Blue': (0, 130, 200), 'Red': (230, 25, 75), 'Yellow': (255, 225, 25), 'Green': (60, 180, 75), 'Orange': (245, 130, 48), 'Purple': (145, 30, 180), 'Cyan': (70, 240, 240), 'Magenta': (240, 50, 230), 'Lavender': (230, 190, 255), 'Lime': (210, 245, 60), 'Teal': (0, 128, 128), 'Pink': (250, 190, 190), 'Brown': (170, 110, 40), 'Beige': (255, 250, 200), 'Maroon': (128, 0, 0), 'Mint': (170, 255, 195), 'Olive': (128, 128, 0), 'Apricot': (255, 215, 180), 'Navy': (0, 0, 128), 'Grey': (128, 128, 128), 'White': (255, 255, 255), 'Black': (0, 0, 0)}

color_list = list(COLORS.keys())

masks = wwtool.generate_image(2048, 2048)
for idx, gt_mask in enumerate(gt_masks):
    mask = poly2mask(gt_mask, 2048, 2048) * 1
    masks[:, :, 0] = mask * COLORS[color_list[idx % 20]][2]
    masks[:, :, 1] = mask * COLORS[color_list[idx % 20]][1]
    masks[:, :, 2] = mask * COLORS[color_list[idx % 20]][0]
    img += masks

heatmap = wwtool.show_grayscale_as_heatmap(img / 255.0, show=False, return_img=True)
alpha = 0.4
예제 #8
0
        image_file = os.path.join(image_dir, image_fn)
        label_file = os.path.join(label_dir, image_fn.replace('png', 'txt'))
        save_file = os.path.join(save_dir, image_fn)
        img = cv2.imread(image_file)

        with open(label_file, 'r') as f:
            lines = f.readlines()

        gt_masks = []
        for line in lines:
            object_struct = {}
            line = line.rstrip().split(' ')
            mask = [float(_) for _ in line[0:-1]]
            gt_masks.append([mask])

        img_mask = wwtool.generate_image(img_scale, img_scale, (0, 0, 0))

        COLORS = {
            'Blue': (0, 130, 200),
            'Red': (230, 25, 75),
            'Yellow': (255, 225, 25),
            'Green': (60, 180, 75),
            'Orange': (245, 130, 48),
            'Purple': (145, 30, 180),
            'Cyan': (70, 240, 240),
            'Magenta': (240, 50, 230),
            'Lavender': (230, 190, 255),
            'Lime': (210, 245, 60),
            'Teal': (0, 128, 128),
            'Pink': (250, 190, 190),
            'Brown': (170, 110, 40),