Пример #1
0
def get_prediction(image_folder_root,
                   LABELS,
                   cfg_path,
                   weight_path,
                   confidence_level=0.5):
    """
    Run every image in a given folder through darknet.
    Return a list of dictionaries with pertinent information
    about each image: image_path, class_ids, labels, boxes,
    true_labels, and true_boxes.
    """
    # Loads YOLO into Python
    net = get_yolo_net(cfg_path, weight_path)

    # np.random.seed(42)
    # colors = np.random.randint(0, 255, size=(len(LABELS), 3), dtype='uint8')

    # Lists all files in the directory and splits them into two lists:
    # one for images and one for txt files
    files = os.listdir(image_folder_root)
    image_paths = sorted(
        [os.path.join(image_folder_root, f) for f in files if '.jpg' in f])
    txt_paths = sorted(
        [os.path.join(image_folder_root, f) for f in files if '.txt' in f])

    # Loops over each image and txt file in the directory
    results = []
    for image_path, txt_path in zip(image_paths, txt_paths):
        try:
            # Get image height and width
            image = cv2.imread(image_path)
            (H, W) = image.shape[:2]

            # Get darknet prediction data
            class_ids, labels, boxes, confidences = yolo_forward(
                net, LABELS, image, confidence_level)
            print(
                f"SUCCESS: Predicted Class IDs: {class_ids}; Labels: {labels}; for image: {image_path}.\n"
            )
        except Exception:  # Catch occasional errors
            print(f"ERROR: This image had an error: {image_path}")
            continue

        # Reads ground truth data from txt file
        with open(txt_path, "r") as f:
            txt_labels = f.readlines()

        # Splits data into two lists: labels and boxes
        true_labels = [int(label.split()[0]) for label in txt_labels]
        true_boxes = [label.split()[1:] for label in txt_labels]

        # Convert boxes from YOLO dimensions to standard dimensions
        for i, box in enumerate(true_boxes):
            box = [float(num) for num in box]
            true_boxes[i] = yolo_to_standard_dims(box, H, W)

        # Adds pertinent information to a dictionary and adds the dictionary to the return list
        result = {
            'image_path': image_path,
            'class_ids': class_ids,
            'labels': labels,
            'boxes': boxes,
            'confidences': confidences,
            'true_labels': true_labels,
            'true_boxes': true_boxes
        }
        results.append(result)

    return results
Пример #2
0
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 32 * 1024 * 1024

# load the NN to memory
here = os.getcwd()
names_path = os.path.join(here, 'yolo', 'currency_obj.names')
with open(names_path, "r") as f:
    LABELS = f.read().strip().split("\n")
np.random.seed(42)
COLORS = np.random.randint(0, 255, size=(len(LABELS), 3), dtype="uint8")

weights_path = os.path.join(here, 'yolo', 'currency_yolov3_final.weights')
cfg_path = os.path.join(here, 'yolo', 'currency_yolov3.cfg')
net = get_yolo_net(cfg_path, weights_path)


def allowed_file(filename):
    return '.' in filename and filename.rsplit(
        '.', 1)[1].lower() in ALLOWED_EXTENSIONS


# routes definitions
@app.route('/', methods=['GET', 'POST'])
def home():
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            return redirect(
                render_template('home.html', error="Error: No file part"))
Пример #3
0
def evaluate():

    labels = ["Mom's Car"]
    positive_img_dir = os.path.join(os.getcwd(), 'labeled_car_data')
    negative_img_dir = os.path.join(os.getcwd(), 'unlabeled_car_data')
    confidence_level = 0.5
    threshold = 0.3
    img_list = []
    total_counter = 0
    counter = 0

    y_actu = []
    y_pred = []

    net_clement = get_yolo_net('yolov3.cfg', 'yolov3_final.weights')

    for img in os.listdir(positive_img_dir):
        if img.endswith('.JPG'):
            image = cv2.imread(os.path.join(positive_img_dir, img))
            img_detect = yolo_forward(net_clement, labels, image,
                                      confidence_level, threshold)
            total_counter += 1
            if img_detect == ([], [], [], []):
                y_actu.append(1)
                y_pred.append(0)
                continue
            else:
                img_list.append(img_detect)
                print(img_detect)
                counter += 1
                y_actu.append(1)
                y_pred.append(1)
        else:
            continue

    for img in os.listdir(negative_img_dir):
        if img.endswith('.JPG'):
            image = cv2.imread(os.path.join(negative_img_dir, img))
            img_detect = yolo_forward(net_clement, labels, image,
                                      confidence_level, threshold)
            total_counter += 1
            if img_detect == ([], [], [], []):
                y_actu.append(0)
                y_pred.append(0)
                continue
            else:
                img_list.append(img_detect)
                print(img_detect)
                counter += 1
                y_actu.append(0)
                y_pred.append(1)
        else:
            continue

    print('\n{} images detected out of {} total'.format(
        counter, total_counter))

    moms_car_counter = 0

    for i in img_list:
        moms_car_counter += len(i[0])

    print("Mom's car detected {} times".format(moms_car_counter))

    return y_actu, y_pred