File size: 2,121 Bytes
16a0f31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
from tqdm import tqdm
import os
from pathlib import Path
import numpy as np

from evaluation.utils.json_helpers import dict_to_json


# -----------------------------------------------------------------------------
#  This class is a sample code provided to help you with saving your predicted
#  scores as JSON files. We strongly suggest that you use the provided methods,
#  but you are NOT required to follow this structure. Feel free to adapt,
#  modify, or extend this template in favor of your own workflow.
# -----------------------------------------------------------------------------
class DumpScores:
    def __init__(self):
        self.scores_dir = "./output_scores"
        self.save_scores_precision = 4

    def save_scores(self, image_path_list, pred_img_level, pred_pix_level):
        print(
            f"Saving scores at '{self.scores_dir}' with precision: '{self.save_scores_precision}'"
        )
        for i in tqdm(range(len(image_path_list)), desc=f"Saving scores"):
            image_path = image_path_list[i]
            image_score_path = self.get_scores_path_for_image(image_path)
            os.makedirs(os.path.dirname(image_score_path), exist_ok=True)

            vectorized_enforce_precision = np.vectorize(self.enforce_precision)
            d = {
                "img_level_score": vectorized_enforce_precision(
                    pred_img_level[i], self.save_scores_precision
                ),
                "pix_level_score": vectorized_enforce_precision(
                    pred_pix_level[i], self.save_scores_precision
                ),
            }
            dict_to_json(d, image_score_path)

    def get_scores_path_for_image(self, image_path):
        """example image_path: './data/photovoltaic_module/test/good/037.png'"""
        path = Path(image_path)

        category, split, anomaly_type = path.parts[-4:-1]
        image_name = path.stem

        return os.path.join(
            self.scores_dir, category, split, anomaly_type, f"{image_name}_scores.json"
        )

    def enforce_precision(self, x, precision):
        return float(f"{x:.{precision}f}")