コード例 #1
0
def main(directory: str, delay: int, max_cnt: int, thickness: int,
         labels_path: str, show_box_centres: bool):
    xml_paths = glob.glob(os.path.join(directory, "*.xml"))  # Search for xml files
    max_cnt = max_cnt if max_cnt >= 0 else len(xml_paths)
    cnt = 0
    # Read labels from file
    show_labels = labels_path is not None
    if show_labels:
        with open(labels_path, 'r') as token:
            labels = token.read().split('\n')
        pass
    else:
        labels = None

    for xml_path in xml_paths:
        if cnt >= max_cnt:
            break

        xml_obj = XMLImage(xml_path=xml_path)
        img_path = xml_obj.image_path()
        image = cv2.imread(img_path)
        draw_bounding_boxes(image, xml_obj.boxes_classes, labels=labels, thickness=thickness, delay=delay,
                            dot_center=show_box_centres)
        cnt += 1
        pass  # for xml_path
    pass  # def main
コード例 #2
0
def main(directory: str, shape2d: Tuple[int, int]):
    # Counters
    print(type(shape2d), shape2d)
    shape2d = (int(shape2d[0]), int(shape2d[1]))
    print(type(shape2d), shape2d)
    cnt = 0
    cnt_no_resize_needed = 0
    paths = glob.glob(f"{directory}/*.xml")
    print(f"Found {len(paths)} xml files in {directory}")

    for xml_path in paths:
        cnt += 1
        xml_obj = XMLImage(xml_path=xml_path)
        image_path = xml_obj.image_path()
        image = cv2.imread(image_path)
        if xml_obj.height == shape2d[1] and xml_obj.width == shape2d[0]:
            cnt_no_resize_needed += 1
            continue
        image, xml_obj = resize(image, shape2d, xml_obj)

        cv2.imwrite(image_path, image)
        xml_obj.save()
        pass
    # Show summarry
    print(
        f"Processed {cnt} images. {cnt_no_resize_needed} image were already in good size. Output size was {shape2d}."
    )
    pass
コード例 #3
0
def main(read_directory: str, save_directory: str, sub_size, prepare_size):
    xml_paths = glob.glob(f"{read_directory}/*.xml")
    Trace(f"read_directory is '{read_directory}' got {len(xml_paths)} to '{save_directory}'\nsub_size is {sub_size}"
          f"\tprepare_size is {prepare_size}", Trace.TRACE_INFO, __file__, main.__name__)

    for xml_path in xml_paths:
        # Create xml object
        xml_obj = XMLImage(xml_path=xml_path)
        # Read image path
        img_path = xml_obj.image_path()
        # Read image
        image = cv2.imread(img_path)
        # Run workflow
        list_image, list_xml_obj = workflow(image, sub_size, prepare_size, xml_obj)
        for i in range(len(list_image)):
            # Save sub data
            sub_image = list_image[i]
            sub_xml_obj = list_xml_obj[i]

            img_file_name = create_sub_name(img_path, i, save_directory)
            sub_xml_obj.image_filename = img_file_name.split(settings.SLASH)[-1]

            cv2.imwrite(img_file_name, sub_image)
            sub_xml_obj.save(create_sub_name(xml_path, i, save_directory))
            pass  # for i
        pass  # for xml_path
    pass  # main
コード例 #4
0
def correct_labels(directory: str, shape: Tuple[int, int], old_label: str,
                   new_label: str, del_label: str, change_type: int):
    if change_type == LOWER_CASE:
        change_function = str.lower
    elif change_type == UPPER_CASE:
        change_function = str.upper
    elif change_type == TITLE:
        change_function = str.title
    else:
        change_function = str

    switch_labels = bool(old_label) and bool(new_label)
    delete_label_flag = bool(del_label)
    any_change = switch_labels or (change_function
                                   is not str) or delete_label_flag

    if not any_change:
        Trace(f"\nNo change needed.\n", Trace.TRACE_INFO, __file__,
              correct_labels.__name__)
        return

    old_label = old_label.lower()
    del_label = del_label.lower()

    xml_paths = glob.glob(os.path.join(directory, '*.xml'))
    for xml_path in xml_paths:
        # Read
        xml_obj = XMLImage(xml_path=xml_path)
        # Edit
        index = -1
        to_delete = []
        for box in xml_obj.boxes_classes:
            index += 1
            # Delete label
            if delete_label_flag and box.label.lower() == del_label:
                to_delete.append(index)
                # xml_obj.boxes_classes.pop(index)
                continue

            # Switch label
            if switch_labels and box.label.lower() == old_label:
                box.label = new_label

            # Correct label
            box.label = change_function(box.label).strip()
            pass  # for box
        for i in range(len(to_delete) - 1, -1, -1):
            xml_obj.boxes_classes.pop(to_delete[i])

        # Save
        xml_obj.save()
        pass  # for xml_path
    pass
コード例 #5
0
def black_bars(image: settings.CV2_IMAGE, shape2d,
               xml_obj: XMLImage) -> Tuple[settings.CV2_IMAGE, XMLImage]:
    h_img, w_img = image.shape
    h_out, w_out = shape2d
    if h_img > h_out or w_img > w_out:
        Trace(
            f"Given image ({image.shape}) is bigger than give output ({shape2d})",
            Trace.TRACE_WARNING, __file__, black_bars.__name__)
        image = image[:h_img, :w_img]
        pass
    new_image = np.zeros(shape2d).astype('uint8')
    new_image[:h_img, :w_img] = image
    return new_image, xml_obj.black_bars(shape2d)
コード例 #6
0
def check_img_sizes_from_xml(directory):
    # Read all xml files in directory
    paths = glob.glob(f"{directory}/*.xml")
    # Show info
    print(f"Found {len(paths)} xml files in {directory}")
    # Prepare dict
    img_shapes = dict()
    box_areas = dict()
    labels = dict()
    # Read all sizes from xml files:
    for xml_path in paths:
        xml_obj = XMLImage(xml_path=xml_path)
        img_size = (xml_obj.width, xml_obj.height, xml_obj.depth)
        # Store size
        add_key_counter(img_size, img_shapes)

        for box in xml_obj.boxes_classes:
            # Box label
            label = box.label
            add_key_counter(label, labels)
            # Box area
            b_area = box.area
            add_key_counter(b_area, box_areas)
        pass
    # Show counted sizes
    print(f'Image size:')
    for key, value in img_shapes.items():
        print(
            f"\t{'x'.join([str(elem) for elem in key]).ljust(10)} -> {value} time(s)"
        )
        pass

    print(f'\nLabels:')
    # Show counted labels
    for key, value in labels.items():
        _key = ("'" + key + "'").ljust(10)
        print(f"\t{_key} -> {value} time(s)")
        pass

    # print(f'\nBounding boxes:')
    # for key, value in box_areas.items():
    #     print(f"\t{str(key).ljust(6)} -> {value} time(s)")
    #     pass
    pass
コード例 #7
0
def xml_to_csv2(path: str):
    xml_list = []
    xml_paths = glob.glob(path + '/*.xml')
    print(f"Got {len(xml_paths)} in directory {path}")
    for xml_path in xml_paths:
        xml_obj = XMLImage(xml_path=xml_path)
        filename = xml_obj.image_filename
        width = xml_obj.width
        height = xml_obj.height
        for box in xml_obj.boxes_classes:
            value = [
                filename, width, height, box.label, box.x_min, box.y_min,
                box.x_max, box.y_max
            ]
            xml_list.append(value)
            pass  # for box
        pass  # for xml_path
    column_name = [
        'filename', 'width', 'height', 'class', 'xmin', 'ymin', 'xmax', 'ymax'
    ]
    xml_df = pd.DataFrame(xml_list, columns=column_name)
    return xml_df
コード例 #8
0
def resize(image: settings.CV2_IMAGE, shape2d,
           xml_obj: XMLImage) -> Tuple[settings.CV2_IMAGE, XMLImage]:
    return cv2.resize(image, shape2d[:2]), xml_obj.resize(shape2d)