├── .gitignore ├── HoVW ├── build_master_dir.sh ├── classification │ ├── __init__.py │ ├── classify-nodes.py │ ├── kmeans-nodes-test.py │ ├── meanshift-test.py │ └── split-train-test.py ├── executions.py ├── pipeline.bat ├── pipeline.sh ├── requirements.txt ├── src │ ├── __init__.py │ ├── assign-node-label.py │ ├── assign-tree-label.py │ ├── centers_dendrogram.py │ ├── clusters.py │ ├── descriptors.py │ ├── fit.py │ ├── image.py │ ├── index.py │ ├── kmeans-nodes-test.py │ ├── kmeans-nodes.py │ ├── meanshift-graphs-test.py │ ├── meanshift-graphs.py │ ├── pickle4reducer.py │ ├── tree.py │ ├── trees-distance.py │ └── utils.py └── views │ ├── find_clusters_neighbor.py │ ├── reveal_clusters-graphs.py │ ├── reveal_clusters-nodes.py │ ├── visualize_graph_spatial_distribution.py │ └── visualize_node_spatial_distribution.py ├── LICENSE ├── README.md └── wheels └── mahotas-1.4.4-cp36-cp36m-win_amd64.whl /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_STORE 2 | hovw-ce2 3 | docs/code 4 | datasets/ce2/* 5 | datasets/mpeg7-png/* 6 | # HoVW 7 | HoVW/API 8 | HoVW/databases 9 | HoVW/evaluation 10 | HoVW/exec 11 | HoVW/manifolds 12 | HoVW/others 13 | HoVW/Master/clusters 14 | HoVW/Master/images 15 | HoVW/Master/data/* 16 | HoVW/Master/dataset/* 17 | HoVW/Master/datasetOutput/* 18 | HoVW/src/precison_recall_test* 19 | HoVW/src/others 20 | HoVW/executions.py 21 | *.png 22 | *.jpg 23 | *.jpeg 24 | *.tiff 25 | *.tif 26 | *.pickle 27 | *.clr 28 | *.dict 29 | *.npy 30 | *.npz 31 | *.cb 32 | *.descriptor 33 | *.log 34 | *.codeword 35 | *.bagw 36 | *.txt 37 | !requirements.txt 38 | *.potato 39 | *.zip 40 | 41 | # Windows 42 | desktop.ini 43 | *.exe 44 | 45 | # VScode 46 | .vscode/ 47 | 48 | # Byte-compiled / optimized / DLL files 49 | __pycache__/ 50 | *.py[cod] 51 | *$py.class 52 | 53 | # C extensions 54 | *.so 55 | 56 | # Distribution / packaging 57 | .Python 58 | build/ 59 | develop-eggs/ 60 | dist/ 61 | downloads/ 62 | eggs/ 63 | .eggs/ 64 | lib/ 65 | lib64/ 66 | parts/ 67 | sdist/ 68 | var/ 69 | *.egg-info/ 70 | .installed.cfg 71 | *.egg 72 | MANIFEST 73 | 74 | # PyInstaller 75 | # Usually these files are written by a python script from a template 76 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 77 | *.manifest 78 | *.spec 79 | 80 | # Installer logs 81 | pip-log.txt 82 | pip-delete-this-directory.txt 83 | 84 | # Unit test / coverage reports 85 | htmlcov/ 86 | .tox/ 87 | .coverage 88 | .coverage.* 89 | .cache 90 | nosetests.xml 91 | coverage.xml 92 | *.cover 93 | .hypothesis/ 94 | .pytest_cache/ 95 | 96 | # Translations 97 | *.mo 98 | *.pot 99 | 100 | # Django stuff: 101 | *.log 102 | local_settings.py 103 | db.sqlite3 104 | 105 | # Flask stuff: 106 | instance/ 107 | .webassets-cache 108 | 109 | # Scrapy stuff: 110 | .scrapy 111 | 112 | # Sphinx documentation 113 | docs/_build/ 114 | 115 | # PyBuilder 116 | target/ 117 | 118 | # Jupyter Notebook 119 | .ipynb_checkpoints 120 | 121 | # pyenv 122 | .python-version 123 | 124 | # celery beat schedule file 125 | celerybeat-schedule 126 | 127 | # SageMath parsed files 128 | *.sage.py 129 | 130 | # Environments 131 | .env 132 | .venv 133 | env/ 134 | venv/ 135 | ENV/ 136 | env.bak/ 137 | venv.bak/ 138 | 139 | # Spyder project settings 140 | .spyderproject 141 | .spyproject 142 | 143 | # Rope project settings 144 | .ropeproject 145 | 146 | # mkdocs documentation 147 | /site 148 | 149 | # mypy 150 | .mypy_cache/ 151 | -------------------------------------------------------------------------------- /HoVW/build_master_dir.sh: -------------------------------------------------------------------------------- 1 | MASTER='Master' 2 | DIR_IMAGES=$MASTER'/images' 3 | DIR_DATASET=$MASTER'/dataset' 4 | DIR_DATA=$MASTER'/data' 5 | 6 | DIR_TRAIN=$DIR_DATASET'/train' 7 | DIR_TEST=$DIR_DATASET'/test' 8 | 9 | DIR_OUT=$MASTER'/datasetOutput' 10 | 11 | DIR_BOW=$DIR_OUT'/BOW' 12 | DIR_ASS_KME=$DIR_BOW'/assignment-kme' 13 | DIR_ASS_MSH=$DIR_BOW'/assignment-msh' 14 | DIR_BAG_KME=$DIR_BOW'/bag-kme' 15 | DIR_BAG_MSH=$DIR_BOW'/bag-msh' 16 | 17 | DIR_LOGS=$DIR_OUT'/logs' 18 | DIRC=$DIR_OUT'/descriptor' 19 | 20 | if [ ! -d "$MASTER" ]; then 21 | mkdir $MASTER 22 | echo "mkdir "$MASTER 23 | fi 24 | 25 | if [ ! -d "$DIR_IMAGES" ]; then 26 | mkdir $DIR_IMAGES 27 | echo "mkdir "$DIR_IMAGES 28 | fi 29 | 30 | if [ ! -d "$DIR_DATASET" ]; then 31 | mkdir $DIR_DATASET 32 | echo "mkdir "$DIR_DATASET 33 | fi 34 | 35 | if [ ! -d "$DIR_DATA" ]; then 36 | mkdir $DIR_DATA 37 | echo "mkdir "$DIR_DATA 38 | fi 39 | 40 | if [ ! -d "$DIR_TRAIN" ]; then 41 | mkdir $DIR_TRAIN 42 | echo "mkdir "$DIR_TRAIN 43 | fi 44 | 45 | if [ ! -d "$DIR_TEST" ]; then 46 | mkdir $DIR_TEST 47 | echo "mkdir "$DIR_TEST 48 | fi 49 | 50 | if [ ! -d "$DIR_OUT" ]; then 51 | mkdir $DIR_OUT 52 | echo "mkdir "$DIR_OUT 53 | fi 54 | 55 | if [ ! -d "$DIR_BOW" ]; then 56 | mkdir $DIR_BOW 57 | echo "mkdir "$DIR_BOW 58 | fi 59 | 60 | if [ -d "$DIR_ASS_KME" ]; then 61 | rm -rf $DIR_ASS_KME 62 | mkdir $DIR_ASS_KME 63 | echo "rm -rf | mkdir "$DIR_ASS_KME 64 | else 65 | mkdir $DIR_ASS_KME 66 | echo "mkdir "$DIR_ASS_KME 67 | fi 68 | 69 | if [ -d "$DIR_ASS_MSH" ]; then 70 | rm -rf $DIR_ASS_MSH 71 | mkdir $DIR_ASS_MSH 72 | echo "rm -rf | mkdir "$DIR_ASS_MSH 73 | else 74 | mkdir $DIR_ASS_MSH 75 | echo "mkdir "$DIR_ASS_MSH 76 | fi 77 | 78 | if [ -d "$DIR_BAG_KME" ]; then 79 | rm -rf $DIR_BAG_KME 80 | mkdir $DIR_BAG_KME 81 | echo "rm -rf | mkdir "$DIR_BAG_KME 82 | else 83 | mkdir $DIR_BAG_KME 84 | echo "mkdir "$DIR_BAG_KME 85 | fi 86 | 87 | if [ -d "$DIR_BAG_MSH" ]; then 88 | rm -rf $DIR_BAG_MSH 89 | mkdir $DIR_BAG_MSH 90 | echo "rm -rf | mkdir "$DIR_BAG_MSH 91 | else 92 | mkdir $DIR_BAG_MSH 93 | echo "mkdir "$DIR_DIR_BAG_MSHIMAGES 94 | fi 95 | 96 | if [ -d "$DIR_LOGS" ]; then 97 | rm -rf $DIR_LOGS 98 | mkdir $DIR_LOGS 99 | echo "rm -rf | mkdir "$DIR_LOGS 100 | else 101 | mkdir $DIR_LOGS 102 | echo "mkdir "$DIR_LOGS 103 | fi 104 | 105 | if [ -d "$DIRC" ]; then 106 | rm -rf $DIRC 107 | mkdir $DIRC 108 | echo "rm -rf | mkdir "$DIRC 109 | else 110 | mkdir $DIRC 111 | echo "mkdir "$DIRC 112 | fi 113 | 114 | DIR_OUT=$DIR_OUT'/test' 115 | DIR_BOW=$DIR_OUT'/BOW' 116 | DIR_ASS_KME=$DIR_BOW'/assignment-kme' 117 | DIR_ASS_MSH=$DIR_BOW'/assignment-msh' 118 | DIR_BAG_KME=$DIR_BOW'/bag-kme' 119 | DIR_BAG_MSH=$DIR_BOW'/bag-msh' 120 | 121 | if [ ! -d "$DIR_OUT" ]; then 122 | mkdir $DIR_OUT 123 | fi 124 | 125 | if [ ! -d "$DIR_BOW" ]; then 126 | mkdir $DIR_BOW 127 | fi 128 | 129 | if [ -d "$DIR_ASS_KME" ]; then 130 | rm -rf $DIR_ASS_KME 131 | mkdir $DIR_ASS_KME 132 | echo "rm -rf | mkdir "$DIR_ASS_KME 133 | else 134 | mkdir $DIR_ASS_KME 135 | echo "mkdir "$DIR_ASS_KME 136 | fi 137 | 138 | if [ -d "$DIR_ASS_MSH" ]; then 139 | rm -rf $DIR_ASS_MSH 140 | mkdir $DIR_ASS_MSH 141 | echo "rm -rf | mkdir "$DIR_ASS_MSH 142 | else 143 | mkdir $DIR_ASS_MSH 144 | echo "mkdir "$DIR_ASS_MSH 145 | fi 146 | 147 | if [ -d "$DIR_BAG_KME" ]; then 148 | rm -rf $DIR_BAG_KME 149 | mkdir $DIR_BAG_KME 150 | echo "rm -rf | mkdir "$DIR_BAG_KME 151 | else 152 | mkdir $DIR_BAG_KME 153 | echo "mkdir "$DIR_BAG_KME 154 | fi 155 | 156 | if [ -d "$DIR_BAG_MSH" ]; then 157 | rm -rf $DIR_BAG_MSH 158 | mkdir $DIR_BAG_MSH 159 | echo "rm -rf | mkdir "$DIR_BAG_MSH 160 | else 161 | mkdir $DIR_BAG_MSH 162 | echo "mkdir "$DIR_BAG_MSH 163 | fi -------------------------------------------------------------------------------- /HoVW/classification/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Prograf-UFF/HoVW/4cb3ee59f9a91da877da83504cb4f8a61d1f7951/HoVW/classification/__init__.py -------------------------------------------------------------------------------- /HoVW/classification/classify-nodes.py: -------------------------------------------------------------------------------- 1 | import argparse, pickle, re 2 | from sklearn.svm import LinearSVC 3 | 4 | parser = argparse.ArgumentParser() 5 | parser.add_argument('-i', help='path with data train') 6 | parser.add_argument('-o', help='path with data test') 7 | args = parser.parse_args() 8 | 9 | i_path = args.i 10 | o_path = args.o 11 | 12 | objects = [] 13 | with (open(i_path, "rb")) as openfile: 14 | while True: 15 | try: 16 | objects.append(pickle.load(openfile)) 17 | except EOFError: 18 | break 19 | 20 | im_features = objects[1] 21 | 22 | im_names = [] 23 | for name in objects[0]: 24 | im_names.append(re.sub('-.*', '', objects[0][name])) 25 | 26 | print(im_features.shape, len(im_names)) 27 | 28 | clf = LinearSVC() 29 | clf.fit(im_features, im_names) 30 | 31 | objects = [] 32 | with (open(o_path, "rb")) as openfile: 33 | while True: 34 | try: 35 | objects.append(pickle.load(openfile)) 36 | except EOFError: 37 | break 38 | 39 | im_features = objects[1] 40 | 41 | im_names = [] 42 | for name in objects[0]: 43 | im_names.append(re.sub('-.*', '', objects[0][name])) 44 | 45 | print(im_features.shape, len(im_names)) 46 | 47 | print(clf.score(im_features, im_names)) 48 | -------------------------------------------------------------------------------- /HoVW/classification/kmeans-nodes-test.py: -------------------------------------------------------------------------------- 1 | from sklearn.cluster import KMeans 2 | import numpy as np 3 | from os import listdir, path 4 | import argparse, time, re, pickle 5 | 6 | parser = argparse.ArgumentParser() 7 | parser.add_argument('-i', help='path with images') 8 | parser.add_argument('-o', help='output path') 9 | parser.add_argument('-c', help='clusters') 10 | parser.add_argument('-l', help='logs directory') 11 | 12 | args = parser.parse_args() 13 | 14 | i_path = args.i 15 | o_path = args.o 16 | logs_path = args.l 17 | k_clusters = -1 18 | c_path = args.c 19 | X = np.asarray([[None]*29], dtype=np.float_) #HARD-CODED TEM QUE LER ESSE 29 DO ARQUIVO 20 | y = [] 21 | 22 | for dfile in listdir(i_path): 23 | try: 24 | with open(i_path+dfile, 'r') as f: 25 | print("Reading from " + f.name) 26 | content = f.readlines() 27 | 28 | for i in range(int(content[1])): 29 | X = np.append(X, 30 | [np.array(list(np.float_(e) for e in content[2+i].split(' ')), dtype=np.float_)], 31 | axis=0) 32 | y.append(re.sub('\..*', '', dfile)) 33 | 34 | except KeyboardInterrupt as err: 35 | print("Ctrl + c interruption") 36 | break 37 | except Exception as e: 38 | print("ERROR: " + dfile) 39 | print(e) 40 | break 41 | continue 42 | 43 | X = np.delete(X, 0, 0) 44 | 45 | objects=[] 46 | with (open(c_path, "rb")) as openfile: 47 | while True: 48 | try: 49 | objects.append(pickle.load(openfile)) 50 | except EOFError: 51 | break 52 | 53 | ###Assignment --- Vector quantization 54 | 55 | #PRECISA SER TESTADO EM MAIS CASOS------- 56 | oufl = [] 57 | past = None 58 | count = 0 59 | for i in range(len(y)): 60 | if(y[i] != past): 61 | oufl.append((past, count)) 62 | count = 1 63 | past = y[i] 64 | else: count+=1 65 | past = y[i] 66 | oufl.append((past, count)) 67 | oufl = oufl[1:] 68 | #----- 69 | cluster = objects[0] 70 | k_clusters = cluster.get_params()['n_clusters'] 71 | quantization = cluster.predict(X) 72 | 73 | j = 0 74 | im_names = {} 75 | im_features = np.zeros((len(oufl), k_clusters), np.float_) 76 | name_c = 0 77 | 78 | for e in oufl: 79 | bag = [0] * k_clusters 80 | with open(path.join(o_path, 'BOW/assignment-kme/' + e[0] + '.codeword'), 'w') as fa, \ 81 | open(path.join(o_path, 'BOW/bag-kme/' + e[0] + '.bagw'), 'w') as fb: 82 | #print("Writing " + fa.name + " and " + fb.name) 83 | for i in range(e[1]): 84 | vq = quantization[j] 85 | bag[int(vq)] += 1 86 | ### 87 | im_names[name_c] = e[0] 88 | im_features[name_c][int(vq)] += 1 89 | ### 90 | fa.write(str(vq) + ' ') 91 | fa.write(' '.join(str(k) for k in cluster.cluster_centers_[vq].tolist()) + '\n') 92 | j += 1 93 | ### 94 | name_c += 1 95 | ### 96 | bagf = [k/sum(bag) for k in bag] 97 | fb.write(' '.join(str(k) for k in bagf)) 98 | 99 | with open('Master/data/classf_data-test.pickle', 'wb') as handle: 100 | pickle.dump(im_names, handle, protocol=pickle.HIGHEST_PROTOCOL) 101 | pickle.dump(im_features, handle, protocol=pickle.HIGHEST_PROTOCOL) -------------------------------------------------------------------------------- /HoVW/classification/meanshift-test.py: -------------------------------------------------------------------------------- 1 | from sklearn.cluster import MeanShift 2 | import numpy as np 3 | from os import listdir 4 | import argparse, time, re, pickle 5 | 6 | parser = argparse.ArgumentParser() 7 | parser.add_argument('-i', help='path with images') 8 | parser.add_argument('-o', help='output path') 9 | parser.add_argument('-c', help='clusters') 10 | parser.add_argument('-l', help='logs directory') 11 | 12 | args = parser.parse_args() 13 | 14 | i_path = args.i 15 | o_path = args.o 16 | logs_path = args.l 17 | c_path = args.c 18 | X = np.asarray([[None]*29], dtype=np.float_) #HARD-CODED TEM QUE LER ESSE 29 DO ARQUIVO 19 | y = [] 20 | log = open(logs_path + '/error-clustering-msh.log', 'w') 21 | T_START = time.time() 22 | 23 | for dfile in listdir(i_path): 24 | try: 25 | with open(i_path+dfile, 'r') as f: 26 | print("Reading from " + f.name) 27 | content = f.readlines() 28 | 29 | for i in range(int(content[1])): 30 | X = np.append(X, 31 | [np.array(list(np.float_(e) for e in content[2+i].split(' ')), dtype=np.float_)], 32 | axis=0) 33 | y.append(re.sub('\..*', '', dfile)) 34 | 35 | except KeyboardInterrupt as err: 36 | print("Ctrl + c interruption") 37 | break 38 | except Exception as e: 39 | log.write(dfile + '\n') 40 | print("ERROR: " + dfile) 41 | print(e) 42 | break 43 | continue 44 | 45 | X = np.delete(X, 0, 0) 46 | 47 | objects=[] 48 | with (open(c_path, "rb")) as openfile: 49 | while True: 50 | try: 51 | objects.append(pickle.load(openfile)) 52 | except EOFError: 53 | break 54 | 55 | oufl = [] 56 | past = None 57 | count = 0 58 | for i in range(len(y)): 59 | if(y[i] != past): 60 | oufl.append((past, count)) 61 | count = 1 62 | past = y[i] 63 | else: count+=1 64 | past = y[i] 65 | oufl.append((past, count)) 66 | oufl = oufl[1:] 67 | 68 | cluster_count = len(objects[0].cluster_centers_)+1 69 | quantization = objects[0].predict(X) 70 | 71 | j = 0 72 | im_names = {} 73 | im_features = np.zeros((len(oufl), cluster_count), np.float_) 74 | name_c = 0 75 | 76 | for e in oufl: 77 | for i in range(e[1]): 78 | vq = quantization[j] 79 | im_names[name_c] = e[0] 80 | im_features[name_c][int(vq)] += 1 81 | j += 1 82 | name_c += 1 83 | 84 | with open('classf_data-test.pickle', 'wb') as handle: 85 | pickle.dump(im_names, handle, protocol=pickle.HIGHEST_PROTOCOL) 86 | pickle.dump(im_features, handle, protocol=pickle.HIGHEST_PROTOCOL) -------------------------------------------------------------------------------- /HoVW/classification/split-train-test.py: -------------------------------------------------------------------------------- 1 | import os, argparse, random 2 | 3 | parser = argparse.ArgumentParser() 4 | parser.add_argument('-i', help='path with images') 5 | parser.add_argument('-o', help='path with images') 6 | args = parser.parse_args() 7 | 8 | i_path = args.i 9 | o_path = args.o 10 | 11 | images = os.listdir(i_path) 12 | 13 | test_size = int(len(images) * 0.3) 14 | test_index = random.sample(range(len(images)), k=test_size) 15 | 16 | testgroup = [] 17 | removed = 0 18 | for i in test_index: 19 | testgroup.append(images.pop(i-removed)) 20 | removed += 1 21 | 22 | # val_size = int(len(images) * 0.2) + 1 23 | # val_index = random.sample(range(len(images)), k=val_size) 24 | 25 | # valgroup = [] 26 | # removed = 0 27 | # for i in test_index: 28 | # valgroup.append(images.pop(i-removed)) 29 | # removed += 1 30 | 31 | traingroup = images 32 | 33 | try: 34 | train_folder = o_path + "/train" 35 | print("Creating " + train_folder) 36 | if not os.path.exists(train_folder): 37 | os.makedirs(train_folder) 38 | test_folder = o_path + "/test" 39 | print("Creating " + test_folder) 40 | if not os.path.exists(test_folder): 41 | os.makedirs(test_folder) 42 | # test_folder = o_path + "/validation" 43 | # print("Creating " + test_folder) 44 | # if not os.path.exists(test_folder): 45 | # os.makedirs(test_folder) 46 | except Exception as e: 47 | print("Error:", e) 48 | 49 | print("Creating Train Set") 50 | for i in traingroup: 51 | try: 52 | print("Moving ", i) 53 | os.rename(i_path + "/" + i, train_folder + "/" + i) 54 | except Exception as e: 55 | print("Error:", e) 56 | 57 | print("Creating Test Set") 58 | for i in testgroup: 59 | try: 60 | print("Moving ", i) 61 | os.rename(i_path + "/" + i, test_folder + "/" + i) 62 | except Exception as e: 63 | print("Error:", e) 64 | 65 | # print("Creating Validation Set") 66 | # for i in valgroup: 67 | # try: 68 | # print("Moving ", i) 69 | # os.rename(i_path + "/" + i, test_folder + "/" + i) 70 | # except Exception as e: 71 | # print("Error:", e) 72 | 73 | 74 | print("Train size ", len(traingroup)) 75 | print("Test size ", len(testgroup)) 76 | # print("Validation size ", len(valgroup)) 77 | -------------------------------------------------------------------------------- /HoVW/executions.py: -------------------------------------------------------------------------------- 1 | import os 2 | import numpy as np 3 | 4 | k_list = np.arange(100, 1300, 100) 5 | k_list = [100] 6 | for k in k_list: 7 | with open('exec/results-batch.txt', 'a') as f: 8 | f.write("-- K = {}\n".format(k)) 9 | with open('exec/results-batch2.txt', 'a') as f: 10 | f.write("-- K = {}\n".format(k)) 11 | 12 | q1 = """python src/kmeans-nodes.py -i "Master/datasetOutput/descriptor/" -o "Master/datasetOutput" -c {} -l "Master/datasetOutput/logs" """.format(k) 13 | print(q1);os.system(q1) 14 | 15 | q2 = """python src/kmeans-nodes-test.py -i "Master/datasetOutput/test/descriptor/" -o "Master/datasetOutput/test" -c "Master/data/kme-clusters2.clr" -l "Master/datasetOutput/logs" """ 16 | print(q2);os.system(q2) 17 | 18 | q3 = """python src/assign-node-label.py -i "Master/data/img_trees-train.pickle" -c "Master/datasetOutput/BOW/assignment-kme" -d "Master/data" -t "train" """ 19 | print(q3);os.system(q3) 20 | 21 | q4 = """python src/assign-node-label.py -i "Master/data/img_trees-test.pickle" -c "Master/datasetOutput/test/BOW/assignment-kme" -d "Master/data" -t "test" """ 22 | print(q4);os.system(q4) 23 | 24 | q5 = """python src/trees-distance.py -i "Master/data/img_trees_labeled-train.pickle" -c "Master/data/kme-clusters-cdm.npy" -m "Master/data/tree_distances_matrix-train.npy" -d "Master/data/apted_custom_dist.pickle" -p 4 """ 25 | print(q5);os.system(q5) 26 | 27 | #bw_list = [None, 0.3, 0.1, 0.01] 28 | bw_list = [0.01, 0.1, 0.3, 0.5, None,0.7] 29 | bw_list = [0.7] 30 | for bw in bw_list: 31 | with open('exec/results-batch.txt', 'a') as f: 32 | f.write("-- Bandwidth = {}\n".format(bw)) 33 | with open('exec/results-batch2.txt', 'a') as f: 34 | f.write("-- Bandwidth = {}\n".format(bw)) 35 | 36 | #ATENCAO: ADICIONEI NO CODIGO PARA ESCREVER O BANDWIDTH no arquivo de batch 37 | q6 = """python src/meanshift-graphs.py "Master/data/tree_distances_matrix-train.npy" "Master/data/trees_clustered" {} "Master/data/img_trees_labeled-train.pickle" """.format(bw) 38 | print(q6);os.system(q6) 39 | 40 | q7 = """python src/assign-tree-label.py "Master/data/img_trees_labeled-train.pickle" "Master/data/trees_clustered_vq-train.npy" """ 41 | print(q7);os.system(q7) 42 | 43 | q8 = """python src/meanshift-graphs-test.py "Master/data/img_trees_labeled-test.pickle" "Master/data/trees_clustered_codebook.npz" "Master/data/kme-clusters-cdm.npy" "Master/data/trees_clustered_centers.npy" """ 44 | print(q8);os.system(q8) 45 | 46 | q9 = """python src/centers_dendrogram.py -d "Master/data/tree_distances_matrix-train.npy" -c "Master/data/trees_clustered_centers.npy" -o "Master/data/" """ 47 | print(q9);os.system(q9) 48 | 49 | q10 = """python views/reveal_clusters-graphs.py""" 50 | print(q10);os.system(q10) 51 | 52 | # # p_list = [20, 15, 10, 5, 1] 53 | # p_list = [20] 54 | # for p in p_list: 55 | # q11 = """python src/precison_recall_test2.py {}""".format(p) 56 | # print(q11);os.system(q11) 57 | 58 | -------------------------------------------------------------------------------- /HoVW/pipeline.bat: -------------------------------------------------------------------------------- 1 | :: sh build_master_dir.sh 2 | 3 | SET K=250 4 | SET BANDWIDTH=0.3 5 | SET PROCESS=2 6 | 7 | :: python classification/split-train-test.py -i "Master/images" -o "Master/dataset" 8 | 9 | python src/index.py -i "Master/dataset/train/" -o "Master/datasetOutput" -l "Master/datasetOutput/logs" -d "Master/data" -t "train" 10 | :: python src/index.py -i "Master/dataset/test/" -o "Master/datasetOutput/test" -l "Master/datasetOutput/logs" -d "Master/data" -t "test" 11 | 12 | python src/kmeans-nodes.py -i "Master/datasetOutput/descriptor/" -o "Master/datasetOutput" -c %K% -l "Master/datasetOutput/logs" 13 | :: python classification/kmeans-nodes-test.py -i "Master/datasetOutput/test/descriptor/" -o "Master/datasetOutput/test" -c "Master/data/kme-clusters.clr" -l "Master/datasetOutput/logs" 14 | 15 | :: python src/others/meanshift-nodes.py -i "Master/datasetOutput/descriptor/" -o "Master/datasetOutput" -b 0.3 -l "Master/datasetOutput/logs" 16 | :: python classification/meanshift-test.py -i "Master/datasetOutput/test/descriptor/" -o "Master/datasetOutput/test" -c "msh-clusters.clr" -l "Master/datasetOutput/logs" 17 | 18 | python src/assign-node-label.py -i "Master/data/img_trees-train.pickle" -c "Master/datasetOutput/BOW/assignment-kme" -d "Master/data" -t "train" 19 | :: python src/assign-node-label.py -i "Master/data/img_trees-test.pickle" -c "Master/datasetOutput/test/BOW/assignment-kme" -d "Master/data" -t "test" 20 | 21 | python src/trees-distance.py -i "Master/data/img_trees_labeled-train.pickle" -c "Master/data/kme-clusters-cdm.npy" -m "Master/data/tree_distances_matrix-train.npy" -d "Master/data/apted_custom_dist.pickle" -p %PROCESS% 22 | 23 | python src/meanshift-graphs.py "Master/data/tree_distances_matrix-train.npy" "Master/data/trees_clustered" %BANDWIDTH% "Master/data/img_trees_labeled-train.pickle" 24 | 25 | python src/assign-tree-label.py "Master/data/img_trees_labeled-train.pickle" "Master/data/trees_clustered_vq-train.npy" 26 | :: python src/others/meanshift-graphs-test.py "Master/data/img_trees_labeled-test.pickle" "Master/data/trees_clustered_codebook.npz" "Master/data/kme-clusters-cdm.npy" "Master/data/trees_clustered_centers.npy" 27 | 28 | python src/centers_dendrogram.py -d "Master/data/tree_distances_matrix-train.npy" -c "Master/data/trees_clustered_centers.npy" -o "Master/data/" 29 | 30 | ::EXTRAS -- visualization only, ignore on the main pipeline 31 | 32 | :: python databases/populate.py -f "Master/data/img_trees_labeled_full-train.pickle" 33 | :: python classification/classify-nodes.py -i "Master/data/classf_data-train.pickle" -o "Master/data/classf_data-test.pickle" 34 | python views/reveal_clusters-graphs.py 35 | python views/reveal_clusters-nodes.py 36 | :: python views/visualize_graph_spatial_distribution.py 37 | 38 | ::FIT 39 | :: python src/fit.py -i "Master/images/olho.png" -o "Master/images/tmp/clusters.potato" -l "Master/datasetOutput/logs" -a "Master/data/kme-clusters.clr" -t "Master/data/trees_clustered_codebook.npz" -d "Master/data/apted_custom_dist.pickle" -z "Master/data/dendogram.npy" -------------------------------------------------------------------------------- /HoVW/pipeline.sh: -------------------------------------------------------------------------------- 1 | # python classification/split-train-test.py -i "Master/images" -o "Master/dataset" 2 | 3 | python src/index.py -i "Master/dataset/train/" -o "Master/datasetOutput" -l "Master/datasetOutput/logs" -d "Master/data" -t "train" 4 | # python src/index.py -i "Master/dataset/test/" -o "Master/datasetOutput/test" -l "Master/datasetOutput/logs" -d "Master/data" -t "test" 5 | 6 | python src/kmeans-nodes.py -i "Master/datasetOutput/descriptor/" -o "Master/datasetOutput" -c 300 -l "Master/datasetOutput/logs" 7 | # python src/kmeans-nodes-test.py -i "Master/datasetOutput/test/descriptor/" -o "Master/datasetOutput/test" -c "Master/data/kme-clusters2.clr" -l "Master/datasetOutput/logs" 8 | 9 | # python src/others/meanshift-nodes.py -i "Master/datasetOutput/descriptor/" -o "Master/datasetOutput" -b 0.3 -l "Master/datasetOutput/logs" 10 | # python classification/meanshift-test.py -i "Master/datasetOutput/test/descriptor/" -o "Master/datasetOutput/test" -c "msh-clusters.clr" -l "Master/datasetOutput/logs" 11 | 12 | python src/assign-node-label.py -i "Master/data/img_trees-train.pickle" -c "Master/datasetOutput/BOW/assignment-kme" -d "Master/data" -t "train" 13 | # python src/assign-node-label.py -i "Master/data/img_trees-test.pickle" -c "Master/datasetOutput/test/BOW/assignment-kme" -d "Master/data" -t "test" 14 | 15 | python src/trees-distance.py -i "Master/data/img_trees_labeled-train.pickle" -c "Master/data/kme-clusters-cdm.npy" -m "Master/data/tree_distances_matrix-train.npy" -d "Master/data/apted_custom_dist.pickle" -p 4 16 | 17 | python src/meanshift-graphs.py "Master/data/tree_distances_matrix-train.npy" "Master/data/trees_clustered" 0.3 "Master/data/img_trees_labeled-train.pickle" 18 | 19 | python src/assign-tree-label.py "Master/data/img_trees_labeled-train.pickle" "Master/data/trees_clustered_vq-train.npy" 20 | python src/meanshift-graphs-test.py "Master/data/img_trees_labeled-test.pickle" "Master/data/trees_clustered_codebook.npz" "Master/data/kme-clusters-cdm.npy" "Master/data/trees_clustered_centers.npy" 21 | 22 | python src/centers_dendrogram.py -d "Master/data/tree_distances_matrix-train.npy" -c "Master/data/trees_clustered_centers.npy" -o "Master/data/" 23 | 24 | # python databases/populate.py -f "Master/data/img_trees_labeled_full-train.pickle" 25 | 26 | #EXTRAS -- apenas visualização, não levar em consideração no pipeline 27 | # python classification/classify-nodes.py -i "Master/data/classf_data-train.pickle" -o "Master/data/classf_data-test.pickle" 28 | python views/reveal_clusters-graphs.py 29 | python views/reveal_clusters-nodes.py 30 | # python views/visualize_graph_spatial_distribution.py 31 | 32 | #FIT 33 | python src/fit.py -i "Master/images/olho.png" -o "Master/images/tmp/clusters.potato" -l "Master/datasetOutput/logs" -a "Master/data/kme-clusters.clr" -t "Master/data/trees_clustered_codebook.npz" -d "Master/data/apted_custom_dist.pickle" -z "Master/data/dendogram.npy" 34 | 35 | python src/precison_recall_test.py 20 -------------------------------------------------------------------------------- /HoVW/requirements.txt: -------------------------------------------------------------------------------- 1 | opencv-python>=3.4.2.16 2 | mahotas 3 | numpy 4 | -------------------------------------------------------------------------------- /HoVW/src/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python -------------------------------------------------------------------------------- /HoVW/src/assign-node-label.py: -------------------------------------------------------------------------------- 1 | import pickle, argparse, collections, re 2 | from os import listdir, path 3 | import matplotlib.pyplot as plt 4 | 5 | def init_args(): 6 | """Input Parameters""" 7 | parser = argparse.ArgumentParser() 8 | parser.add_argument('-i', help='images idx file') 9 | parser.add_argument('-c', help='codewords dir') 10 | parser.add_argument('-d', help='data file path') 11 | parser.add_argument('-t', help='train or test') 12 | 13 | return parser.parse_args() 14 | 15 | def distribuition_plot(agg_dict, dfile_path): 16 | plt.bar(range(len(agg_dict)), agg_dict.keys(), align="center") 17 | xitcks = [] 18 | for i in agg_dict.values(): 19 | xitcks.append(len(i)) 20 | plt.xticks(range(len(agg_dict)), xitcks, rotation='vertical') 21 | 22 | plt.xlabel("Count of clusters") 23 | plt.ylabel("Elements in cluster") 24 | 25 | plt.rcParams["figure.figsize"] = [600,600] 26 | for a,b in zip(range(len(agg_dict)), agg_dict.keys()): 27 | plt.text(a-0.5, b, b) 28 | plt.savefig(path.join(dfile_path, 'nodes-distribuition-plot.png')) 29 | # plt.show() 30 | 31 | def main(): 32 | args = init_args() 33 | i_file = args.i 34 | cw_dir = args.c 35 | t_type = args.t 36 | dfile_path = args.d 37 | hist_l = {} 38 | images = [] 39 | 40 | # TODO: Dá para otimizar o uso da memória. Basta, ao invés, de armazenar 41 | # tudo em images [] ler do arquivo e processar ou upar para memória em batch 42 | with open(i_file, 'rb') as f: 43 | while True: 44 | try: 45 | images.append(pickle.load(f)) 46 | except EOFError: 47 | break 48 | 49 | for im in images: 50 | cw = re.sub('.*\/', '', im.tree.name) 51 | cw = re.sub('\..*', '', cw) + '.codeword' 52 | print("Working on", cw, "and", im.tree.name) 53 | labels = [] 54 | with open(path.join(cw_dir,cw), 'r') as f: 55 | for line in f: 56 | label = int(line.split(" ")[0]) 57 | if(label not in hist_l): hist_l[label] = 1 58 | else: hist_l[label] += 1 59 | labels.append(label) 60 | 61 | # TODO: juntar as duas funções abaixo; elas deveriam ser feitas juntas 62 | im.tree.set_labels(labels) 63 | im.tree.set_nodes_depth() 64 | 65 | with open(path.join(dfile_path, 'img_trees_labeled-' + t_type + '.pickle'), 'wb') as handle: 66 | for img in images: 67 | pickle.dump(img, handle, protocol=pickle.HIGHEST_PROTOCOL) 68 | 69 | agg_dict = {} 70 | for i in hist_l.keys(): 71 | if(hist_l[i] in agg_dict): agg_dict[hist_l[i]].append(i) 72 | else: agg_dict[hist_l[i]] = [i] 73 | 74 | agg_dict = collections.OrderedDict(sorted(agg_dict.items(), key=lambda t: t[0])) 75 | 76 | mask_count = 0 77 | with open(path.join(dfile_path, 'codeword-count-{}.dict'.format(t_type)), 'w') as f: 78 | for de in agg_dict: 79 | mask_count += de*len(agg_dict[de]) 80 | f_string = str(de) + ': ' 81 | f_string += ' '.join(str(dv) for dv in agg_dict[de]) + '\n' 82 | f.write(f_string) 83 | print(mask_count) 84 | 85 | distribuition_plot(agg_dict, dfile_path) 86 | 87 | main() -------------------------------------------------------------------------------- /HoVW/src/assign-tree-label.py: -------------------------------------------------------------------------------- 1 | import sys, os, pickle 2 | import numpy as np 3 | import image as Image 4 | 5 | trees_file = sys.argv[1] 6 | vq_file = sys.argv[2] 7 | 8 | vq_list = np.load(vq_file) 9 | 10 | img_trees = [] 11 | test = [] 12 | with open(trees_file, 'rb') as f: 13 | while True: 14 | try: 15 | img_trees.append(pickle.load(f)) 16 | except EOFError: 17 | break 18 | 19 | for img, vq in zip(img_trees, vq_list): 20 | print(img.tree.name, int(vq)) 21 | test.append((img.tree.name, int(vq))) 22 | img.tree.label = int(vq) 23 | ''' 24 | print("----") 25 | for a in test: 26 | if (a[1] == 85): 27 | print(a[0]) 28 | ''' 29 | with open('Master/data/img_trees_labeled_full-train.pickle', 'wb') as handle: 30 | for img_tree in img_trees: 31 | pickle.dump(img_tree, handle, protocol=pickle.HIGHEST_PROTOCOL) 32 | -------------------------------------------------------------------------------- /HoVW/src/centers_dendrogram.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import numpy as np 3 | import matplotlib.pyplot as plt 4 | from scipy.cluster import hierarchy 5 | 6 | def init_args(): 7 | """Input Parameters""" 8 | parser = argparse.ArgumentParser() 9 | parser.add_argument('-d', help="trees' distances matrix") 10 | parser.add_argument('-c', help="trees' clustered centers") 11 | parser.add_argument('-o', help="dendogram output path") 12 | 13 | return parser.parse_args() 14 | 15 | def main(): 16 | 17 | args = init_args() 18 | 19 | A = np.load(args.d) 20 | C = np.load(args.c) 21 | output_path = args.o 22 | 23 | centers_distance_matrix = np.zeros((len(C), len(C)), dtype=np.float_) 24 | 25 | for c1, i in zip(C, range(len(C))): 26 | for c2, j in zip(C, range(len(C))): 27 | centers_distance_matrix[i][j] = A[c1][c2] 28 | 29 | print(centers_distance_matrix) 30 | 31 | Z = hierarchy.linkage(centers_distance_matrix) 32 | 33 | np.save(output_path + "dendogram.npy", Z) 34 | 35 | fig = plt.figure() 36 | 37 | plt.title('Hierarchical Clustering Dendrogram (truncated)') 38 | plt.xlabel('sample index or (cluster size)') 39 | plt.ylabel('distance') 40 | 41 | hierarchy.dendrogram(Z) 42 | 43 | plt.savefig(output_path + "dendogram_view.png") 44 | # plt.show() 45 | 46 | main() -------------------------------------------------------------------------------- /HoVW/src/clusters.py: -------------------------------------------------------------------------------- 1 | import os, argparse, time, re, pickle, gc 2 | import numpy as np 3 | from sklearn.cluster import KMeans, MiniBatchKMeans, MeanShift 4 | from scipy.spatial import distance_matrix 5 | from scipy.spatial.distance import cdist 6 | from klepto.archives import file_archive 7 | from utils import Log 8 | 9 | 10 | class Cluster(MiniBatchKMeans, MeanShift): 11 | """A general class which includes others SKLearn.Cluster 12 | http://scikit-learn.org/stable/modules/classes.html#module-sklearn.cluster 13 | 14 | Now, we implment both KMeans and MeanShift. 15 | 16 | Parameters 17 | ---------- 18 | cnt: Shape's contour. 19 | outline: Shape's outline. 20 | 21 | Attributes 22 | ---------- 23 | All attributes available on parental classes. 24 | centroids_distance: array, shape = [codebook size, codebook size] 25 | Dissimilarity matrix (distances) between clusters centroids. 26 | """ 27 | 28 | def __init__(self, **kwargs): 29 | self.centroids_distance = None 30 | if 'load' in kwargs: 31 | self._load(kwargs['load']) 32 | else: 33 | try: 34 | method = kwargs['method'] 35 | del kwargs['method'] 36 | except KeyError as ke: 37 | print(kr) 38 | raise 39 | 40 | if method == 'KMeans' or method == 'MiniBatchKMeans': 41 | MiniBatchKMeans.__init__(self,**kwargs) 42 | elif method == 'MeanShift': 43 | MeanShift.__init__(self,**kwargs) 44 | else: 45 | e = "No method '{}' avaiable. Please use KMeans or MeanShift".format(method) 46 | log = Log(path='.', name='cluster_class') 47 | log.write(error=e, data=self) 48 | raise ValueError(e) 49 | 50 | def load(self, path): 51 | """Load the model object from a serialized file. 52 | 53 | Parameters 54 | ---------- 55 | path: string 56 | Path where the file is in. 57 | """ 58 | 59 | with open(path, 'rb') as f: 60 | self.__dict__.update(pickle.load(f)) 61 | 62 | def save(self, path, name=None): 63 | """Save the model object in a serialized file. 64 | 65 | Parameters 66 | ---------- 67 | path: string 68 | Path where the file should be save. 69 | name: string, default = None 70 | Name of the file. 71 | """ 72 | #TODO: centroids_distance nao deve ser aqui 73 | 74 | self.centroids_distance = self._centroids_distance_matrix() 75 | 76 | print("Saving", name, "in", path) 77 | arch = file_archive('{}.clr'.format(os.path.join(path, name))) 78 | for d in self.__dict__: 79 | arch[d] = self.__dict__[d] 80 | arch.dump() 81 | 82 | with open(os.path.join(path, name) + '2.clr', 'wb') as f: 83 | pickle.dump(self, f, protocol=pickle.HIGHEST_PROTOCOL) 84 | 85 | print("Exporting", name + "-cdm", "in", path) 86 | np.save(os.path.join(path, name + "-cdm") + '.npy', self.centroids_distance) 87 | 88 | def _centroids_distance_matrix(self): 89 | """Generate the dissimilarity matrix of the clusters centroids. 90 | In a Bag-of-Words apporach the codebook is iqual the 91 | number of clusters in the model. 92 | 93 | Returns 94 | ------- 95 | Array, shape = [codebook size, codebook size] 96 | Dissimilarity matrix (distances) between clusters centroids. 97 | """ 98 | 99 | return distance_matrix(self.cluster_centers_, self.cluster_centers_) 100 | 101 | _load = load -------------------------------------------------------------------------------- /HoVW/src/descriptors.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import mahotas 3 | import numpy as np 4 | 5 | class ZernikeMoments: 6 | """The Zernike Moments descriptor invariant to scale, rotation and 7 | translation (interface for Mahotas Zernike moment's application). 8 | 9 | Parameters 10 | ---------- 11 | degree: int, default = 8 12 | The degree of the polynomial moment (default corresponds 21 13 | polynoms). 14 | """ 15 | 16 | def __init__(self, degree=8): 17 | self.degree = degree 18 | 19 | def describe(self, shape, radius): 20 | """Describe the Zernike Moments of self.degree order. 21 | 22 | Parameters 23 | ---------- 24 | shape: Contour of shape to be described. 25 | radius: Radius of circumference which circumscribes the 26 | shape. 27 | 28 | Returns 29 | ------- 30 | List of float 31 | The fist moments of order self.degree. 32 | """ 33 | 34 | return mahotas.features.zernike_moments(shape, radius, self.degree) 35 | 36 | class GeometricDescriptors: 37 | """Geometric descriptors. Implements multiple geometric descriptors 38 | statically. 39 | """ 40 | @staticmethod 41 | def compactness(area, perimeter): 42 | """Calculate the Compactness of a shape. 43 | 44 | compactness = (4 * PI * Area) / (Perimeter ** 2) 45 | 46 | Parameters 47 | ---------- 48 | area: area of the shape. 49 | perimeter: perimeter of the shape. 50 | 51 | Returns 52 | ------- 53 | Float 54 | Compactness of the shape. 55 | """ 56 | 57 | return (4*np.pi*area)/(perimeter**2) 58 | 59 | @staticmethod 60 | def convexity(contour, perimeter): 61 | """Calculate the Convexity of a shape. 62 | 63 | convexity = Perimeter of Hull / Perimeter 64 | 65 | Parameters 66 | ---------- 67 | contour: contour of the shape. 68 | perimeter: perimeter of the shape. 69 | 70 | Returns 71 | ------- 72 | Float 73 | Convexity of the shape. 74 | """ 75 | 76 | phull = cv2.arcLength(cv2.convexHull(contour),True) #perimeter of hull 77 | 78 | return phull/perimeter 79 | 80 | @staticmethod 81 | def eccentricity(contour, centroid): 82 | """Calculate the Eccentricity of a shape. 83 | 84 | Parameters 85 | ---------- 86 | contour: contour of the shape. 87 | centroid: perimeter of the shape. 88 | 89 | Returns 90 | ------- 91 | Float 92 | Eccentricity of the shape. 93 | """ 94 | 95 | def _covariance_matrix(contour, centroid): 96 | """Calculate the Covariance Matrix of a shape. 97 | covariance marix = 1/N * 98 | sum(i=0;N-1) ([xi - cx][yi - cy]) * 99 | ([xi - cx][yi - cy])^T = 100 | ([cxx, cxy][cyx, cyy]) 101 | 102 | cxy = cyx (happens beacuse of the derivation) 103 | 104 | Parameters 105 | ---------- 106 | contour: contour of the shape. 107 | centroid: perimeter of the shape. 108 | 109 | Returns 110 | ------- 111 | List of floats representing the covariance matrix of 112 | the shape. 113 | """ 114 | 115 | cxx = cxy = cyy = 0.0 116 | for point in contour: 117 | point = point[0] 118 | l1 = point[0] - centroid[0] 119 | l2 = point[1] - centroid[1] 120 | cxx += l1*l1 121 | cxy += l1*l2 122 | cyy += l2*l2 123 | 124 | return [cxx, cxy, cyy] 125 | 126 | covM = _covariance_matrix(contour, centroid) 127 | bSqrt = np.sqrt((covM[0] + covM[2])*(covM[0] + covM[2]) 128 | - 4 * (covM[0] * covM[2] - covM[1]*covM[1])) 129 | 130 | lambda1 = 1/2 * (covM[0] + covM[2] + bSqrt) 131 | lambda2 = 1/2 * (covM[0] + covM[2] - bSqrt) 132 | 133 | return lambda2/lambda1 134 | 135 | @staticmethod 136 | def ellipse_variance(): 137 | raise NotImplementedError('ellipse_variance not implemented') 138 | 139 | @staticmethod 140 | def circle_variance(): 141 | raise NotImplementedError('circle_variance not implemented') 142 | 143 | @staticmethod 144 | def rectangularity(area, contour): 145 | """Calculate the Rectangularity of a shape. 146 | 147 | rectangularity = area / minimum rectangle 148 | 149 | Parameters 150 | ---------- 151 | area: area of the shape. 152 | contour: contour of the shape. 153 | 154 | Returns 155 | ------- 156 | Float 157 | Rectangularity of the shape. 158 | """ 159 | 160 | rectangle = cv2.minAreaRect(contour) 161 | 162 | return area/rectangle 163 | 164 | @staticmethod 165 | def avg_bending_energy(contour, step=1): 166 | """Calculate the Average Bending Energy of a shape. 167 | ref: https://stackoverflow.com/posts/34678359/revisions 168 | 169 | Parameters 170 | ---------- 171 | contour: contour of the shape. 172 | step: ? (default: 1). 173 | 174 | Returns 175 | ------- 176 | Float 177 | Average bending energy of the shape. 178 | """ 179 | curvature = [] 180 | if(len(contour) < step): 181 | return -1 182 | 183 | isClosed = max(np.absolute(contour[0][0]-contour[len(contour)-1][0])) <= 1 184 | for i in range(len(contour)): 185 | pos = contour[i][0] 186 | maxStep = step 187 | if(not isClosed): 188 | maxStep = min(min(step,i), len(contour)-1-i) 189 | if(maxStep == 0): 190 | curvature2D = np.inf 191 | curvature2D = 0 192 | curvature.append(curvature2D) 193 | continue 194 | 195 | iminus = i - maxStep 196 | iplus = i + maxStep 197 | pminus = contour[iminus + len(contour) if iminus < 0 else iminus][0] 198 | pplus = contour[iplus - len(contour) if iplus >= len(contour) else iplus][0] 199 | 200 | f1stDerivative = (pplus - pminus)/(iplus-iminus) 201 | f2ndDerivative = (pplus - 2*pos + pminus) / ((iplus-iminus)/2*(iplus-iminus)/2) 202 | 203 | divisor = f1stDerivative*f1stDerivative 204 | divisor = divisor[0] + divisor[1] 205 | if(np.absolute(divisor) > 10e-8): 206 | curvature2D = np.absolute(f1stDerivative[0]*f2ndDerivative[1] - f1stDerivative[1]*f2ndDerivative[0]) 207 | curvature2D = curvature2D/pow(divisor, 3/2) 208 | else: 209 | curvature2D = np.inf 210 | curvature2D = 0 211 | 212 | curvature.append(curvature2D) 213 | 214 | return np.sum(curvature)/len(curvature) 215 | -------------------------------------------------------------------------------- /HoVW/src/fit.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import pickle, argparse 4 | import numpy as np 5 | from apted import APTED, Config 6 | from utils import Log 7 | from image import Image 8 | from clusters import Cluster 9 | 10 | 11 | # TODO: Mesma classe que em trees-distance; precisa colocar em um .py separado 12 | class ImageTreeDistance(Config): 13 | def __init__(self, centroids_matrix): 14 | self.centroids_matrix = centroids_matrix 15 | self.centroids_mean = centroids_matrix.mean() 16 | 17 | def delete(self, node): 18 | """Calculates the cost of deleting a node""" 19 | a = np.max([np.log2(node.neighbors), np.log2(node.depth)]) 20 | a = 1/a if a > 0 else 0 21 | return self.centroids_mean * a 22 | 23 | def insert(self, node): 24 | """Calculates the cost of inserting a node""" 25 | return self.delete(node) 26 | 27 | def rename(self, node1, node2): 28 | """Compares attribute .value of trees""" 29 | # ATTENTION: if the node is a root node and if try to relabeled 30 | # it the cost is zero 31 | if node1.label == None or node2.label == None: 32 | return 0 33 | 34 | return self.centroids_matrix[node1.label][node2.label] 35 | 36 | def children(self, node): 37 | return node.childs 38 | 39 | def init_args(): 40 | parser = argparse.ArgumentParser() 41 | parser.add_argument('-i', help='image') 42 | parser.add_argument('-o', help='output path') 43 | parser.add_argument('-l', help='logs directory') 44 | parser.add_argument('-a', help="artifacts' codebook") 45 | parser.add_argument('-t', help="trees' codebook") 46 | parser.add_argument('-d', help='apted custom distance') 47 | parser.add_argument('-z', help="center's dendogram") 48 | 49 | return parser.parse_args() 50 | 51 | def calc_dist_trees(t1, t2, apted_dist): 52 | #print(t1.tree.name, t2.tree.name) 53 | return APTED(t1.tree.root, t2.tree.root, apted_dist).compute_edit_distance() 54 | 55 | def compute_label(X): 56 | return np.argwhere(X == np.min(X))[0][0] 57 | 58 | def compute_hierarchy(X): 59 | return np.argwhere(X == np.min(X))[0][0] 60 | 61 | def gabi_do_the_math(dendogram, cluster): 62 | """Computes cluster's neighborhood based on clusters centers' dendogram. 63 | Author: Gabriela Gomes""" 64 | 65 | def find_index(dendogram, n): 66 | i = 0 67 | dendogram_size = dendogram.shape[0] 68 | while i < dendogram_size and dendogram[i][0] != n and dendogram[i][1] != n: i += 1 69 | if i == dendogram_size: 70 | return -1 #no raiz 71 | return i 72 | 73 | def build_top(dendogram): 74 | top_info = {} 75 | alt = {} 76 | dendogram_size = dendogram.shape[0] 77 | for d in range(dendogram_size): 78 | top = find_index(dendogram, dendogram_size + d + 1) 79 | t = dendogram[top] 80 | 81 | if top in top_info: 82 | top_info[top].append(d) 83 | else: 84 | top_info[top] = [d] 85 | 86 | alt[d] = -1 if top == -1 else top 87 | 88 | return top_info, alt 89 | 90 | def busca1(dendogram, top_info, alt, index, brotherhood): 91 | dendogram_size = dendogram.shape[0] 92 | if index == -1: 93 | return brotherhood 94 | 95 | i, j, dendogram[index][2] = dendogram[index][0], dendogram[index][1], 1 96 | if i < dendogram_size: brotherhood.append(int(i)) 97 | if j < dendogram_size: brotherhood.append(int(j)) 98 | if index in top_info.keys(): 99 | filhos = top_info[index] 100 | for f in filhos: 101 | if dendogram[f][2] == 0: 102 | brotherhood = busca1(dendogram, top_info, alt, f, brotherhood) 103 | if dendogram[alt[index]][2] == 0: 104 | brotherhood = busca1(dendogram, top_info, alt, alt[index], brotherhood) 105 | 106 | elif dendogram[alt[index]][2] == 0: 107 | brotherhood = busca1(dendogram, top_info, alt, alt[index], brotherhood) 108 | 109 | return brotherhood 110 | 111 | dendogram[:,2] = 0 112 | 113 | top_info, alt = build_top(dendogram) 114 | 115 | return busca1(dendogram, top_info, alt, find_index(dendogram, cluster), []) 116 | 117 | def main(): 118 | args = init_args() 119 | o_path = args.o 120 | log = Log(path=args.l, name='query_image') 121 | 122 | dendogram = np.load(args.z) 123 | query_img = Image(path=args.i) 124 | artifacts_clusters = Cluster(load=args.a) 125 | trees_codebook = np.load(args.t) 126 | with open(args.d, 'rb') as f: 127 | apted_dist = pickle.load(f) 128 | 129 | artifacts = query_img.tree.get_tree_masks()[1:] 130 | 131 | artifacts_labels = [] 132 | for artifact in artifacts: 133 | artifacts_labels.append(artifacts_clusters.predict(artifact.feature_vector.reshape(1, -1))[0]) 134 | 135 | # TODO: juntar as duas funções abaixo; elas deveriam ser feitas juntas 136 | query_img.tree.set_labels(artifacts_labels) 137 | query_img.tree.set_nodes_depth() 138 | 139 | M = np.zeros(len(trees_codebook['trees']), np.float_) 140 | for t1,i in zip(trees_codebook['trees'],range(len(trees_codebook['trees']))): 141 | M[i] = calc_dist_trees(t1, query_img, apted_dist) 142 | 143 | query_img.tree.label = compute_label(M) 144 | 145 | label_brotherhood = gabi_do_the_math(dendogram, query_img.tree.label) 146 | #print(label_brotherhood) 147 | with open('Master/images/olha_aqui.pickle', 'wb') as f: 148 | pickle.dump(query_img, f) 149 | 150 | with open(o_path, 'wb') as f: 151 | pickle.dump({"label":label_brotherhood}, f, protocol=pickle.HIGHEST_PROTOCOL) 152 | 153 | main() -------------------------------------------------------------------------------- /HoVW/src/image.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import operator 3 | import numpy as np 4 | from tree import ImageTree 5 | from descriptors import ZernikeMoments as ZM, GeometricDescriptors as GD 6 | 7 | class Mask: 8 | """The mask represents a shape of the image. 9 | 10 | Parameters 11 | ---------- 12 | cnt: Shape's contour. 13 | outline: Shape's outline. 14 | 15 | Attributes 16 | ---------- 17 | contour: array, shape = [list of points, point, point's coordinates] 18 | Shape's contour edges points. 19 | center_radius: tuple = (x, y, radius) 20 | Geometric center (point) of the shape and the radius between 21 | this point and the farthest edge point. 22 | centroid_radius: tuple = (x, y, radius) 23 | Center of mass (point) of the shape and the radius between 24 | this point and the farthest edge point. 25 | outline: array, shape = [height, width] 26 | Shape's outline. 27 | area: float 28 | Shape's area. 29 | perimeter: float 30 | Shape's perimeter. 31 | feature_vector: array, shape = [features] 32 | Features which describes the shape. 33 | """ 34 | 35 | def __init__(self, cnt, outline): 36 | self.contour = cnt 37 | self.outline = outline 38 | self.center_radius = self._center_radius() 39 | self.centroid_radius = self._centroid_radius() 40 | self.area = cv2.contourArea(self.contour) 41 | self.perimeter = cv2.arcLength(self.contour,True) 42 | self.feature_vector = self._build_feature_vector() 43 | 44 | def _center_radius(self): 45 | center,radius = cv2.minEnclosingCircle(self.contour) 46 | 47 | return (center[0], center[1],radius) 48 | 49 | def _centroid_radius(self): 50 | moment = cv2.moments(self.contour) 51 | cx = int(moment['m10']/moment['m00']) 52 | cy = int(moment['m01']/moment['m00']) 53 | 54 | ext = [] 55 | ext.append(tuple(self.contour[self.contour[:, :, 0].argmin()][0])) #left 56 | ext.append(tuple(self.contour[self.contour[:, :, 0].argmax()][0])) #Right 57 | ext.append(tuple(self.contour[self.contour[:, :, 1].argmin()][0])) #Top 58 | ext.append(tuple(self.contour[self.contour[:, :, 1].argmax()][0])) #Bottom 59 | r = -1 60 | for e in ext: 61 | x = np.sqrt((cx-e[0])**2 + (cy-e[1])**2) 62 | r = x if x>r else r 63 | 64 | return (cx, cy, r) 65 | 66 | def _build_feature_vector(self): 67 | """Build the feature vector. 68 | 69 | Format: 70 | convexity, compactness, eccentricity, avg_bending_energy, ZMs 71 | 72 | Returns 73 | ------- 74 | array, shape = [features] 75 | Array with the features. 76 | """ 77 | 78 | convexity = np.array([GD.convexity(self.contour, self.perimeter)]) 79 | compactness = np.array([GD.compactness(self.area, self.perimeter)]) 80 | eccentricity = np.array([GD.eccentricity(self.contour, 81 | (self.centroid_radius[0], self.centroid_radius[1]))]) 82 | avg_bending_energy = np.array( 83 | [GD.avg_bending_energy(self.contour, 1)]) 84 | 85 | geo_vec = np.append(convexity, [compactness, eccentricity, 86 | avg_bending_energy]) 87 | 88 | desc = ZM() 89 | zernike_moments = desc.describe(self.outline, self.center_radius[2]) 90 | 91 | return np.append(geo_vec, zernike_moments) 92 | 93 | def show(self, overload=False): 94 | """Show shape. 95 | 96 | Parameters 97 | ---------- 98 | overload: Show circles relating to center and center of mass. 99 | """ 100 | 101 | header = 'Mask' 102 | img = self.outline 103 | 104 | if overload: 105 | header = 'Mask Complete' 106 | img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB) 107 | cv2.circle(img, (int(self.centroid_radius[0]),int(self.centroid_radius[1])),\ 108 | int(self.centroid_radius[2]), (0,0,255)) 109 | cv2.circle(img, (int(self.centroid_radius[0]),int(self.centroid_radius[1])),\ 110 | 2, (0, 0, 255), -1) 111 | 112 | cv2.circle(img, (int(self.center_radius[0]),int(self.center_radius[1])),\ 113 | int(self.center_radius[2]), (0,255,0)) 114 | cv2.circle(img, (int(self.center_radius[0]),int(self.center_radius[1])),\ 115 | 2, (0,255,0), -1) 116 | 117 | cv2.imshow(header, img) 118 | cv2.waitKey(0) 119 | 120 | def draw(self, output=None, header=None, overload=False): 121 | """Draw the shape. 122 | 123 | Parameters 124 | ---------- 125 | overload: Show circles relating to center and center of mass. 126 | output: Path where the image should be drawn. 127 | header: Final image's name. 128 | """ 129 | 130 | final_header = 'mask' 131 | img = self.outline 132 | 133 | if overload: 134 | final_header = 'mask-complete' 135 | img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB) 136 | cv2.circle(img, (int(self.centroid_radius[0]),int(self.centroid_radius[1])), \ 137 | 2, (0, 0, 255), -1) 138 | cv2.circle(img, (int(self.centroid_radius[0]),int(self.centroid_radius[1])), \ 139 | int(self.centroid_radius[2]), (0, 0, 255)) 140 | 141 | cv2.circle(img, (int(self.center_radius[0]),int(self.center_radius[1])), \ 142 | 2, (0, 255, 0), -1) 143 | cv2.circle(img, (int(self.center_radius[0]),int(self.center_radius[1])), \ 144 | int(self.center_radius[2]), (0, 255, 0)) 145 | 146 | 147 | if header: final_header = header 148 | if output: final_header = output + final_header 149 | 150 | final_header += '.png' 151 | cv2.imwrite(final_header, img) 152 | 153 | class Image: 154 | """Image representation. 155 | 156 | Parameters 157 | ---------- 158 | path: Path where the image is located. 159 | 160 | Attributes 161 | ---------- 162 | path: string 163 | Original image's path. 164 | original: array, shape = [height, width, channels] 165 | Image itself. 166 | grayscale: array, shape = [height, width] 167 | Image grayscale version. 168 | threshold: array, shape = [height, width] 169 | Image binary threshold. 170 | tree: ImageTree 171 | Hierarchical (tree) representation of the image, 172 | segmented by its shapes. 173 | """ 174 | 175 | def __init__(self, path): 176 | self.path = path 177 | self.original = cv2.imread(path) 178 | self.grayscale = cv2.cvtColor(self.original, cv2.COLOR_BGR2GRAY) 179 | self.threshold = self._get_threshold() 180 | self.tree = self._set_tree() 181 | 182 | def _get_threshold(self): 183 | blur = cv2.medianBlur(self.grayscale, 5) 184 | blur = cv2.bilateralFilter(blur,9,75,75) 185 | _,threshold = cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) 186 | #THRESH_BINARY = fundo preto or THRESH_BINARY_INV = fundo branco 187 | 188 | return threshold 189 | 190 | def _get_hierarchy_masks(self): 191 | 192 | outline = np.zeros(self.grayscale.shape, dtype = "uint8") 193 | 194 | (_, cnts, hierarchy) = cv2.findContours(self.threshold.copy(), 195 | cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) 196 | masks = [] 197 | i = 0 198 | hierarchy = hierarchy[0] 199 | alter_hie = [] 200 | for cnt in cnts: 201 | if(cv2.contourArea(cnt) > 0): 202 | masks.append([cnt, cv2.drawContours(outline.copy(), 203 | [cnt], -1, 255, -1)]) #contour, outline 204 | alter_hie.append(np.append(hierarchy[i], 1)) 205 | else: 206 | alter_hie.append(np.append(hierarchy[i], 0)) 207 | i += 1 208 | hierarchy = np.array([alter_hie]) 209 | 210 | return (hierarchy[0], masks) 211 | 212 | def _set_tree(self): 213 | (hierarchy, shapes) = self._get_hierarchy_masks() 214 | masks = [] 215 | for mask in shapes: 216 | masks.append(Mask(mask[0],mask[1])) 217 | 218 | tree = ImageTree(hierarchy, masks, self.path) 219 | 220 | # 1 = acima da metade; #0 = toda a imagem 221 | tree.cut_off(0.2) 222 | 223 | return tree 224 | 225 | def draw(self, output=None): 226 | """Draw the image by its shapes. 227 | 228 | Parameters 229 | ---------- 230 | output: Path where the image should be drawn. 231 | """ 232 | masks = self.tree.get_tree_masks() 233 | for m,i in zip(masks, range(len(masks))): 234 | if m: m.draw(output, str(i), 'c') -------------------------------------------------------------------------------- /HoVW/src/index.py: -------------------------------------------------------------------------------- 1 | import pickle, argparse, re, sys 2 | from os import listdir, path 3 | from utils import Log 4 | from image import Image 5 | 6 | def img_structuring(img_path, descriptor_file): 7 | """Create the descriptor file of image's shapes""" 8 | try: 9 | img = Image(img_path) 10 | shapes = img.tree.get_tree_masks()[1:] 11 | with open(descriptor_file, 'w') as descriptor_file: 12 | print("Writing " + descriptor_file.name) 13 | descriptor_file.write(str(shapes[0].feature_vector.shape[0]) + '\n') 14 | descriptor_file.write(str(len(shapes)) + '\n') 15 | for shape in shapes: 16 | descriptor_file.write(' '.join(str(e) for e in shape.feature_vector.tolist()) + '\n') 17 | except: raise 18 | 19 | return img, len(shapes) 20 | 21 | def init_args(): 22 | """Input Parameters""" 23 | parser = argparse.ArgumentParser() 24 | parser.add_argument('-i', help='path with images') 25 | parser.add_argument('-o', help='output path') 26 | parser.add_argument('-l', help='logs directory') 27 | parser.add_argument('-d', help='data file path') 28 | parser.add_argument('-t', help='train or test') 29 | 30 | return parser.parse_args() 31 | 32 | def main(): 33 | args = init_args() 34 | 35 | i_path = args.i 36 | o_path = args.o 37 | d_path = path.join(o_path, 'descriptor') 38 | logs_path = args.l 39 | data_file = args.d 40 | t_type = args.t 41 | 42 | log = Log(path=logs_path, name='descriptor') 43 | 44 | with open(path.join(data_file, 'img_trees-' + t_type + '.pickle'), 'wb') as handle: 45 | print("Writing " + handle.name) 46 | total_shapes = 0 47 | i = 0 48 | for img_path in listdir(i_path): 49 | try: 50 | img_name = re.sub('\..*', '', img_path) 51 | img, count_shapes = img_structuring(path.join(i_path, img_path), path.join(d_path, img_name + '.descriptor')) 52 | total_shapes += count_shapes 53 | pickle.dump(img, handle, protocol=pickle.HIGHEST_PROTOCOL) 54 | i += 1 55 | except KeyboardInterrupt as err: 56 | log.write(error="Ctrl + c interruption", data=img_path) 57 | print("Ctrl + c interruption") 58 | break 59 | except Exception as e: 60 | log.write(error=e, data=img_path) 61 | print("ERROR: " + img_path) 62 | print(e) 63 | continue 64 | 65 | print("Images Count: {}; Images Considered {}; Shapes identified: {}".format(len(listdir(i_path)), i, total_shapes)) 66 | log.close() 67 | 68 | if __name__ == "__main__": 69 | main() -------------------------------------------------------------------------------- /HoVW/src/kmeans-nodes-test.py: -------------------------------------------------------------------------------- 1 | #from sklearn.cluster import KMeans 2 | from clusters import Cluster 3 | import numpy as np 4 | from os import listdir, path 5 | import argparse, time, re, pickle 6 | 7 | parser = argparse.ArgumentParser() 8 | parser.add_argument('-i', help='path with images') 9 | parser.add_argument('-o', help='output path') 10 | parser.add_argument('-c', help='clusters') 11 | parser.add_argument('-l', help='logs directory') 12 | 13 | args = parser.parse_args() 14 | 15 | i_path = args.i 16 | o_path = args.o 17 | logs_path = args.l 18 | k_clusters = -1 19 | c_path = args.c 20 | X = np.asarray([[None]*29], dtype=np.float_) #HARD-CODED TEM QUE LER ESSE 29 DO ARQUIVO 21 | y = [] 22 | 23 | for dfile in listdir(i_path): 24 | try: 25 | with open(i_path+dfile, 'r') as f: 26 | print("Reading from " + f.name) 27 | content = f.readlines() 28 | 29 | for i in range(int(content[1])): 30 | X = np.append(X, 31 | [np.array(list(np.float_(e) for e in content[2+i].split(' ')), dtype=np.float_)], 32 | axis=0) 33 | y.append(re.sub('\..*', '', dfile)) 34 | 35 | except KeyboardInterrupt as err: 36 | print("Ctrl + c interruption") 37 | break 38 | except Exception as e: 39 | print("ERROR: " + dfile) 40 | print(e) 41 | break 42 | continue 43 | 44 | X = np.delete(X, 0, 0) 45 | 46 | objects=[] 47 | with (open(c_path, "rb")) as openfile: 48 | while True: 49 | try: 50 | objects.append(pickle.load(openfile)) 51 | except EOFError: 52 | break 53 | 54 | ###Assignment --- Vector quantization 55 | 56 | #PRECISA SER TESTADO EM MAIS CASOS------- 57 | oufl = [] 58 | past = None 59 | count = 0 60 | for i in range(len(y)): 61 | if(y[i] != past): 62 | oufl.append((past, count)) 63 | count = 1 64 | past = y[i] 65 | else: count+=1 66 | past = y[i] 67 | oufl.append((past, count)) 68 | oufl = oufl[1:] 69 | #----- 70 | cluster = objects[0] 71 | k_clusters = cluster.n_clusters 72 | quantization = cluster.predict(X) 73 | 74 | j = 0 75 | im_names = {} 76 | im_features = np.zeros((len(oufl), k_clusters), np.float_) 77 | name_c = 0 78 | 79 | for e in oufl: 80 | bag = [0] * k_clusters 81 | with open(path.join(o_path, 'BOW/assignment-kme/' + e[0] + '.codeword'), 'w') as fa, \ 82 | open(path.join(o_path, 'BOW/bag-kme/' + e[0] + '.bagw'), 'w') as fb: 83 | #print("Writing " + fa.name + " and " + fb.name) 84 | for i in range(e[1]): 85 | vq = quantization[j] 86 | bag[int(vq)] += 1 87 | ### 88 | im_names[name_c] = e[0] 89 | im_features[name_c][int(vq)] += 1 90 | ### 91 | fa.write(str(vq) + ' ') 92 | fa.write(' '.join(str(k) for k in cluster.cluster_centers_[vq].tolist()) + '\n') 93 | j += 1 94 | ### 95 | name_c += 1 96 | ### 97 | bagf = [k/sum(bag) for k in bag] 98 | fb.write(' '.join(str(k) for k in bagf)) 99 | 100 | with open('Master/data/classf_data-test.pickle', 'wb') as handle: 101 | pickle.dump(im_names, handle, protocol=pickle.HIGHEST_PROTOCOL) 102 | pickle.dump(im_features, handle, protocol=pickle.HIGHEST_PROTOCOL) -------------------------------------------------------------------------------- /HoVW/src/kmeans-nodes.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import pickle, argparse, re, time 4 | from os import listdir, path 5 | import numpy as np 6 | from utils import Log 7 | from clusters import Cluster 8 | 9 | from sklearn import metrics 10 | from sklearn.metrics import pairwise_distances 11 | import matplotlib.pyplot as plt 12 | 13 | def init_args(): 14 | """Input Parameters""" 15 | parser = argparse.ArgumentParser() 16 | parser.add_argument('-i', help="path with image's descriptors") 17 | parser.add_argument('-o', help='output path') 18 | parser.add_argument('-c', help='codebook size') 19 | parser.add_argument('-l', help='logs directory') 20 | 21 | return parser.parse_args() 22 | 23 | def read_image_descriptors(i_path, log): 24 | """Retrive all features from all image's descriptor file and build 25 | the train set X""" 26 | X = np.asarray([[None]*29], dtype=np.float_) #HARD-CODED 29 Features 27 | y = [] 28 | for dfile in listdir(i_path): 29 | try: 30 | with open(path.join(i_path, dfile), 'r') as f: 31 | print("Reading from " + f.name) 32 | content = f.readlines() 33 | for i in range(int(content[1])): 34 | X = np.append(X, 35 | [np.array(list(np.float_(e) for e in content[2+i].split(' ')), dtype=np.float_)], 36 | axis=0) 37 | y.append(re.sub('\..*', '', dfile)) 38 | except KeyboardInterrupt as err: 39 | print("Ctrl + c interruption") 40 | break 41 | except Exception as e: 42 | log.write(error=e, data=dfile) 43 | print("ERROR: " + dfile) 44 | print(e) 45 | break 46 | continue 47 | 48 | print(X.shape) 49 | return X, y 50 | 51 | def main(): 52 | args = init_args() 53 | 54 | i_path = args.i 55 | o_path = args.o 56 | logs_path = args.l 57 | k_clusters = int(args.c) 58 | 59 | log = Log(logs_path, 'clustering-kme') 60 | 61 | X, y = read_image_descriptors(i_path, log) 62 | 63 | X = np.delete(X, 0, 0) 64 | 65 | # TODO: SEPARAR AVALIAÇÃO EM UM OUTRO ARQUIVO. ATUALMENTE SE QUISER 66 | # AVALIAÇÃO OU EXECUÇÃO NECESSITA APENAS COMENTAR/DESCOMENTAR A SEÇÃO 67 | 68 | #AVALIAÇÃO 69 | # #--- supervisionada 70 | # sls = [] 71 | # chs = [] 72 | 73 | #--- não supervisionada 74 | # inertia_list = [] 75 | 76 | # kc = [1000, 1500, 2000, 2500, 3000] 77 | # for k_clusters in kc: 78 | # print(k_clusters) 79 | # kmeans = Cluster(method='KMeans', init='k-means++', n_clusters=k_clusters, random_state=42, max_iter=300) 80 | # kmeans.fit(X) 81 | 82 | # #--- supervisionada 83 | # labels = kmeans.labels_ 84 | # sls.append(metrics.silhouette_score(X, labels, metric='mahalanobis')) 85 | # chs.append(metrics.calinski_harabaz_score(X, labels)) 86 | 87 | #--- não supervisionada 88 | # inertia_list.append(kmeans.inertia_) 89 | 90 | # fig = plt.figure() 91 | 92 | # #--- supervisionada 93 | # plt.subplot(1,1,1) 94 | # plt.title('silhouette_score') 95 | # plt.xlabel('codebook size') 96 | # plt.plot(kc, sls, 'r') 97 | 98 | # plt.subplot(2,1,2) 99 | # plt.title('calinski_harabaz_score') 100 | # plt.xlabel('codebook size') 101 | # plt.plot(kc, chs, 'b') 102 | 103 | # print(sls) 104 | # print(chs) 105 | 106 | #--- não supervisionada supervisionada 107 | # plt.subplot(1,1,1) 108 | # plt.title('inertia') 109 | # plt.xlabel('codebook size') 110 | # plt.plot(kc, inertia_list, 'r') 111 | 112 | # print(inertia_list) 113 | 114 | # plt.savefig('kmeans-scores.png') 115 | # plt.show() 116 | 117 | # EXECUÇÃO 118 | kmeans = Cluster(method='KMeans', init='k-means++', n_clusters=k_clusters, batch_size=X.shape[0], random_state=42, max_iter=300) 119 | print("Learning...") 120 | kmeans.fit(X) 121 | 122 | kmeans.save('Master/data/', 'kme-clusters') 123 | 124 | # with open(path.join(o_path, 'codebook-bovw-kme.cb'), 'w') as f: 125 | # print("Writing " + f.name) 126 | # f.write(str(kmeans.cluster_centers_.shape[1]) + '\n' + 127 | # str(kmeans.cluster_centers_.shape[0]) + '\n') 128 | # for c_center in kmeans.cluster_centers_: 129 | # f.write(' '.join(str(e) for e in c_center.tolist()) + '\n') 130 | 131 | log.close() 132 | 133 | ###Assignment --- Vector quantization 134 | log = Log(logs_path, 'bag-assignment-kme') 135 | 136 | #PRECISA SER TESTADO EM MAIS CASOS------- 137 | oufl = [] 138 | past = None 139 | count = 0 140 | for i in range(len(y)): 141 | if(y[i] != past): 142 | oufl.append((past, count)) 143 | count = 1 144 | past = y[i] 145 | else: count+=1 146 | past = y[i] 147 | oufl.append((past, count)) 148 | oufl = oufl[1:] 149 | #----- 150 | 151 | # ### TODO:data for classifier -- em um ambiente não supervisionado deve estar comentado 152 | im_names = {} 153 | im_features = np.zeros((len(oufl), k_clusters), np.float_) 154 | name_c = 0 155 | # ### 156 | 157 | quantization = kmeans.predict(X) 158 | j = 0 159 | 160 | t0 = time.time() 161 | for e in oufl: 162 | bag = [0] * k_clusters 163 | with open(path.join(o_path, 'BOW/assignment-kme/' + e[0] + '.codeword'), 'w') as fa, \ 164 | open(path.join(o_path, 'BOW/bag-kme/' + e[0] + '.bagw'), 'w') as fb: 165 | print("Writing " + fa.name + " and " + fb.name) 166 | for i in range(e[1]): 167 | vq = quantization[j] 168 | j += 1 169 | bag[int(vq)] += 1 170 | # ### ### TODO:data for classifier 171 | im_names[name_c] = e[0] 172 | im_features[name_c][int(vq)] += 1 173 | # ### 174 | fa_string = str(vq) + ' ' 175 | fa_string += ' '.join(str(k) for k in kmeans.cluster_centers_[vq]) + '\n' 176 | fa.write(fa_string) 177 | # ### ### TODO:data for classifier 178 | name_c += 1 179 | # ### 180 | sum_bag = sum(bag) 181 | fb.write(' '.join(str(k/sum_bag) for k in bag)) 182 | 183 | # ### ### TODO:data for classifier 184 | with open('Master/data/classf_data-train.pickle', 'wb') as handle: 185 | pickle.dump(im_names, handle, protocol=pickle.HIGHEST_PROTOCOL) 186 | pickle.dump(im_features, handle, protocol=pickle.HIGHEST_PROTOCOL) 187 | ### 188 | 189 | 190 | log.close() 191 | 192 | if __name__ == "__main__": 193 | main() -------------------------------------------------------------------------------- /HoVW/src/meanshift-graphs-test.py: -------------------------------------------------------------------------------- 1 | import sys, os, pickle 2 | import numpy as np 3 | from image import Image 4 | from apted import APTED, Config 5 | from apted.helpers import Tree 6 | from apted import APTED, PerEditOperationConfig 7 | 8 | class my_distance(Config): 9 | def __init__(self, centroids_matrix): 10 | self.centroids_matrix = centroids_matrix 11 | self.centroids_mean = centroids_matrix.mean() 12 | 13 | def delete(self, node): 14 | """Calculates the cost of deleting a node""" 15 | a = np.max([np.log2(node.neighbors), np.log2(node.depth)]) 16 | a = 1/a if a > 0 else 0 17 | return self.centroids_mean * a 18 | 19 | def insert(self, node): 20 | """Calculates the cost of inserting a node""" 21 | return self.delete(node) 22 | 23 | def rename(self, node1, node2): 24 | """Compares attribute .value of trees""" 25 | if node1.label == None or node2.label == None: 26 | return 0 #atenção aqui, se for raiz e tentar renomear a raiz dá zero. precisa ser melhor pensado 27 | return self.centroids_matrix[node1.label][node2.label] 28 | 29 | def children(self, node): 30 | return node.childs 31 | 32 | def compute_kneighbors(X): 33 | labels = [] 34 | for x in X: 35 | l = np.argwhere(x == np.min(x))[0][0] 36 | labels.append(l) 37 | 38 | return labels 39 | 40 | def compute_distance_matrix(test_imgs, codebook_trees, cmdist): 41 | M = np.zeros((len(test_imgs), len(codebook_trees)), np.float_) 42 | for i in range(len(test_imgs)): 43 | print(i) 44 | t1 = test_imgs[i] 45 | M[i] = ([APTED(t1.tree.root, t2.tree.root, my_distance(cmdist)).compute_edit_distance() for t2 in codebook_trees]) 46 | 47 | return M 48 | 49 | def assign_labels(test_imgs, labels, output): 50 | print("Assigning labels") 51 | with open(output, 'wb') as handle: 52 | for t, l in zip(test_imgs, labels): 53 | t.tree.label = l 54 | print(t.tree.name, l) 55 | pickle.dump(t, handle, protocol=pickle.HIGHEST_PROTOCOL) 56 | 57 | def main(): 58 | 59 | test_file = sys.argv[1] 60 | codebook_file = sys.argv[2] 61 | cdist_file = sys.argv[3] 62 | cluster_centers_file = sys.argv[4] 63 | 64 | test_imgs = [] 65 | with open(test_file, 'rb') as f: 66 | while True: 67 | try: 68 | test_imgs.append(pickle.load(f)) 69 | except EOFError: 70 | break 71 | codebook = np.load(codebook_file) 72 | codebook_map = codebook['map'] 73 | codebook_trees = codebook['trees'] 74 | a = np.load(cdist_file) 75 | cluster_centers = np.load(cluster_centers_file) 76 | 77 | M = compute_distance_matrix(test_imgs, codebook_trees, a) 78 | 79 | labels = compute_kneighbors(M) 80 | 81 | assign_labels(test_imgs, labels, 'Master/data/img_trees_labeled_full-test.pickle') 82 | 83 | if __name__ == '__main__': 84 | main() 85 | 86 | -------------------------------------------------------------------------------- /HoVW/src/meanshift-graphs.py: -------------------------------------------------------------------------------- 1 | import sys, os, pickle, math 2 | import numpy as np 3 | from sklearn.utils import check_random_state 4 | from sklearn.neighbors import NearestNeighbors 5 | 6 | from sklearn import metrics 7 | from sklearn.metrics import pairwise_distances 8 | 9 | ''' 10 | sklearn source code with some changes in relation to the distance metric 11 | 12 | http://scikit-learn.org/stable/auto_examples/cluster/plot_mean_shift.html#example-cluster-plot-mean-shift-py 13 | 14 | 15 | @article{scikit-learn, 16 | title={Scikit-learn: Machine Learning in {P}ython}, 17 | author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. 18 | and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. 19 | and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and 20 | Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, 21 | journal={Journal of Machine Learning Research}, 22 | volume={12}, 23 | pages={2825--2830}, 24 | year={2011} 25 | } 26 | ''' 27 | 28 | def get_mean_node(points, M): 29 | 30 | dist = np.zeros((points.shape[0],)) 31 | 32 | for i in range(points.shape[0]): 33 | D = M[points[i],points] 34 | dist[i] = np.sum(D) 35 | 36 | pos=np.argmin(dist) 37 | 38 | return points[pos] 39 | 40 | def compute_kneighbors(X, k, Y=None): 41 | 42 | dist = X 43 | if Y is not None: 44 | dist = X[:,Y] 45 | 46 | S = np.argsort(dist, axis=1) 47 | 48 | idx = S[:,range(k)] 49 | 50 | M = np.zeros((idx.shape)) 51 | i=0 52 | for sa in S: 53 | M[i,:] = dist[i,sa[:k]] 54 | i+=1 55 | 56 | return M, idx 57 | 58 | def estimate_bandwidth(X): 59 | """Estimate the bandwidth to use with MeanShift algorithm 60 | 61 | Parameters 62 | ---------- 63 | X : array [n_samples, n_features] 64 | Input points. 65 | 66 | quantile : float, default 0.3 67 | should be between [0, 1] 68 | 0.5 means that the median of all pairwise distances is used. 69 | 70 | n_samples : int 71 | The number of samples to use. If None, all samples are used. 72 | 73 | random_state : int or RandomState 74 | Pseudo number generator state used for random sampling. 75 | 76 | Returns 77 | ------- 78 | bandwidth : float 79 | The bandwidth parameter. 80 | """ 81 | 82 | quantile=0.3 83 | random_state=0 84 | random_state = check_random_state(random_state) 85 | 86 | knn = int(X.shape[0] * quantile) 87 | #nbrs = NearestNeighbors(n_neighbors=int(X.shape[0] * quantile)) 88 | #nbrs.fit(X) 89 | 90 | d, _ = compute_kneighbors(X, knn) 91 | bandwidth = np.mean(np.max(d, axis=1)) 92 | 93 | return bandwidth 94 | 95 | def compute_radius_neighbors(X, M, radius, points=None): 96 | """Finds the neighbors within a given radius of a point or points. 97 | 98 | Returns indices of the neighbors of each point. 99 | 100 | Parameters 101 | ---------- 102 | X : array-like, last dimension same as that of fit data 103 | The new point or points 104 | 105 | radius : float 106 | Limiting distance of neighbors to return. 107 | (default is the value passed to the constructor). 108 | 109 | return_distance : boolean, optional. Defaults to True. 110 | If False, distances will not be returned 111 | 112 | Returns 113 | ------- 114 | dist : array 115 | Array representing the euclidean distances to each point, 116 | only present if return_distance=True. 117 | 118 | ind : array 119 | Indices of the nearest points in the population matrix. 120 | 121 | Examples 122 | -------- 123 | In the following example, we construct a NeighborsClassifier 124 | class from an array representing our data set and ask who's 125 | the closest point to [1,1,1] 126 | 127 | >>> samples = [[0., 0., 0.], [0., .5, 0.], [1., 1., .5]] 128 | >>> from sklearn.neighbors import NearestNeighbors 129 | >>> neigh = NearestNeighbors(radius=1.6) 130 | >>> neigh.fit(samples) # doctest: +ELLIPSIS 131 | NearestNeighbors(algorithm='auto', leaf_size=30, ...) 132 | >>> print(neigh.radius_neighbors([1., 1., 1.])) # doctest: +ELLIPSIS 133 | (array([[ 1.5, 0.5]]...), array([[1, 2]]...) 134 | 135 | The first array returned contains the distances to all points which 136 | are closer than 1.6, while the second array returned contains their 137 | indices. In general, multiple points can be queried at the same time. 138 | 139 | Notes 140 | ----- 141 | Because the number of neighbors of each point is not necessarily 142 | equal, the results for multiple query points cannot be fit in a 143 | standard data array. 144 | For efficiency, `radius_neighbors` returns arrays of objects, where 145 | each object is a 1D array of indices or distances. 146 | """ 147 | 148 | #X = atleast2d_or_csr(X) 149 | if points is None: 150 | points = range(M.shape[1]) 151 | 152 | dist = M[X, points] 153 | neigh_ind = np.where(dist < radius)[0] 154 | 155 | # if there are the same number of neighbors for each point, 156 | # we can do a normal array. Otherwise, we return an object 157 | # array with elements that are numpy arrays 158 | try: 159 | neigh_ind = np.asarray(neigh_ind, dtype=int) 160 | dtype_F = float 161 | except ValueError: 162 | neigh_ind = np.asarray(neigh_ind, dtype='object') 163 | dtype_F = object 164 | 165 | return neigh_ind 166 | 167 | def mean_shift(X, bandwidth=None): 168 | """ 169 | Perform MeanShift Clustering of data using a flat kernel 170 | 171 | Seed using a binning technique for scalability. 172 | 173 | Parameters 174 | ---------- 175 | 176 | X : matrix of distance (source X source) 177 | Input data. 178 | 179 | bandwidth : float, optional 180 | Kernel bandwidth. 181 | If bandwidth is not defined, it is set using 182 | a heuristic given by the median of all pairwise distances. 183 | 184 | seeds : array [n_seeds, n_features] 185 | Point used as initial kernel locations. 186 | 187 | bin_seeding : boolean 188 | If true, initial kernel locations are not locations of all 189 | points, but rather the location of the discretized version of 190 | points, where points are binned onto a grid whose coarseness 191 | corresponds to the bandwidth. Setting this option to True will speed 192 | up the algorithm because fewer seeds will be initialized. 193 | default value: False 194 | Ignored if seeds argument is not None. 195 | 196 | min_bin_freq : int, optional 197 | To speed up the algorithm, accept only those bins with at least 198 | min_bin_freq points as seeds. If not defined, set to 1. 199 | 200 | Returns 201 | ------- 202 | 203 | cluster_centers : array [n_clusters, n_features] 204 | Coordinates of cluster centers. 205 | 206 | labels : array [n_samples] 207 | Cluster labels for each point. 208 | 209 | Notes 210 | ----- 211 | See examples/cluster/plot_meanshift.py for an example. 212 | 213 | """ 214 | 215 | min_bin_freq=1 216 | max_iterations=300 217 | bandwidth = bandwidth if bandwidth != None else estimate_bandwidth(X) 218 | seeds = range(X.shape[0]) #get_bin_seeds(X, bandwidth, min_bin_freq) 219 | 220 | n_samples = X.shape[0] 221 | stop_thresh = 1e-3 * bandwidth # when mean has converged 222 | center_intensity_dict = {} 223 | 224 | #nbrs = NearestNeighbors(radius=bandwidth).fit(X) 225 | 226 | # For each seed, climb gradient until convergence or max_iterations 227 | for my_mean in seeds: 228 | completed_iterations = 0 229 | 230 | while True: 231 | # Find mean of points within bandwidth 232 | #i_nbrs = 233 | points_within = compute_radius_neighbors(my_mean, X, bandwidth) 234 | 235 | 236 | #points_within = X[i_nbrs] 237 | if points_within.size == 0: 238 | break # Depending on seeding strategy this condition may occur 239 | my_old_mean = my_mean # save the old mean 240 | my_mean = get_mean_node(points_within, X) 241 | # If converged or at max_iterations, addS the cluster 242 | if (X[my_mean, my_old_mean] < stop_thresh or 243 | completed_iterations == max_iterations): 244 | center_intensity_dict[my_mean] = points_within.size 245 | break 246 | completed_iterations += 1 247 | 248 | # POST PROCESSING: remove near duplicate points 249 | # If the distance between two kernels is less than the bandwidth, 250 | # then we have to remove one because it is a duplicate. Remove the 251 | # one with fewer points. 252 | 253 | sorted_by_intensity = sorted(center_intensity_dict.items(), 254 | key=lambda tup: tup[1], reverse=True) 255 | 256 | sorted_centers = np.array([tup[0] for tup in sorted_by_intensity]) 257 | 258 | unique = np.ones(len(sorted_centers), dtype=np.bool) 259 | 260 | #nbrs = NearestNeighbors(radius=bandwidth).fit(sorted_centers) 261 | for i, center in enumerate(sorted_centers): 262 | if unique[i]: 263 | neighbor_idxs = compute_radius_neighbors(center, X, bandwidth, sorted_centers) 264 | unique[neighbor_idxs] = 0 265 | unique[i] = 1 # leave the current point as unique 266 | cluster_centers = sorted_centers[unique] 267 | 268 | 269 | # ASSIGN LABELS: a point belongs to the cluster that it is closest to 270 | #nbrs = NearestNeighbors(n_neighbors=1).fit(cluster_centers) 271 | 272 | # Not necessary 273 | labels = np.zeros(n_samples, dtype=np.int) 274 | distances, idxs = compute_kneighbors(X, 1, cluster_centers) 275 | 276 | labels = idxs.flatten() #cluster_all == True 277 | #labels.fill(-1) #cluster_all == False 278 | 279 | bool_selector = distances.flatten() <= bandwidth 280 | labels[bool_selector] = idxs.flatten()[bool_selector] 281 | 282 | ''' 283 | #AVALIACAO 284 | D = X[~np.eye(X.shape[0],dtype=bool)].reshape(X.shape[0],-1) 285 | print("silhouette:", metrics.silhouette_score(D, labels, metric='mahalanobis')) 286 | print("calinski_harabaz:", metrics.calinski_harabaz_score(D, labels)) 287 | ''' 288 | 289 | return np.array(cluster_centers) , np.array(labels) 290 | 291 | def save_codebook(centers, labels, trees_file, output): 292 | 293 | img_trees = [] 294 | with open(trees_file, 'rb') as f: 295 | while True: 296 | try: 297 | img_trees.append(pickle.load(f)) 298 | except EOFError: 299 | break 300 | 301 | D = {} 302 | T = [] 303 | for c in centers: 304 | D[labels[c]] = c 305 | img_trees[c].tree.label = labels[c] #já dá a label aqui msm 306 | T.append(img_trees[c]) 307 | 308 | 309 | np.savez(output + '_codebook.npz', map=D, trees=T) #dict mapping C -> L 310 | 311 | return D, T 312 | 313 | def save_centers(centers, labels, output): 314 | np.save(output + '_centers.npy', centers) 315 | np.save(output + '_vq-train.npy', labels) #o index da lista de centroids corresponde a label associada 316 | 317 | def main(): 318 | 319 | matrix_file = sys.argv[1] 320 | output = sys.argv[2] 321 | 322 | trees_file = sys.argv[4] 323 | 324 | M = np.load(matrix_file) 325 | 326 | bandwidth = estimate_bandwidth(M) if sys.argv[3] == 'None' else float(sys.argv[3]) 327 | 328 | print("Bandwidth: {}".format(bandwidth)) 329 | # with open('exec/results-batch.txt', 'a') as f: 330 | # f.write("- BWValue = {}\n".format(bandwidth)) 331 | # with open('exec/results-batch2.txt', 'a') as f: 332 | # f.write("- asdBWValue = {}\n".format(bandwidth)) 333 | 334 | C, L = mean_shift(M, bandwidth) 335 | with open('exec/results-batch.txt', 'a') as f: 336 | f.write('C_size = {}\n'.format(C.size)) 337 | with open('exec/results-batch2.txt', 'a') as f: 338 | f.write('C_size = {}\n'.format(C.size)) 339 | 340 | save_centers(C, L, output) 341 | D, T = save_codebook(C, L, trees_file, output) 342 | 343 | print(C, C.size) 344 | print(L, L.size) 345 | print(D, len(D)) 346 | 347 | 348 | # TODO:Análise do cluster 0; todo código pode ser removido 349 | # cluster0_indexes = np.where(L == 0)[0] 350 | # cluster0_size = cluster0_indexes.shape[0] 351 | # cluster0_matrix = np.zeros((cluster0_size,cluster0_size), dtype=np.float_) 352 | 353 | # ai = 0 354 | # for x,i in zip(M,range(M.shape[0])): 355 | # aj = 0 356 | # if (i not in cluster0_indexes): 357 | # continue 358 | # for y,j in zip(x,range(M.shape[0])): 359 | # if(j not in cluster0_indexes): 360 | # continue 361 | # cluster0_matrix[ai,aj] = M[i,j] 362 | # aj += 1 363 | # ai += 1 364 | 365 | # print(cluster0_matrix[1]) 366 | 367 | # cluster0_bandwidth = estimate_bandwidth(cluster0_matrix) 368 | # print("cluster0_bandwidth: {}".format(cluster0_bandwidth)) 369 | # cluster0_C, cluster0_L = mean_shift(cluster0_matrix, cluster0_bandwidth) 370 | # print(cluster0_C, cluster0_C.size) 371 | # print(cluster0_L, cluster0_L.size) 372 | main() 373 | -------------------------------------------------------------------------------- /HoVW/src/pickle4reducer.py: -------------------------------------------------------------------------------- 1 | from multiprocessing.reduction import ForkingPickler, AbstractReducer 2 | 3 | class ForkingPickler4(ForkingPickler): 4 | def __init__(self, *args): 5 | args = list(args) 6 | if len(args) > 1: 7 | args[1] = 2 8 | else: 9 | args.append(2) 10 | 11 | super().__init__(*args) 12 | 13 | @classmethod 14 | def dumps(cls, obj, protocol=4): 15 | return ForkingPickler.dumps(obj, protocol) 16 | 17 | def dump(obj, file, protocol=4): 18 | ForkingPickler4(file, protocol).dump(obj) 19 | 20 | class Pickle4Reducer(AbstractReducer): 21 | ForkingPickler = ForkingPickler4 22 | register = ForkingPickler4.register 23 | dump = dump -------------------------------------------------------------------------------- /HoVW/src/tree.py: -------------------------------------------------------------------------------- 1 | class ImageTreeNode: 2 | def __init__(self, name, parent, label=None, data=None): 3 | self.name = name 4 | self.label = label 5 | self.parent = parent 6 | self.mask = data 7 | self.depth = -1 #nível da arvore 8 | self.neighbors = -1 #quantidade de nós no mesmo nível 9 | self.childs = [] 10 | 11 | def add_child(self, child): 12 | self.childs.append(child) 13 | 14 | def remove_child(self, child): 15 | self.childs.remove(child) 16 | 17 | def set_label(self, label): 18 | self.label = label 19 | 20 | def print_node(self, indent=''): 21 | print(indent, "+ TreeNode(", self.name, "):") 22 | print(indent, "\t- label = ", 23 | ("Unlabeled" if self.label is None else self.label)) 24 | print(indent, "\t- depth = ", str(self.depth)) 25 | print(indent, "\t- neighbors count = ", str(self.neighbors)) 26 | print(indent, "\t- parent =", (self.parent.name, self.parent) 27 | if(self.parent) else 'None') 28 | print(indent, "\t- mask =", self.mask) 29 | print(indent, "\t- childs =", [(c.name, c) for c in self.childs]) 30 | print() 31 | 32 | class ImageTree: 33 | def __init__(self, hierarchy, masks, name='-1'): 34 | self.root = ImageTreeNode(name='-1', parent=None, 35 | label=None, data=None) 36 | self.total_nodes = 1#Setado em 1 pq tem a raiz 37 | #Atributo alterado em: _build_subtree; 38 | # _cut_off; _cut_off_none_child 39 | self._build_tree(hierarchy, masks) 40 | self.name = name 41 | self.label = None 42 | 43 | def _build_subtree(self, hierarchy, parent, index, 44 | brothers_list=[]): 45 | node = ImageTreeNode(name=str(index), parent=parent, 46 | label=None, data=hierarchy[index][5]) 47 | self.total_nodes += 1 48 | if(hierarchy[index][2] == -1): 49 | if(hierarchy[index][0] == -1): 50 | return node 51 | elif(hierarchy[index][1] == -1): #first leaf 52 | brothers_list.append(node) 53 | bi = hierarchy[index][0] 54 | while(bi != -1 and parent != self.root): 55 | k = self._build_subtree(hierarchy, parent, 56 | bi, brothers_list) 57 | brothers_list.append(k) 58 | bi = hierarchy[bi][0] 59 | 60 | return brothers_list 61 | return node 62 | else: 63 | inf_tree = self._build_subtree(hierarchy, node, 64 | hierarchy[index][2], []) 65 | if(isinstance(inf_tree, list)): 66 | for st in inf_tree: node.add_child(st) 67 | else: node.add_child(inf_tree) 68 | 69 | return node 70 | 71 | def _build_tree(self, hierarchy, masks): 72 | ''' 73 | hierarchy[i][0] = Next; .[1] = Previous; .[2] = First Child; 74 | hierarchy[i][3] = Parent; .[4] = Usable (1=T|0=F); .[5] = Mask 75 | ''' 76 | 77 | def _merge_hierarchy_mask(hierarchy, masks): 78 | h = [] 79 | mask_index = 0 80 | for i in range(len(hierarchy)): 81 | element = hierarchy[i].tolist() 82 | if(element[4] == 1): 83 | element.append(masks[mask_index]) 84 | mask_index += 1 85 | else: 86 | element.append(None) 87 | h.append(element) 88 | 89 | return h 90 | 91 | def _build_stack(hierarchy): 92 | stack = [] 93 | for i in range(len(hierarchy)): 94 | if(hierarchy[i][3] == -1): 95 | stack.append(i) 96 | 97 | return stack 98 | 99 | def _cut_off_none_child(node): 100 | for child in list(node.childs): 101 | if child.mask is None: 102 | node.childs.remove(child) 103 | self.total_nodes -= 1 104 | else: 105 | _cut_off_none_child(child) 106 | 107 | hierarchy = _merge_hierarchy_mask(hierarchy, masks) 108 | stack = _build_stack(hierarchy) 109 | while(stack): 110 | index = stack.pop() 111 | subtree = self._build_subtree(hierarchy, self.root, index, []) 112 | if(isinstance(subtree,list)): 113 | for st in subtree: self.root.add_child(st) 114 | else: self.root.add_child(subtree) 115 | 116 | _cut_off_none_child(self.root) 117 | 118 | def _cut_off(self, value, node): 119 | for child in list(node.childs): 120 | if(child.mask.area < value): 121 | self.total_nodes -= 1 + len(child.childs) 122 | node.childs.remove(child) 123 | else: 124 | self._cut_off(value, child) 125 | 126 | def cut_off(self, value): 127 | def _sum_nodes_area(node, total_area): 128 | try: 129 | total_area += node.mask.area 130 | except AttributeError as err: 131 | #print(err) 132 | pass 133 | for child in list(node.childs): 134 | total_area = _sum_nodes_area(child, total_area) 135 | 136 | return total_area 137 | 138 | 139 | value = value * _sum_nodes_area(self.root, 0) / self.total_nodes 140 | self._cut_off(value, self.root) 141 | 142 | def print_tree(self, simple=None): 143 | def _print_tree_node_simple(node, indent): 144 | print(indent, '[', node.name, ']') 145 | indent += '\t' 146 | for child in node.childs: 147 | _print_tree_node_simple(child, indent) 148 | 149 | def _print_tree_simple(): 150 | print('[', self.root.name, ']') 151 | indent = '\t' 152 | for child in self.root.childs: 153 | _print_tree_node_simple(child, indent) 154 | 155 | def _print_tree_node_complete(node, indent): 156 | node.print_node(indent=indent) 157 | indent += '\t' 158 | for child in node.childs: 159 | _print_tree_node_complete(child, indent) 160 | 161 | def _print_tree_complete(): 162 | self.root.print_node() 163 | indent = '\t' 164 | for child in self.root.childs: 165 | _print_tree_node_complete(child, indent) 166 | 167 | if simple: 168 | _print_tree_simple() 169 | else: 170 | _print_tree_complete() 171 | 172 | def _draw_tree(self, node, output): 173 | try: 174 | node.mask.draw('c', output, node.name) 175 | except AttributeError as err: 176 | #print(err) 177 | pass 178 | for child in list(node.childs): 179 | self._draw_tree(child, output) 180 | 181 | def draw_tree(self, output): 182 | self._draw_tree(self.root, output) 183 | 184 | def _get_tree_data(self, node, data): 185 | try: 186 | data.append(node) 187 | except AttributeError as err: 188 | #print(err) 189 | pass 190 | for child in list(node.childs): 191 | data = self._get_tree_data(child, data) 192 | 193 | return data 194 | 195 | def get_tree_data(self): #return list of nodes 196 | return self._get_tree_data(self.root, []) 197 | 198 | def _get_tree_masks(self, node, data): 199 | try: 200 | data.append(node.mask) 201 | except AttributeError as err: 202 | #print(err) 203 | pass 204 | for child in list(node.childs): 205 | data = self._get_tree_masks(child, data) 206 | 207 | return data 208 | 209 | def get_tree_masks(self): #return list of nodes 210 | return self._get_tree_masks(self.root, []) 211 | 212 | def _set_labels(self, node, labels): 213 | try: 214 | node.set_label(labels.pop(0)) 215 | except AttributeError as err: 216 | #print(err) 217 | pass 218 | except IndexError as err: 219 | print("DEU UMA MERDA CABULOSA") 220 | print(err) 221 | exit(1) 222 | for child in list(node.childs): 223 | self._set_labels(child, labels) 224 | 225 | def set_labels(self, labels): 226 | ''' 227 | root tem que ser vazio: [None] + labels 228 | ''' 229 | labels = [None] + labels 230 | self._set_labels(self.root, labels) 231 | 232 | def _set_nodes_depth(self, node, depth, width): 233 | try: 234 | node.depth = depth 235 | if(depth not in width): 236 | width[depth] = 1 237 | else: 238 | width[depth] += 1 239 | except AttributeError as err: 240 | #print(err) 241 | pass 242 | except IndexError as err: 243 | print("DEU UMA MERDA CABULOSA") 244 | print(err) 245 | exit(1) 246 | 247 | for child in list(node.childs): 248 | _, width = self._set_nodes_depth(child, depth+1, width) 249 | 250 | node.neighbors = width[depth] 251 | return depth, width 252 | 253 | def set_nodes_depth(self): 254 | _, width = self._set_nodes_depth(self.root, 1, {}) 255 | return width #dict depth : width 256 | 257 | def _get_apted(self, node, apted, depth, width): 258 | try: 259 | apted += '{' 260 | apted += str(node.label) if node.label != None else '-1' 261 | 262 | if(depth not in width): 263 | width[depth] = 1 264 | else: 265 | width[depth] += 1 266 | except AttributeError as err: 267 | #print(err) 268 | pass 269 | except IndexError as err: 270 | print("DEU UMA MERDA CABULOSA") 271 | print(err) 272 | exit(1) 273 | 274 | for child in list(node.childs): 275 | apted, _, width = self._get_apted(child, apted, depth+1, width) 276 | apted += '}' 277 | 278 | return apted, depth, width 279 | 280 | def set_apted(self): 281 | 282 | apted, _, width = self._get_apted(self.root, '', 1, {}) 283 | apted += '}' 284 | 285 | return apted, width -------------------------------------------------------------------------------- /HoVW/src/trees-distance.py: -------------------------------------------------------------------------------- 1 | import pickle, argparse, collections, time, multiprocessing, math 2 | from itertools import product, combinations, islice 3 | from functools import partial 4 | from os import listdir, path 5 | import matplotlib.pyplot as plt 6 | import numpy as np 7 | import pickle4reducer 8 | from scipy.spatial.distance import cdist 9 | from apted import APTED, Config, PerEditOperationConfig 10 | from apted.helpers import Tree 11 | from image import Image 12 | 13 | class ImageTreeDistance(Config): 14 | def __init__(self, centroids_matrix): 15 | self.centroids_matrix = centroids_matrix 16 | self.centroids_mean = centroids_matrix.mean() 17 | 18 | def delete(self, node): 19 | """Calculates the cost of deleting a node""" 20 | #a = np.max([(node.neighbors), (node.depth)]) 21 | a = np.max([np.log2(node.neighbors), np.log2(node.depth)]) 22 | a = 1/a if a > 0 else 0 23 | return self.centroids_mean * a 24 | 25 | def insert(self, node): 26 | """Calculates the cost of inserting a node""" 27 | return self.delete(node) 28 | 29 | def rename(self, node1, node2): 30 | """Compares attribute .value of trees""" 31 | # ATTENTION: if the node is a root node and if try to relabeled 32 | # it the cost is zero 33 | if node1.label == None or node2.label == None: 34 | return 0 35 | 36 | return self.centroids_matrix[node1.label][node2.label] 37 | 38 | def children(self, node): 39 | return node.childs 40 | 41 | def init_args(): 42 | """Input Parameters""" 43 | parser = argparse.ArgumentParser() 44 | parser.add_argument('-i', help='images tree labeled file') 45 | parser.add_argument('-c', help='clusters distance file') 46 | parser.add_argument('-m', help='output trees distance matrix') 47 | parser.add_argument('-d', help='apted custom tree edit distance class') 48 | parser.add_argument('-p', help='qtd parallel process') 49 | 50 | return parser.parse_args() 51 | 52 | def heatmap_plot(distances): 53 | plt.imshow(distances, cmap='inferno', interpolation='nearest') 54 | plt.colorbar() 55 | plt.title("Hierarchies Distance Matrix Heatmap") 56 | plt.savefig("distance_heatmap.png") 57 | 58 | def calc_dist_trees(t1, t2, clusters_dist): 59 | print(t1.tree.name, t2.tree.name) 60 | return APTED(t1.tree.root, t2.tree.root, 61 | ImageTreeDistance(clusters_dist)).compute_edit_distance() 62 | 63 | def combinations_matrix(shape, combinations_list): 64 | A = np.zeros(shape, dtype=np.float_) 65 | limit = combinations_list.shape[0]-1 66 | b0 = 0 67 | for a,j in zip(A, range(A.shape[1]-1)): 68 | t = a.shape[0] - (j+1) 69 | b1 = b0 + t 70 | b1 = b1 if b1 < limit else limit 71 | if(b0 == b1): b1 += 1 72 | assign = combinations_list[b0:b1] 73 | a[j+1:] = assign 74 | A[j+1:,j] = assign 75 | b0 = b1 76 | 77 | return A 78 | 79 | def main(): 80 | args = init_args() 81 | 82 | trees_path = args.i 83 | cdist_path = args.c 84 | apted_dist_save = args.d 85 | tmatrix_path = args.m 86 | qtd_process = int(args.p) 87 | 88 | img_trees = [] 89 | with open(trees_path, 'rb') as f: 90 | while True: 91 | try: 92 | img_trees.append(pickle.load(f)) 93 | except EOFError: 94 | break 95 | 96 | a = clusters_dist = np.load(cdist_path) 97 | 98 | i, j = np.argwhere(a == np.min(a[np.where(a > 0)]))[0] 99 | print("Min = A[%d,%d] = %.16f" % (i, j, a[i,j])) 100 | 101 | i,j = np.unravel_index(a.argmax(), a.shape) 102 | print("Max = A[%d,%d] = %.16f" % (i, j, a[i,j])) 103 | 104 | print("Mean(A) =", a.mean(), "\nMedian(A) =", np.median(a)) 105 | 106 | with open(path.join(apted_dist_save), 'wb') as handle: 107 | pickle.dump(ImageTreeDistance(clusters_dist), handle, protocol=pickle.HIGHEST_PROTOCOL) 108 | 109 | calc_dist_trees_partial = partial(calc_dist_trees,clusters_dist=clusters_dist) 110 | 111 | #parallel 112 | t0 = time.time() 113 | 114 | repetition = 2 115 | comb_iter = combinations(img_trees, r=repetition) 116 | 117 | """ 118 | n!/(r!*(n-r)!) = 1/r! * n * (n-1) * ... * (n-r+1) 119 | """ 120 | comb_iter_size = len(img_trees)*(len(img_trees)-1)//math.factorial(repetition) 121 | 122 | tree_distances = [] 123 | chuncks = 1 124 | 125 | # ctx = multiprocessing.get_context() 126 | # ctx.reducer = pickle4reducer.Pickle4Reducer() 127 | 128 | for i in range(chuncks): 129 | print("Chunck {}".format(i)) 130 | comb_sliced = islice(comb_iter, 0, comb_iter_size//chuncks) 131 | with multiprocessing.Pool(processes=qtd_process) as pool: 132 | td = pool.starmap(calc_dist_trees_partial, comb_sliced) 133 | tree_distances += td 134 | 135 | tree_distances = combinations_matrix((len(img_trees),len(img_trees)), np.array(tree_distances)) 136 | 137 | 138 | print("Parallel Time: ", time.time() - t0) 139 | 140 | # #sequential 141 | # tree_distances = np.zeros((len(img_trees), len(img_trees)), np.float_) 142 | # t0 = time.time() 143 | 144 | # for t1, i in zip(img_trees, range(len(img_trees))): 145 | # print(i) 146 | # tree_distances[i] = ([calc_dist_trees_partial(t1, t2) for t2 in img_trees]) 147 | 148 | # print("Sequential Time: ", time.time() - t0) 149 | 150 | print(tree_distances) 151 | np.save(tmatrix_path, tree_distances) 152 | 153 | heatmap_plot(tree_distances) 154 | 155 | if __name__ == "__main__": 156 | main() -------------------------------------------------------------------------------- /HoVW/src/utils.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import os, time 4 | 5 | class Log(object): 6 | """General logs files management. 7 | 8 | Parameters 9 | ---------- 10 | path: Path for log's file. 11 | name: Log's file name. 12 | 13 | Attributes 14 | ---------- 15 | path: string 16 | Path where the log file is in. 17 | name: string, default = None 18 | Name of the log file. 19 | stime: time 20 | Object instantiation time. 21 | etime: time, default = None 22 | File closing time. 23 | log_file: file 24 | File object. 25 | """ 26 | 27 | def __init__(self, path, name=None): 28 | self.path = path 29 | self.name = name + '.log' if name else '.log' 30 | self.stime = time.time() 31 | self.etime = None 32 | self.log_file = open(os.path.join(self.path, self.name), 'w') 33 | 34 | def write(self, **kwargs): 35 | """Write in log's file. 36 | 37 | Parameters 38 | ---------- 39 | kwargs: Dictionary, key = signature, value = parameter 40 | Arbitrary sequence of parameters. 41 | """ 42 | 43 | for a in kwargs: 44 | self.log_file.write(str(a.upper()) + ": ") 45 | self.log_file.write(str(kwargs[a]) + '\n') 46 | 47 | def close(self): 48 | """Closes the log's file. 49 | """ 50 | 51 | self.etime = time.time() 52 | a = self.etime-self.stime 53 | ts = '%s s = %s m' % (a, a/60) 54 | self.write(start_time=self.stime, end_time=self.etime, timestamp=ts) 55 | self.log_file.close() -------------------------------------------------------------------------------- /HoVW/views/find_clusters_neighbor.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from scipy.cluster import hierarchy 3 | 4 | Z = np.load("Master/data/dendogram.npy") 5 | 6 | clusters = [] 7 | k = 34 8 | 9 | clusters.append(k) 10 | #print(clusters) 11 | 12 | asd = True 13 | 14 | while(asd == True): 15 | if(len(clusters)==458): 16 | break 17 | x = 1; y = 0 18 | for z,i in zip(Z, range(Z.shape[0])): 19 | if(int(z[0]) == k): 20 | if(z[1] < Z.shape[0]): #caso folha 21 | clusters.append(int(z[1])) 22 | #print(clusters) 23 | k = Z.shape[0] + i+1 24 | else: 25 | idx = int((z[1]%Z.shape[0])-1) 26 | if(Z[idx][0] < Z.shape[0] and Z[idx][1] < Z.shape[0]): # filhos folha-folha 27 | clusters.append(int(Z[idx][0])) 28 | clusters.append(int(Z[idx][1])) 29 | #print(clusters) 30 | k = Z.shape[0] + i+1 31 | elif(Z[idx][0] < Z.shape[0]): # filhos folha-nfolha 32 | clusters.append(int(Z[idx][0])) 33 | #print(clusters) 34 | k = int((Z[idx][1]%Z.shape[0])-1) 35 | elif(Z[idx][1] < Z.shape[0]): # filhos nfolha-folha 36 | clusters.append(int(Z[idx][1])) 37 | #print(clusters) 38 | k = int((Z[idx][0]%Z.shape[0])-1) 39 | else: 40 | k = int((Z[idx][x]%Z.shape[0])-1) 41 | print("saiu 1", x) 42 | x = 0 43 | 44 | elif(int(z[1]) == k): 45 | if(z[0] < Z.shape[0]): #caso folha 46 | clusters.append(int(z[0])) 47 | #print(clusters) 48 | k = Z.shape[0] + i+1 49 | else: 50 | idx = int((z[0]%Z.shape[0])-1) 51 | if(Z[idx][0] < Z.shape[0] and Z[idx][1] < Z.shape[0]): # caso folha-folha 52 | clusters.append(int(Z[idx][0])) 53 | clusters.append(int(Z[idx][1])) 54 | #print(clusters) 55 | k = Z.shape[0] + i+1 56 | elif(Z[idx][0] < Z.shape[0]): # filhos folha-nfolha 57 | clusters.append(int(Z[idx][0])) 58 | #print(clusters) 59 | k = int((Z[idx][1]%Z.shape[0])-1) 60 | elif(Z[idx][1] < Z.shape[0]): # filhos nfolha-folha 61 | clusters.append(int(Z[idx][1])) 62 | #print(clusters) 63 | k = int((Z[idx][0]%Z.shape[0])-1) 64 | else: 65 | k = int((Z[idx][y]%Z.shape[0])-1) 66 | print("saiu 2", y) 67 | y = 1 68 | 69 | print(clusters) 70 | 71 | -------------------------------------------------------------------------------- /HoVW/views/reveal_clusters-graphs.py: -------------------------------------------------------------------------------- 1 | import os, shutil, pickle, sys, re, collections 2 | sys.path.insert(0, 'src') 3 | from image import Image 4 | 5 | def handle_tree(tree, path): 6 | name = tree.name 7 | label = str(tree.label) 8 | 9 | print(name, label) 10 | 11 | dst = os.path.join(path, label) 12 | if label not in os.listdir(path): 13 | os.mkdir(dst) 14 | 15 | dst += '/' + re.sub('.*\/', '', name) 16 | 17 | shutil.copyfile(name, dst) 18 | 19 | def retrive_imgs(font): 20 | img_trees = [] 21 | for t in font: 22 | f_name = 'Master/data/img_trees_labeled_full-' + t + '.pickle' 23 | print("Reading from:", f_name) 24 | with open(f_name, 'rb') as f: 25 | while True: 26 | try: 27 | img_trees.append(pickle.load(f)) 28 | except EOFError: 29 | break 30 | 31 | return img_trees 32 | 33 | def clusters_len(img_trees): 34 | d = {} 35 | for it in img_trees: 36 | l = it.tree.label 37 | if l not in d: d[l] = 1 38 | else: d[l] += 1 39 | 40 | return collections.OrderedDict(sorted(d.items(), key=lambda t: t[0])) 41 | 42 | def make_dir(root, relative): 43 | 44 | if 'clusters' not in os.listdir(root): 45 | os.mkdir(os.path.join(root, 'clusters')) 46 | 47 | clusters = os.path.join(root, 'clusters') 48 | 49 | if relative in os.listdir(clusters): 50 | shutil.rmtree(os.path.join(clusters, relative)) 51 | 52 | root_clusters = os.path.join(clusters, relative) 53 | os.mkdir(root_clusters) 54 | os.mkdir(os.path.join(root_clusters, "full")) 55 | os.mkdir(os.path.join(root_clusters, "train")) 56 | os.mkdir(os.path.join(root_clusters, "test")) 57 | 58 | return root_clusters 59 | 60 | def log(font, d): 61 | f = open(font + '.txt', 'w') 62 | for k,v in d.items(): 63 | f.write(str(k) + ":" + str(v) + '\n') 64 | 65 | def main(): 66 | 67 | root = 'Master' 68 | relative = 'graphs' 69 | root_clusters = make_dir(root, relative) 70 | 71 | for t in [['train']]:#, ['test'], ['train', 'test']]: 72 | img_trees = retrive_imgs(t) 73 | 74 | dst = os.path.join(root_clusters, t[0]) \ 75 | if len(t) == 1 else os.path.join(root_clusters, 'full') 76 | 77 | for it in img_trees: 78 | handle_tree(it.tree, dst) 79 | 80 | d = clusters_len(img_trees) 81 | print(d) 82 | 83 | log(os.path.join(dst, 'log'), d) 84 | 85 | if __name__ == '__main__': 86 | main() -------------------------------------------------------------------------------- /HoVW/views/reveal_clusters-nodes.py: -------------------------------------------------------------------------------- 1 | import os, shutil, pickle, sys, re, collections 2 | sys.path.insert(0, 'src') 3 | from image import Image, Mask 4 | from tree import ImageTree, ImageTreeNode 5 | 6 | def handle_tree(tree, path): 7 | 8 | i = 0 9 | for n in tree.get_tree_data()[1:]: 10 | label = str(n.label) 11 | 12 | if label == None or n.mask == None: 13 | continue 14 | 15 | name = tree.name + ' ' + str(i) 16 | 17 | print(name, label) 18 | 19 | dst = os.path.join(path, label) 20 | if label not in os.listdir(path): 21 | os.mkdir(dst) 22 | 23 | dst += '/' + re.sub('.*\/', '', name) 24 | n.mask.draw(output=dst, header='-'+str(i)) 25 | i += 1 26 | 27 | def retrive_imgs(font): 28 | img_trees = [] 29 | for t in font: 30 | f_name = 'Master/data/img_trees_labeled_full-' + t + '.pickle' 31 | print("Reading from:", f_name) 32 | with open(f_name, 'rb') as f: 33 | while True: 34 | try: 35 | img_trees.append(pickle.load(f)) 36 | except EOFError: 37 | break 38 | 39 | return img_trees 40 | 41 | def clusters_len(img_trees): 42 | d = {} 43 | for it in img_trees: 44 | for inode in it.tree.get_tree_data()[1:]: 45 | l = inode.label 46 | if l not in d: d[l] = 1 47 | else: d[l] += 1 48 | print(d) 49 | return collections.OrderedDict(sorted(d.items(), key=lambda t: t[0])) 50 | 51 | def make_dir(root, relative): 52 | 53 | if 'clusters' not in os.listdir(root): 54 | os.mkdir(os.path.join(root, 'clusters')) 55 | 56 | clusters = os.path.join(root, 'clusters') 57 | 58 | if relative in os.listdir(clusters): 59 | shutil.rmtree(os.path.join(clusters, relative)) 60 | 61 | root_clusters = os.path.join(clusters, relative) 62 | os.mkdir(root_clusters) 63 | os.mkdir(os.path.join(root_clusters, "full")) 64 | os.mkdir(os.path.join(root_clusters, "train")) 65 | os.mkdir(os.path.join(root_clusters, "test")) 66 | 67 | return root_clusters 68 | 69 | def log(font, d): 70 | f = open(font + '.txt', 'w') 71 | for k,v in d.items(): 72 | f.write(str(k) + ":" + str(v) + '\n') 73 | 74 | def main(): 75 | 76 | root = 'Master' 77 | relative = 'nodes' 78 | root_clusters = make_dir(root, relative) 79 | 80 | for t in [['train'], ['test'], ['train', 'test']]: 81 | img_trees = retrive_imgs(t) 82 | 83 | dst = os.path.join(root_clusters, t[0]) \ 84 | if len(t) == 1 else os.path.join(root_clusters, 'full') 85 | 86 | for it in img_trees: 87 | it.tree.root 88 | handle_tree(it.tree, dst) 89 | 90 | d = clusters_len(img_trees) 91 | print(d) 92 | 93 | log(os.path.join(dst, 'log'), d) 94 | 95 | if __name__ == '__main__': 96 | main() -------------------------------------------------------------------------------- /HoVW/views/visualize_graph_spatial_distribution.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import numpy as np 3 | import matplotlib.pyplot as plt 4 | from mpl_toolkits.mplot3d import Axes3D 5 | import matplotlib.animation as animation 6 | 7 | class SpacePoint(): 8 | def __init__(self, coordinates=None, index=None, label=None): 9 | if coordinates == None: 10 | self.coordinates = self._np_coordinates((-1,-1,-1)) 11 | else: 12 | self.coordinates = self._np_coordinates(coordinates) 13 | 14 | if index == None: 15 | self.index = -1 16 | else: 17 | self.index = index 18 | 19 | if label == None: 20 | self.label = -1 21 | else: 22 | self.label = label 23 | 24 | def _np_coordinates(self,c): 25 | return np.array([c[0],c[1],c[2]], dtype=np.float_) 26 | 27 | def set_coordinates(self, c): 28 | self.coordinates = c 29 | 30 | def set_label(self, l): 31 | self.label = l 32 | 33 | def pprint(self): 34 | print("Point {} ; Label {}: \n\t- x: {}\n\t- y: {}\n\t- z: {}" 35 | .format(self.index, self.label, self.coordinates[0], self.coordinates[1], self.coordinates[2])) 36 | 37 | 38 | def update_lines(num, dataLines, lines): 39 | for line, data in zip(lines, dataLines): 40 | # NOTE: there is no .set_data() for 3 dim data... 41 | line.set_data(data[0:2, :num]) 42 | line.set_3d_properties(data[2, :num]) 43 | return lines 44 | 45 | def d2c(D): 46 | visited = [] 47 | all_points = [] 48 | #points are tuple of: ndarray for position and distance's matrix index 49 | p1 = SpacePoint((0,0,0), 0) 50 | visited.append(0) 51 | 52 | p1maxdist = np.amax(D[0]) 53 | p2index = np.argwhere(D == p1maxdist)[0][1] 54 | 55 | p2 = SpacePoint((p1maxdist,0,0), p2index) 56 | visited.append(p2index) 57 | 58 | all_points.append(p1) 59 | all_points.append(p2) 60 | 61 | for i in range(D[0].shape[0]): 62 | if i not in visited: 63 | p3 = SpacePoint((-1,-1,-1), i) 64 | visited.append(i) 65 | break 66 | 67 | p3x = D[p1.index][p2.index] ** 2 + D[p1.index][p3.index] ** 2 - D[p2.index][p3.index] ** 2 68 | p3x = p3x/(2*D[p1.index][p2.index]) 69 | p3y = np.sqrt(D[p1.index][p3.index] ** 2 - p3x ** 2) 70 | 71 | p3.set_coordinates((p3x, p3y, 0)) 72 | 73 | all_points.append(p3) 74 | 75 | for i in range(D[0].shape[0]): 76 | if i not in visited: 77 | p4 = SpacePoint((-1,-1,-1), i) 78 | visited.append(i) 79 | 80 | p4x = D[p1.index][p2.index] ** 2 + D[p1.index][p4.index] ** 2 - D[p2.index][p4.index] ** 2 81 | p4x = p4x/(2*D[p1.index][p2.index]) 82 | 83 | p4y = p3.coordinates[0] ** 2 + p3.coordinates[1] ** 2 - D[p1.index][p4.index] ** 2 84 | p4y = p4y - 2 * p3.coordinates[0] * p4x - D[p3.index][p4.index] ** 2 85 | p4y = p4y / (2 * p3.coordinates[1]) 86 | 87 | p4z = np.sqrt(D[p1.index][p4.index] ** 2 - p4x - p4y) 88 | 89 | p4.set_coordinates((p4x, p4y, p4z)) 90 | 91 | all_points.append(p4) 92 | 93 | return all_points 94 | 95 | if __name__ == '__main__': 96 | colors183 = ["#ff0000", "#ffc480", "#00b330", "#266399", "#621d73", "#f20000", "#8c6c46", "#004011", "#80c4ff", "#2e1a33", "#660000", "#59442d", "#264d30", "#001433", "#c299cc", "#330000", "#a6927c", "#608068", "#295ba6", "#47004d", "#994d4d", "#594f43", "#008c38", "#bfd9ff", "#d900ca", "#4c2626", "#ffaa00", "#1a3324", "#8698b3", "#ff80f6", "#331a1a", "#7f5500", "#a3d9b8", "#003de6", "#bf60b9", "#cc9999", "#593c00", "#00ff88", "#001b66", "#4d264a", "#b21800", "#bf8f30", "#33cc85", "#3662d9", "#4d394b", "#ff5940", "#a68a53", "#1a6642", "#1a2e66", "#b3008f", "#591f16", "#d9c7a3", "#29a67c", "#6c89d9", "#73005c", "#e58273", "#e5b800", "#73e6bf", "#2d3959", "#401036", "#663a33", "#403610", "#86b3a4", "#565e73", "#ffbff2", "#ffc8bf", "#f2da79", "#30403a", "#393e4d", "#997391", "#997873", "#736739", "#00ffcc", "#23318c", "#ff00aa", "#4d3c39", "#999173", "#bffff2", "#8091ff", "#994d80", "#731f00", "#bfb300", "#00f2e2", "#202440", "#33262f", "#cc5c33", "#8c8300", "#00998f", "#b6bef2", "#d90074", "#8c3f23", "#665f00", "#00403c", "#0000b3", "#660036", "#ffa280", "#a6a053", "#1d736d", "#0000a6", "#e5005c", "#b27159", "#333226", "#00eeff", "#000040", "#8c234d", "#7f5140", "#dae639", "#005359", "#737399", "#401023", "#d9b1a3", "#494d13", "#0d3033", "#262633", "#ff80b3", "#ff6600", "#d5d9a3", "#6cd2d9", "#3a29a6", "#592d3e", "#b24700", "#526600", "#4d9499", "#4100f2", "#d9a3b8", "#662900", "#b6f23d", "#00ccff", "#1b0066", "#735662", "#331400", "#9fbf60", "#23778c", "#170d33", "#ff0044", "#d97736", "#74b32d", "#bff2ff", "#896cd9", "#b20030", "#7f4620", "#57d900", "#566d73", "#7736d9", "#b22d50", "#ffb380", "#315916", "#0099e6", "#473366", "#8c4659", "#bf8660", "#1c330d", "#003c59", "#440080", "#cc001b", "#402d20", "#598040", "#23698c", "#754d99", "#990014", "#ffd9bf", "#4c5943", "#0d2633", "#655673", "#4c000a", "#ff8800", "#87a67c", "#609fbf", "#6f00a6", "#731d28", "#995200", "#0e6600", "#335566", "#2b0040", "#d96c7b", "#593000", "#90ff80", "#7c98a6", "#ca79f2", "#331b00", "#00ff00", "#262f33", "#b800e6", "#e59539", "#bfffbf", "#0088ff"] 97 | distances = np.genfromtxt("Master/data/tree_distances_matrix-train.npy") 98 | labels = np.load("Master/data/trees_clustered_vq-train.npy") 99 | 100 | points = d2c(distances) 101 | 102 | #assign labels to points 103 | for p in points: 104 | p.set_label(labels[p.index]) 105 | p.pprint() 106 | 107 | 108 | fig = plt.figure() 109 | ax = fig.add_subplot(111, projection='3d') 110 | 111 | plt.savefig("3d-tree-distance-view.png") 112 | 113 | for p in points: 114 | x, y, z = p.coordinates 115 | ax.scatter(x, y, z, c=colors183[p.label]) 116 | 117 | ax.set_xlabel('X') 118 | ax.set_ylabel('Y') 119 | ax.set_zlabel('Z') 120 | 121 | ax.set_title('Trees distance view') 122 | 123 | plt.show() -------------------------------------------------------------------------------- /HoVW/views/visualize_node_spatial_distribution.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Prograf-UFF/HoVW/4cb3ee59f9a91da877da83504cb4f8a61d1f7951/HoVW/views/visualize_node_spatial_distribution.py -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Hierarchy-of-Visual-Words: a Learning-based Approach for Trademark Image Retrieval 2 | The Hierarchy-of-Visual-Words (HoVW) is a trademark image retrieval method that decomposes images into simpler geometric shapes and defines a descriptor for trademark image representation by encoding the hierarchical arrangement of component shapes. The proposed hierarchical organization of visual data stores each component shape as a visual word. It is capable of representing the geometry of individual elements and the topology of the trademark image, making the descriptor robust against linear as well as to some level of nonlinear transformation. 3 | 4 | --- 5 | ### Check out our paper at [arXiv](https://arxiv.org/abs/1908.02786). 6 | 7 | | |:trophy: [Best Undergraduate Work Award]()
:trophy: [Best Computer Vision/Image Processing/Pattern Recognition Main Track Paper Award]()
at the [32nd Conference on Graphics, Patterns and Images (SIBGRAPI) 2019](http://www.mat.puc-rio.br/sibgrapi2019/) 8 | |:-:|:-| 9 | 10 | ## Cite 11 | 12 | ``` 13 | @inproceedings{lourenco2019, 14 | title = {{Hierarchy-of-Visual-Words: a Learning-based Approach for Trademark Image Retrieval}}, 15 | author = {Louren\c{c}o, V\'{i}tor N. and Silva, Gabriela G. and Fernandes, Leandro A. F.}, 16 | booktitle = {Proceedings of the 32nd Conference on Graphics, Patterns and Images (SIBGRAPI)}, 17 | year={2019}, 18 | } 19 | ``` 20 | 21 | ## Run 22 | To evaluate the HoVW framework follow the `HoVW/pipeline.sh` (Linux or MacOS) or `HoVW/pipeline.sh` (Windows). 23 | 24 | ## Licence 25 | All code is released under the [GNU General Public License](https://www.gnu.org/licenses/), version 3, or (at your option) any later version. 26 | -------------------------------------------------------------------------------- /wheels/mahotas-1.4.4-cp36-cp36m-win_amd64.whl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Prograf-UFF/HoVW/4cb3ee59f9a91da877da83504cb4f8a61d1f7951/wheels/mahotas-1.4.4-cp36-cp36m-win_amd64.whl --------------------------------------------------------------------------------