File size: 2,991 Bytes
5bf30ef
dead143
 
5bf30ef
dead143
 
 
 
 
 
 
 
f8bc55b
 
 
 
 
 
dead143
f8bc55b
dead143
 
10412fe
 
 
 
 
f8bc55b
10412fe
dead143
f8bc55b
 
 
 
 
dead143
f8bc55b
dead143
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5bf30ef
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import onnxruntime as ort
import numpy as np
from numpy.linalg import norm

def load_model(path):
    return ort.InferenceSession(path, providers=["CUDAExecutionProvider","CPUExecutionProvider"])

def cosine_similarity(a, b):
    a = a / (norm(a) + 1e-8)
    b = b / (norm(b) + 1e-8)
    return float(np.dot(a, b))

def predict_image(model, image, ref_emb, thres=0.55):
    """
    ref_emb: 1-D (single reference) or 2-D (k cluster centers, shape [k, dim]).
    When 2-D, sim = max cosine similarity to any cluster center.
    Returns (is_in_criteria: bool, prob: float, sim: float).
    """
    inp = model.get_inputs()[0].name
    out_map = {o.name: i for i, o in enumerate(model.get_outputs())}

    outs = model.run(None, {inp: image})

    missing = [k for k in ("embedding", "probability") if k not in out_map]
    if missing:
        raise KeyError(f"Model output missing expected keys: {missing}. Found: {list(out_map.keys())}")

    emb  = outs[out_map["embedding"]].squeeze().astype(np.float32)
    prob = float(outs[out_map["probability"]].squeeze())

    # Multi-center: take max similarity to any cluster center
    if ref_emb.ndim == 2:
        sim = float(max(cosine_similarity(emb, c) for c in ref_emb))
    else:
        sim = cosine_similarity(emb, ref_emb)

    return sim >= thres, prob, sim

if __name__ == "__main__":
    from utils import preprocess_image

    MODEL_PATH   = "/mnt/d/pig/api/resource/model_2c_v1_emb.onnx"
    REF_EMB_PATH = "/mnt/d/pig/api/resource/avg12_embedding.npy"
    IMAGE_PATH   = "/mnt/d/pig/api/test/data/ec.jpg"
    THRES = 0.75

    sess = load_model(MODEL_PATH)
    ref = np.load(REF_EMB_PATH).astype(np.float32)
    if ref.ndim > 1:
        ref = ref.mean(axis=0)

    x = preprocess_image(IMAGE_PATH)  # [1,3,H,W] float32, ImageNet norm

    flag, prob, sim = predict_image(sess, x, ref, thres=THRES)
    print(f"🔹 Probability = {prob:.4f}")
    print(f"🔹 Similarity  = {sim:.4f}  (≥{THRES}? {flag})")


#################################################################################
# import onnxruntime as ort

# def load_model(MODEL_PATH):
#     return ort.InferenceSession(MODEL_PATH)

# def predict_image(model, image):
#     input_name = model.get_inputs()[0].name
#     output_name = model.get_outputs()[0].name
#     outputs = model.run([output_name], {input_name: image})
#     probability = outputs[0][0][0]
#     # prediction = "bacteria" if probability > 0.5 else "virus"
#     return probability



# if __name__ == "__main__":
#     import os
#     from PIL import Image
#     import numpy as np
#     from utils import preprocess_image

#     MODEL_PATH = "/mnt/d/pig/api/resource/model_2c_v1_tp2.onnx"
#     IMAGE_DIR = "/mnt/d/pig/api/test/data/ec.jpg"

#     # 載入模型
#     model = load_model(MODEL_PATH)
#     print("✅ Model loaded:", MODEL_PATH)

#     x = preprocess_image(IMAGE_DIR)


#     # 預測
#     prob = predict_image(model, x)
#     print(f"🔹 Prediction probability = {prob:.4f}")