Created
March 30, 2022 14:51
-
-
Save addam/2e2e5bea6c074a1dc8f86eff0639951a to your computer and use it in GitHub Desktop.
Simple image classifier using Opencv and a Bag of Words model
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import cv2 | |
import numpy as np | |
from tkinter import Tk | |
from tkinter.filedialog import askopenfilename | |
descriptors = [] | |
# evaluate the similarity between two point clouds | |
# enormous robustness against outliers is necessary | |
def score(a, b): | |
result = [] | |
for i in range(a.shape[1]): | |
best, bestd = 0, float("inf") | |
for j in range(b.shape[0]): | |
d = cv2.norm(a[i,:], b[j,:], cv2.NORM_L1) | |
if d < bestd: | |
best = j | |
bestd = d | |
result.append(bestd) | |
# return the sum of 100 smallest distances | |
result.sort() | |
return sum(result[0:100]) | |
def add_score_row(desc): | |
index = len(descriptors) | |
for other in descriptors: | |
sc = round(score(desc, other)) | |
print(sc, end="\t") | |
print() | |
def draw_keypoints(keypoints, mat): | |
color = (255, 128, 0, 25) | |
for kp in keypoints: | |
pt = (round(kp.pt[0]), round(kp.pt[1])) | |
cv2.circle(mat, pt, round(kp.size), color) | |
cv2.imshow("canvas", mat) | |
cv2.waitKey(10) | |
def img_onload(filename): | |
mat = cv2.imread(filename) | |
while mat.shape[1] + mat.shape[0] > 1000: | |
mat = cv2.pyrDown(mat) | |
detector = cv2.AKAZE.create() | |
keypoints, result = detector.compute(mat, detector.detect(mat)) | |
add_score_row(result) | |
draw_keypoints(keypoints, mat) | |
descriptors.append(result) | |
# the GUI part does cannot be ported that directly from HTML | |
# it just does not work the same | |
Tk().withdraw() | |
while True: | |
name = askopenfilename() | |
if not name: | |
break | |
img_onload(name) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment