-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpredict_genetic_ucid.py
More file actions
146 lines (121 loc) · 5.95 KB
/
Copy pathpredict_genetic_ucid.py
File metadata and controls
146 lines (121 loc) · 5.95 KB
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
# predict_genetic_ucid.py
# -*- coding: utf-8 -*-
import os, sys, argparse
import numpy as np
import cv2
import tensorflow as tf
sys.path.append(r"D:\Imhistory\ImageHistory\utils")
from Network import *
# ---- GA weights of UCID dataset (SE-Dense, SE-Inception, SE-ResNet50, ViT) ----
GA_WEIGHTS = {
75: [0.20061, 0.28446, 0.14702, 0.36790],
85: [0.23021, 0.40494, 0.04245, 0.32239],
95: [0.06745, 0.33683, 0.18399, 0.41174],
}
# # ---- GA weights of BOSSBASE (SE-Dense, SE-Inception, SE-ResNet50, ViT) ----
# GA_WEIGHTS = {
# 75: [0.13952, 0.46086, 0.01697, 0.38264],
# 85: [0.16546, 0.22289, 0.26274, 0.34891],
# 95: [0.09371, 0.45073, 0.00427, 0.45129],
# }
# # ---- GA weights of IMAGENET-Mini10K (SE-Dense, SE-Inception, SE-ResNet50, ViT) ----
# GA_WEIGHTS = {
# 75: [0.34034, 0.22858, 0.03842, 0.39266],
# 85: [0.29683, 0.46990, 0.11377, 0.11949],
# 95: [ 0.00265, 0.49270, 0.39497, 0.10968],
# }
IMHIST_CLASSES = ["Adjustment", "Denoising", "Highpass", "Lowpass", "Uniform"]
def load_image(path, size=(512,512)):
img = cv2.imread(path, 1)
if img is None:
raise FileNotFoundError(f"Image not found: {path}")
# img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# img = cv2.resize(img, size, interpolation=cv2.INTER_AREA)
img = img.astype(np.float32) / img.max()
return img
def build_and_load(model_selection, weights_path, input_shape, optimizer, loss, metric, height, width, dropbool, tf_bool, transformer_type, suffix):
model = get_Network(tf_bool, len(IMHIST_CLASSES), input_shape, loss, optimizer, metric,
height, width, dropbool, model_selection, transformer_type)
model.load_weights(weights_path)
model.compile(loss=loss, optimizer=optimizer, metrics=[metric])
# isim çakışmasın diye
for i, layer in enumerate(model.layers):
try:
layer._name = f"{layer.name}_{suffix}_{i}"
except Exception:
pass
return model
def softmax_ensemble(weights, probs_stack):
"""
weights: (M,), probs_stack: (M, C)
dönen: (C,) (ensemble olasılıkları)
"""
w = np.array(weights, dtype=np.float64)
w = w / np.sum(w)
ens = np.tensordot(w, probs_stack, axes=1) # (C,)
return ens
def main(args):
# ---- Parametreler (eğitim yapılmıyor, derleme için lazım) ----
num_classes = len(IMHIST_CLASSES)
height, width, n_channels = 512, 512, 3
input_shape = (height, width, n_channels)
loss = "categorical_crossentropy"
metric = ["categorical_accuracy"]
dropbool = 1
tf_bool = 2 # 1: pretrained, 2: None (senin koddaki gibi)
transformer_type = 2 # 1-b16, 2-b32, 3-l16, 4-l32
# Optimizer sadece compile için
from tensorflow.keras.optimizers import SGD
optimizer = SGD(learning_rate=0.0002, decay=1e-6, momentum=0.9, nesterov=True)
# ---- Model yolları (senin yapına göre) ----
# Not: Aşağıdaki yollar QF=75 klasörlerinden; 85/95 için de aynı mimariye ait en iyi ağırlıkların yolunu ver.
w_dense = r"D:\Imhistory\ImageHistory\Ensemble_Models\UCID\Ucid_75_Imhistory_weights1_SEDensenet.hdf5"
w_incp = r"D:\Imhistory\ImageHistory\Ensemble_Models\UCID\Ucid_75_Imhistory_weights1_SEInception.hdf5"
w_res = r"D:\Imhistory\ImageHistory\Ensemble_Models\UCID\Ucid_75_Imhistory_weights1_SEResnet.hdf5"
w_vit = r"D:\Imhistory\ImageHistory\Ensemble_Models\UCID\Ucid_75_Imhistory_weights1_Transformer.hdf5"
# ---- Görüntü ----
img = load_image(args.image, size=(width, height))
x = np.expand_dims(img, axis=0) # (1, H, W, 3)
# ---- Modelleri kur/yükle ----
# model_selection: 3: SE-DenseNet121, 4: SE-InceptionV3, 2: SE-ResNet50, 1: ViT
m_dense = build_and_load(3, w_dense, input_shape, optimizer, loss, metric, height, width, dropbool, tf_bool, transformer_type, "sedense121")
m_incp = build_and_load(4, w_incp, input_shape, optimizer, loss, metric, height, width, dropbool, tf_bool, transformer_type, "seinceptionv3")
m_res = build_and_load(2, w_res, input_shape, optimizer, loss, metric, height, width, dropbool, tf_bool, transformer_type, "seresnet50")
m_vit = build_and_load(1, w_vit, input_shape, optimizer, loss, metric, height, width, dropbool, tf_bool, transformer_type, "vitb32")
models = [m_dense, m_incp, m_res, m_vit]
# ---- Tek görüntü tahminleri ----
probs_stack = []
for m in models:
p = m.predict(x, verbose=0)[0] # (C,)
probs_stack.append(p)
probs_stack = np.stack(probs_stack, axis=0) # (M, C)
# ---- GA ağırlıkları ----
if args.qf not in GA_WEIGHTS:
raise ValueError(f"Unsupported QF={args.qf}. Choose from 75, 85, 95.")
weights = GA_WEIGHTS[args.qf]
ens_probs = softmax_ensemble(weights, probs_stack) # (C,)
pred_idx = int(np.argmax(ens_probs))
pred_lab = IMHIST_CLASSES[pred_idx]
# ---- Çıktı yazdır ----
print("\n== Single-Image Prediction ==")
print(f"Image: {args.image}")
print(f"QF: {args.qf} | GA Weights: {np.round(weights, 5).tolist()}")
print("Class probabilities:")
for i, c in enumerate(IMHIST_CLASSES):
print(f" {c:10s}: {ens_probs[i]:.4f}")
print(f"\nPredicted: {pred_lab} (idx={pred_idx})\n")
# if __name__ == "__main__":
# ap = argparse.ArgumentParser()
# ap.add_argument("--image", type=str, required=True, help=r"D:\Imhistory\ImageHistory\Datasets\UCID\Test\QF=75\Adjustment\3_uniformT75_adj1.jpg)")
# ap.add_argument("--qf", type=int, default=75, choices=[75,85,95], help="JPEG quality factor used in pipeline")
# args = ap.parse_args()
# main(args)
# Run cmd
# python predict_single_ucid.py --image "D:\Imhistory\ImageHistory\Datasets\UCID\Test\QF=75\Adjustment\3_uniformT75_adj1.jpg" --qf 75
if __name__ == "__main__":
# Spyder'da doğrudan çalıştırmak için argümanları burada tanımla
class Args:
image = r"D:\Imhistory\ImageHistory\Datasets\UCID\Test\QF=75\Uniform\3_uniformT75.jpg"
qf = 75
args = Args()
main(args)