コード例 #1
0
def csv_from_xml(directory, path_name=''):
    #First get all images and xml files from path and its subfolders
    image_paths = GetFileList(directory, '.jpg')
    xml_paths = GetFileList(directory, '.xml')
    result_df = pd.DataFrame()
    if not len(image_paths) == len(xml_paths):
        print('number of annotations doesnt match number of images')
        return False
    for image in image_paths:
        target_filename = os.path.join(path_name,
                                       image) if path_name else image
        source_filename = os.path.join(directory, image)
        y_size, x_size, _ = np.array(Image.open(source_filename)).shape
        source_xml = image.replace('.jpg', '.xml')
        txt = open(source_xml, "r").read()
        y_vals = re.findall(r'(?:x>\n)(.*)(?:\n</)', txt)
        ymin_vals = y_vals[::2]
        ymax_vals = y_vals[1::2]
        x_vals = re.findall(r'(?:y>\n)(.*)(?:\n</)', txt)
        xmin_vals = x_vals[::2]
        xmax_vals = x_vals[1::2]
        label_vals = re.findall(r'(?:label>\n)(.*)(?:\n</)', txt)
        label_name_vals = re.findall(r'(?:labelname>\n)(.*)(?:\n</)', txt)
        df = pd.DataFrame()
        df['xmin'] = xmin_vals
        df['xmin'] = df['xmin'].astype(float) * x_size
        df['ymin'] = ymin_vals
        df['ymin'] = df['ymin'].astype(float) * y_size
        df['xmax'] = xmax_vals
        df['xmax'] = df['xmax'].astype(float) * x_size
        df['ymax'] = ymax_vals
        df['ymax'] = df['ymax'].astype(float) * y_size
        df['label'] = label_name_vals
        df['code'] = label_vals
        df['image_path'] = target_filename
        df['image'] = os.path.basename(target_filename)
        result_df = result_df.append(df)


#     Bring image column first
    cols = list(df.columns)
    cols = [cols[-1]] + cols[:-1]
    result_df = result_df[cols]
    return result_df
コード例 #2
0
def csv_from_xml(directory, path_name=""):
    # First get all images and xml files from path and its subfolders
    image_paths = GetFileList(directory, ".jpg")
    xml_paths = GetFileList(directory, ".xml")
    result_df = pd.DataFrame()
    data = {
        'image': [],
        'xmin': [],
        'ymin': [],
        'xmax': [],
        'ymax': [],
        'label': [],
        'code': [],
        'image_path': []
    }
    for image in image_paths:
        target_filename = os.path.join(path_name,
                                       image) if path_name else image
        source_filename = os.path.join(directory, image)
        y_size, x_size, _ = np.array(Image.open(source_filename)).shape
        source_xml = image.replace(".jpg", ".xml")
        #print(source_xml)
        tree = ET.parse(source_xml)
        root = tree.getroot()
        for item in root.iter('bndbox'):
            if item.find('xmin') is None:
                break
            #print("found")
            xmin = item.find('xmin').text
            ymin = item.find('ymin').text
            xmax = item.find('xmax').text
            ymax = item.find('ymax').text
            data["xmin"].append(float(xmin))
            data["ymin"].append(float(ymin))
            data["xmax"].append(float(xmax))
            data["ymax"].append(float(ymax))
            data["label"].append("chair")
            data["code"].append(0)
            data["image_path"].append(target_filename)
            data["image"].append(os.path.basename(target_filename))
    result_df = pd.DataFrame(data)
    return result_df
コード例 #3
0
    parser.add_argument(
        '--box_file', type=str, dest = 'box', default = detection_results_file,
        help='File to save bounding box results to. Default is ' + detection_results_file
    )
    
    parser.add_argument(
        '--postfix', type=str, dest = 'postfix', default = '_catface',
        help='Specify the postfix for images with bounding boxes. Default is "_catface"'
    )
    

    FLAGS = parser.parse_args()

    save_img = not FLAGS.no_save_img

    input_image_paths = GetFileList(FLAGS.input_images)

    print('Found {} input images: {}...'.format(len(input_image_paths), [ os.path.basename(f) for f in input_image_paths[:5]]))

    output_path = FLAGS.output
    if not os.path.exists(output_path):
        os.makedirs(output_path)

    # define YOLO detector
    yolo = YOLO(**{"model_path": FLAGS.model_path,
                "anchors_path": FLAGS.anchors_path,
                "classes_path": FLAGS.classes_path,
                "score" : FLAGS.score,
                "gpu_num" : FLAGS.gpu_num,
                "model_image_size" : (416, 416),
                }
コード例 #4
0
        '--postfix',
        type=str,
        dest='postfix',
        default='_catface',
        help=
        'Specify the postfix for images with bounding boxes. Default is "_catface"'
    )

    FLAGS = parser.parse_args()

    save_img = not FLAGS.no_save_img

    file_types = FLAGS.file_types

    if file_types:
        input_paths = GetFileList(FLAGS.input_path, endings=file_types)
    else:
        input_paths = GetFileList(FLAGS.input_path)

    # Split images and videos
    img_endings = ('.jpg', '.jpg', '.png')
    vid_endings = ('.mp4', '.mpeg', '.mpg', '.avi')

    input_image_paths = []
    input_video_paths = []
    for item in input_paths:
        if item.endswith(img_endings):
            input_image_paths.append(item)
        elif item.endswith(vid_endings):
            input_video_paths.append(item)
コード例 #5
0
def predict_input_dir(yolo, classes_path, no_save_img, postfix, box, input_dir,
                      output_dir):
    """Detect faces in input_dir.
    Args:
        classes_path: parsed args from commandline
        no_save_img: parsed args from commandline
        postfix: parsed args from commandline
        box: parsed args from commandline
        input_dir: input directory with images for detecting faces
        output_dir: output directory for saving images
        yolo: initialized yolo model for faster inferring
    """

    # get images paths from input directory
    input_paths = GetFileList(input_dir)
    # Split images
    img_endings = (".jpg", ".jpeg", ".png")
    input_image_paths = []

    for item in input_paths:
        if item.endswith(img_endings):
            input_image_paths.append(item)

    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    save_img = not no_save_img  # whether to save detected images

    # Make a dataframe for the prediction outputs
    out_df = pd.DataFrame(columns=[
        "image",
        "image_path",
        "xmin",
        "ymin",
        "xmax",
        "ymax",
        "label",
        "confidence",
        "x_size",
        "y_size",
    ])
    # labels to draw on check
    class_file = open(classes_path, "r")
    input_labels = [line.rstrip("\n") for line in class_file.readlines()]
    print("Found {} input labels: {} ...".format(len(input_labels),
                                                 input_labels))
    if input_image_paths:
        print("Found {} input images: {} ...".format(
            len(input_image_paths),
            [os.path.basename(f) for f in input_image_paths[:5]],
        ))
        start = timer()

        # predict every images
        for i, img_path in enumerate(input_image_paths):
            print(img_path)
            prediction, image = detect_object(
                yolo,
                img_path,
                save_img=save_img,
                save_img_path=output_dir,
                postfix=postfix,
            )
            y_size, x_size, _ = np.array(image).shape
            for single_prediction in prediction:
                out_df = out_df.append(
                    pd.DataFrame(
                        [[
                            os.path.basename(img_path.rstrip("\n")),
                            img_path.rstrip("\n"),
                        ] + single_prediction + [x_size, y_size]],
                        columns=[
                            "image",
                            "image_path",
                            "xmin",
                            "ymin",
                            "xmax",
                            "ymax",
                            "label",
                            "confidence",
                            "x_size",
                            "y_size",
                        ],
                    ))
        end = timer()
        print("Processed {} images in {:.1f}sec - {:.1f}FPS".format(
            len(input_image_paths),
            end - start,
            len(input_image_paths) / (end - start),
        ))
        out_df.to_csv(output_dir + '/Detection_Results.csv', index=False)