Compare commits

..

No commits in common. "8af553236e00b2c415fd814b4a1abe06b3a44c34" and "57906d2a44c3c6ea2e6c2abd510ed72c7b95c667" have entirely different histories.

2 changed files with 20 additions and 43 deletions

View File

@ -52,7 +52,7 @@ class CVSuiteTestKNN:
for row in data: for row in data:
tree = row.pop(0) tree = row.pop(0)
photoId = row.pop(1) # photoId = row.pop(1)
id = Tree[tree.upper()] id = Tree[tree.upper()]
# print("Tree name =", tree, " id =", id.value) # print("Tree name =", tree, " id =", id.value)
@ -104,16 +104,14 @@ class CVSuiteTestKNN:
if self.trained: if self.trained:
raise EnvironmentError("Model already trained!") raise EnvironmentError("Model already trained!")
else: else:
print(data)
print(data.shape)
self.knn.train(data, cv.ml.ROW_SAMPLE, tags) self.knn.train(data, cv.ml.ROW_SAMPLE, tags)
# Save it # Save it
now = datetime.datetime.now() now = datetime.datetime.now()
self.knn.save(os.path.join(output, F"model_knn_{now.strftime('%Y-%m-%dT%H.%M.%S')}.yaml")) self.knn.save(os.path.join(output, F"model_knn_{now.strftime('%Y-%m-%dT%H.%M.%S')}.yaml"))
def predict(self, data, nr = 3): def predict(self, data):
return self.knn.findNearest(data, nr) return self.knn.predict(data)
if __name__ == "__main__": if __name__ == "__main__":
args = parser.parse_args() args = parser.parse_args()

View File

@ -14,12 +14,7 @@ import json
# OpenCV # OpenCV
import numpy as np import numpy as np
import cv2 import cv2
from sklearn.preprocessing import ( from sklearn.preprocessing import MinMaxScaler, StandardScaler, RobustScaler, MaxAbsScaler
MinMaxScaler,
StandardScaler,
RobustScaler,
MaxAbsScaler,
)
import joblib import joblib
# GUI # GUI
@ -31,11 +26,9 @@ from helpers.statistics import imgStats
from helpers.logger import CVSuiteLogger, C_DBUG, C_WARN from helpers.logger import CVSuiteLogger, C_DBUG, C_WARN
from helpers.canvas import CVSuiteCanvas from helpers.canvas import CVSuiteCanvas
from helpers.sift import getSiftData from helpers.sift import getSiftData
from helpers.tags import Tree
# Tests # Tests
from helpers.test.knn import CVSuiteTestKNN from helpers.test.knn import CVSuiteTestKNN
# from helpers.test.decision_tree import CVSuiteTestDecisionTree # from helpers.test.decision_tree import CVSuiteTestDecisionTree
## UI config load ## UI config load
@ -48,7 +41,6 @@ CONFIG_PATH = "./src/config/config.json"
config_file = open(CONFIG_PATH, encoding="utf-8") config_file = open(CONFIG_PATH, encoding="utf-8")
config_json = json.load(config_file) config_json = json.load(config_file)
## UI class setup ## UI class setup
class CVSuite: class CVSuite:
def __init__(self, master=None): def __init__(self, master=None):
@ -105,6 +97,7 @@ class CVSuite:
# Attempt to load scaler # Attempt to load scaler
if config_json["scaler"] != "": if config_json["scaler"] != "":
self.scaler = joblib.load(config_json["scaler"]) self.scaler = joblib.load(config_json["scaler"])
print(self.scaler)
else: else:
self.scaler = None self.scaler = None
@ -115,9 +108,7 @@ class CVSuite:
self.test_knn = None self.test_knn = None
if config_json["models"]["dectree"] != "": if config_json["models"]["dectree"] != "":
self.test_dectree = CVSuiteTestDecisionTree( self.test_dectree = CVSuiteTestDecisionTree(config_json["models"]["dectree"])
config_json["models"]["dectree"]
)
else: else:
self.test_dectree = None self.test_dectree = None
@ -312,39 +303,26 @@ class CVSuite:
output.configure(state="normal") output.configure(state="normal")
output.delete(1.0, "end") output.delete(1.0, "end")
# Remove tag and photoId # Normalise data
tag = data.pop(0) tag = data.pop(0)
photoId = data.pop(1) photoId = data.pop(1)
# Add actual name
output.insert("end", f"Actual:\n\t{tag.upper()}\n")
# Normalise data using loaded scalers
for idx, value in enumerate(data): for idx, value in enumerate(data):
d = np.array(value) data[idx] = self.scaler[idx].transform(np.array(value).reshape(-1, 1))
data[idx] = self.scaler[idx].transform(d.astype(np.float32).reshape(1, -1))[0][0]
data = np.array([data], dtype=np.float32) print(data)
if self.test_knn is not None: if self.test_knn is not None:
# Do knn test # Do knn test
output.insert("end", "KNN Result:\n") output.insert("end", "KNN Result:\n")
pass
ret, results, neighbours ,dist = self.test_knn.predict(data)
for idx, res_id in enumerate(neighbours[0]):
output.insert("end", f" {idx}:\t{Tree(res_id).name}\n")
print(C_DBUG, "KNN Result:")
print("\t\tresult: \t{}".format(results) )
print("\t\tneighbours:\t{}".format(neighbours) )
print("\t\tdistance:\t{}".format(dist) )
else: else:
print(C_WARN, "KNN Model not configured!") print(C_WARN, "KNN Model not configured!")
if self.test_dectree is not None: if self.test_dectree is not None:
print(self.test_dectree.predict(data)) print(self.test_dectree.predict(data))
output.insert("end", "Decision Tree Result:\n") output.insert("end", "Decision Tree Result:\n")
pass
else: else:
print(C_WARN, "Decison Tree Model not configured!") print(C_WARN, "Decison Tree Model not configured!")
@ -389,11 +367,11 @@ class CVSuite:
print("Full update forced!") print("Full update forced!")
if self.updatePath(): if self.updatePath():
print(C_DBUG, f"Processing {self.img_name}") print(C_DBUG, F"Processing {self.img_name}")
self.mainwindow.title(f"{TITLE} - {self.img_name}") self.mainwindow.title(F"{TITLE} - {self.img_name}")
self.log.add("Tree", self.img_name.split("_")[0]) self.log.add("Tree", self.img_name.split("_")[0])
self.log.add("ID", self.img_name.split("_")[1].split(".")[0]) self.log.add("ID", self.img_name.split("_")[1].split('.')[0])
# Get all user vars # Get all user vars
ct1 = self.canny_thr1.get() ct1 = self.canny_thr1.get()
@ -489,9 +467,11 @@ class CVSuite:
self.log.add("SIFT total response", siftData[5]) self.log.add("SIFT total response", siftData[5])
self.log.add("SIFT average response", siftData[6]) self.log.add("SIFT average response", siftData[6])
# Run tests
self.runTest(self.log.data)
# Write results to CSV file # Write results to CSV file
if not part_update: if not part_update:
self.runTest(self.log.data)
self.log.update() self.log.update()
else: else:
self.log.clear() # Prevent partial updates from breaking log self.log.clear() # Prevent partial updates from breaking log
@ -500,7 +480,6 @@ class CVSuite:
plt.show(block=False) ## Graphs plt.show(block=False) ## Graphs
self.canvas.draw(size) ## Images self.canvas.draw(size) ## Images
if __name__ == "__main__": if __name__ == "__main__":
app = CVSuite() app = CVSuite()
app.run() app.run()