Advertisement
11eimilia11

muitaraiva

Feb 18th, 2019
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 12.85 KB | None | 0 0
  1. import pandas as pd
  2. from numpy import ndarray
  3. from sklearn import preprocessing
  4. from sklearn.neighbors import KNeighborsClassifier
  5. from scipy import stats
  6. from sklearn.naive_bayes import GaussianNB
  7. import statistics
  8. from sklearn.metrics import pairwise_distances_argmin_min
  9. import numpy as np
  10. from random import randint
  11. import matplotlib.pyplot as plt
  12. import cv2
  13. from sklearn.decomposition import PCA
  14. import glob
  15. from sklearn.metrics import pairwise_distances_argmin_min
  16. from sklearn.metrics import accuracy_score
  17. from operator import itemgetter
  18. import math
  19. import os
  20.  
  21. # Carregando fotos da pasta
  22. def loadFiles(path, array):
  23.  
  24.     for i in glob.glob(path):
  25.  
  26.         img = cv2.imread(i)
  27.         array.append(img)
  28.  
  29.     return array
  30.  
  31. # Função que faz o filtro cinza nas fotos
  32. def grayConversion(arrayphotos):
  33.  
  34.     size = len(arrayphotos)
  35.     for x in range (0,size):
  36.         arrayphotos[x] = cv2.cvtColor(arrayphotos[x], cv2.COLOR_BGR2GRAY)
  37.  
  38.     return arrayphotos
  39.  
  40. # Função que aplic o filtro blur nas fotos do array
  41. def blurConversion(arrayphotos ,val1, val2):
  42.  
  43.     for x in range(len(arrayphotos)):
  44.         arrayphotos[x] = cv2.GaussianBlur(arrayphotos[x],(val1,val1), val2)
  45.  
  46.     return arrayphotos
  47.  
  48. #Função que faz a binarização das fotos
  49. def binaryConversion(arrayphotos,threshold,val1):
  50.  
  51.     for x in range(len(arrayphotos)):
  52.         arrayphotos[x] = cv2.adaptiveThreshold(arrayphotos[x],threshold,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,val1,10)
  53.  
  54.     return arrayphotos
  55.  
  56. #Função que inverte as fotos binárias
  57. def invertConversion(arrayphotos):
  58.  
  59.     for x in range(len(arrayphotos)):
  60.         arrayphotos[x] = cv2.bitwise_not(arrayphotos[x])
  61.  
  62.     return arrayphotos
  63.  
  64.  
  65. # função de normalização dos dados usando o modelo de
  66. # normalização por reescala
  67.  
  68. def normalizar(dados):
  69.     x = dados.values
  70.     min_max_scaler = preprocessing.MinMaxScaler()
  71.     x_scaled = min_max_scaler.fit_transform(x)
  72.     dados_norm = pd.DataFrame(x_scaled)
  73.     return dados_norm
  74.  
  75.  
  76. def geneticlabels(dataframe,centers):
  77.     return pairwise_distances_argmin_min(dataframe,centers,metric='minkowski')
  78.  
  79. def find_clusters(X, n_clusters, rng, max_it):
  80.  
  81.     i = rng.permutation(X.shape[0])[:n_clusters]
  82.     centers = X[i]
  83.  
  84.     max_iterator = 0
  85.     distances = []
  86.     while True:
  87.  
  88.         labels,distance = pairwise_distances_argmin_min(X,centers,metric='minkowski')
  89.         distances.append(distance)
  90.  
  91.         new_centers = np.array([X[labels == i].mean(0)
  92.                                 for i in range(n_clusters)])
  93.  
  94.  
  95.         if np.all(centers == new_centers) or max_iterator > max_it:
  96.             break
  97.         centers = new_centers
  98.         max_iterator += 1
  99.  
  100.     return centers, labels, distances
  101.  
  102. def accuracy_majority_vote(base, predict_labels, real_labels, n_clusters):
  103.  
  104.     classes = real_labels.unique()
  105.  
  106.     majority = []
  107.     groups = []
  108.     k = 0
  109.     for i in range(n_clusters):
  110.         group = []
  111.         for a in range(len(base)):
  112.             if predict_labels[a] == i:
  113.                 group.append(real_labels[a])
  114.         groups.append(group)
  115.         majority.append(initialize_dic_majority(classes))
  116.         for real_label in group:
  117.             majority[k][real_label] += 1
  118.         k += 1
  119.  
  120.     label_groups = []
  121.     for m in majority:
  122.         label_groups.append(max(m.items(), key=itemgetter(1))[0])
  123.  
  124.     pred_labels = []
  125.     true_labels = []
  126.     for g in range(len(groups)):
  127.         pred_labels = pred_labels + ([label_groups[g]]*len(groups[g]))
  128.         true_labels = true_labels + [a for a in groups[g]]
  129.  
  130.     return accuracy_score(pred_labels, true_labels)
  131.  
  132.  
  133. def find_clustersGENETIC(X, n_clusters, max_it, array):
  134.  
  135.     centers = array
  136.  
  137.     max_iterator = 0
  138.     distances = []
  139.     while True:
  140.  
  141.         labels,distance = pairwise_distances_argmin_min(X,centers,metric='minkowski')
  142.         distances.append(distance)
  143.  
  144.         new_centers = np.array([X[labels == i].mean(0)
  145.                                 for i in range(n_clusters)])
  146.  
  147.  
  148.         if np.all(centers == new_centers) or max_iterator > max_it:
  149.             break
  150.         centers = new_centers
  151.         max_iterator += 1
  152.  
  153.     return centers, labels, distances
  154.  
  155.  
  156. def WCSSgenetic(x, population):
  157.  
  158.     arrayint = []
  159.     for a in x:
  160.         arrayint.append(int(a))
  161.  
  162.     print(arrayint)
  163.     soma = 0
  164.     for b in arrayint:
  165.         labels, distances = pairwise_distances_argmin_min(population[b],population, metric='minkowski')
  166.         for x in distances:
  167.             soma += x**2
  168.     return soma
  169.  
  170.  
  171. def generatepopulation(X,numberpopu, K, rng):
  172.  
  173.     population = []
  174.  
  175.     for x in range(numberpopu):
  176.         first = rng.permutation(X.shape[0])[:K]
  177.         print(first)
  178.         population.append(np.concatenate(X[first]))
  179.  
  180.     return population
  181.  
  182.  
  183. def find_clustersgenetic(X, n_clusters, max_it, array):
  184.  
  185.     centers = array
  186.  
  187.     max_iterator = 0
  188.     distances = []
  189.     while True:
  190.  
  191.         labels,distance = pairwise_distances_argmin_min(X,centers,metric='minkowski')
  192.         distances.append(distance)
  193.  
  194.         new_centers = np.array([X[labels == i].mean(0)
  195.                                 for i in range(n_clusters)])
  196.  
  197.         if np.all(centers == new_centers) or max_iterator > max_it:
  198.             break
  199.         centers = new_centers
  200.         max_iterator += 1
  201.  
  202.     return centers, labels, distances
  203.  
  204.  
  205. #FUNÇÃO DE NORMALIZAÇÃO
  206.  
  207. def imgtoarray(arrayphotos):
  208.  
  209.     size = len(arrayphotos)
  210.     for x in range (0,size):
  211.         arrayphotos[x] = np.array(arrayphotos[x] , dtype=float)
  212.  
  213.     return arrayphotos
  214.  
  215. def gethumoments(arrayphotos):
  216.  
  217.     for x in range(len(arrayphotos)):
  218.  
  219.         arrayphotos[x] = cv2.HuMoments(cv2.moments(arrayphotos[x]), True).flatten()
  220.  
  221.     return arrayphotos
  222.  
  223. def WCSS2(distance):
  224.     soma = 0
  225.     for x in distance:
  226.         soma += x ** 2
  227.  
  228.     return soma
  229.  
  230.  
  231. def initialize_dic_majority(classes):
  232.     majority = {}
  233.     for c in classes:
  234.         majority[c] = 0
  235.  
  236.     return majority
  237.  
  238.  
  239. def extratorCaracteristicas(arrayimgs):
  240.  
  241.     squarescarac = []
  242.  
  243.  
  244.     for x in arrayimgs:
  245.  
  246.         aux = []
  247.  
  248.         im2, countours, hierachy = cv2.findContours(x, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
  249.  
  250.         if len(countours) == 0:
  251.  
  252.             for b in range(0,45):
  253.  
  254.                 aux.append(0)
  255.  
  256.         elif len(countours) > 0:
  257.             peri = cv2.arcLength(countours[0], True)  # perimetro
  258.             aux.append(peri)
  259.  
  260.             aproxx = cv2.approxPolyDP(countours[0], 0.04 * peri, True)  # vertices
  261.             vertc = len(aproxx)
  262.             aux.append(vertc)
  263.  
  264.             area = cv2.contourArea(countours[0])  # area
  265.             aux.append(area)
  266.  
  267.             if peri > 0:
  268.                 compactness = (4 * math.pi * area) / (peri ** 2)  # compacidade
  269.                 aux.append(compactness)
  270.             elif peri == 0:
  271.                 aux.append(0)
  272.  
  273.             momentum = cv2.moments(x)
  274.             momentum = list(dict.values(momentum))  # momentos
  275.             for i in momentum:
  276.                 aux.append(i)
  277.  
  278.             moments = cv2.HuMoments(momentum, True).flatten()  # Hu moments
  279.  
  280.             for i in moments:
  281.                 aux.append(i)
  282.  
  283.             histogram = get_histogram(aproxx)  # Frequencia de angulos
  284.  
  285.             for h in histogram:
  286.                 aux.append(h)
  287.  
  288.         squarescarac.append(aux)
  289.  
  290.  
  291.     return squarescarac
  292.  
  293. def niveisCinza(image):
  294.  
  295.     gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
  296.  
  297.     return gray
  298.  
  299.  
  300. def filtroGaussiano(image):
  301.  
  302.     gaussianb = cv2.GaussianBlur(image,(5,5),0)
  303.  
  304.     return gaussianb
  305.  
  306. def turnToBinary(image):
  307.  
  308.     binary = cv2.adaptiveThreshold(image,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,31,10)
  309.  
  310.     return binary
  311.  
  312. def inverterCores(image):
  313.  
  314.     invert = cv2.bitwise_not(image)
  315.  
  316.     return invert
  317.  
  318. def resizeImages(images,width,height):
  319.  
  320.     i = len(images)
  321.     for x in range(0,i):
  322.  
  323.         images[x] = cv2.resize(images[x],(width,height))
  324.  
  325.     return images
  326.  
  327.  
  328. def angle3pt(a, b, c):
  329.     """Counterclockwise angle in degrees by turning from a to c around b
  330.        Returns a float between 0.0 and 360.0"""
  331.     ang = math.degrees(
  332.         math.atan2(c[1] - b[1], c[0] - b[0]) - math.atan2(a[1] - b[1], a[0] - b[0]))
  333.  
  334.     return ang + 360 if ang < 0 else ang
  335.  
  336. def get_vertices(imagem):
  337.  
  338.     im2, countours, hierachy = cv2.findContours(imagem, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
  339.  
  340.     peri = cv2.arcLength(countours[0], True)  # perimetro
  341.  
  342.     aproxx = cv2.approxPolyDP(countours[0], 0.04 * peri, True)  # vertices
  343.  
  344.     return aproxx
  345.  
  346. def get_angle(p0, p1, p2):
  347.  
  348.     v0 = np.array(p0) - np.array(p1)
  349.     v1 = np.array(p2) - np.array(p1)
  350.  
  351.     angle = np.math.atan2(np.linalg.det([v0, v1]), np.dot(v0, v1))
  352.     return np.degrees(angle)
  353.  
  354.  
  355. def get_histogram(aproxx):
  356.     zero = []
  357.     zero.append(0)
  358.     zero.append(0)
  359.     zero.append(0)
  360.     zero.append(0)
  361.     zero.append(0)
  362.     zero.append(0)
  363.     zero.append(0)
  364.     zero.append(0)
  365.     zero.append(0)
  366.     zero.append(0)
  367.     zero.append(0)
  368.     #transformando em um array bidimensional
  369.     retornopollyDP = np.reshape(aproxx, (aproxx.shape[0], (aproxx.shape[1] * aproxx.shape[2])))
  370.  
  371.     #checando se não é uma linha
  372.     if (len(retornopollyDP) < 3):
  373.  
  374.         return zero
  375.  
  376.     arraysdeangulo = []
  377.  
  378.     for x in range(len(retornopollyDP)):
  379.         # caso especial : quando a primeira posição do array for o angulo central
  380.         if x == 0:
  381.  
  382.             bla3 = get_angle(retornopollyDP[x + 1], retornopollyDP[x], retornopollyDP[len(retornopollyDP) - 1])
  383.             arraysdeangulo.append(math.fabs(bla3))
  384.  
  385.         # caso especial : quando a última posição do array for o ângulo central
  386.         if x == len(retornopollyDP) - 1:
  387.  
  388.             bla4 = get_angle(retornopollyDP[x - 1], retornopollyDP[x], retornopollyDP[0])
  389.             arraysdeangulo.append(math.fabs(bla4))
  390.  
  391.         if x > 0 and x < len(retornopollyDP) - 1:
  392.  
  393.             bla5 = get_angle(retornopollyDP[x + 1], retornopollyDP[x], retornopollyDP[x - 1])
  394.             arraysdeangulo.append(math.fabs(bla5))
  395.  
  396.     hist, bins = np.histogram(arraysdeangulo, bins=[15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180])
  397.  
  398.     return hist
  399.  
  400.  
  401. # função que calcula os valores de média, moda , mediana e desvio padrão
  402. # para os vetores de acerto de um algoritmo, recebe como parâmetro o vetor
  403. # de acerto e o nome do algoritmo
  404.  
  405. def tendencia_central (nomeAlgoritmo, vetorAcerto, vetorTempo):
  406.     print('________________________________________________\n')
  407.     print(nomeAlgoritmo)
  408.     print('Tempo Média = ', np.mean(vetorTempo))
  409.     print('Tempo Desvio padrão = ', statistics.pstdev(vetorTempo))
  410.     print('Tempo Moda = ', stats.mode(vetorTempo, axis=None))
  411.     print('Tempo Mediana =', np.median(vetorTempo))
  412.     print('----------------------------------------------')
  413.     print('Acurácia Média = ', np.mean(vetorAcerto))
  414.     print('Acurácia Desvio padrão = ', statistics.pstdev(vetorAcerto))
  415.     print('Acurácia Moda = ', stats.mode(vetorAcerto, axis=None))
  416.     print('Acurácia Mediana = ', np.median(vetorAcerto))
  417.  
  418.     print('________________________________________________\n')
  419.  
  420. # funcão que seleciona num quantidade de imagens aleatoriamente
  421. # em um vetor e retorna um vetor auxiliar apenas com as imagens
  422. # selecionadas
  423.  
  424.  
  425. def seleciona_imagens (arrayImgs, num):
  426.     tamanho = len(arrayImgs)
  427.     selecionadas = []
  428.     nao_selecionadas = []
  429.     aux = []
  430.     var = 0
  431.  
  432.     for x in range(0, num):
  433.  
  434.         if x == 0:
  435.  
  436.             var = randint(0, tamanho)
  437.             aux.append(var)
  438.             selecionadas.append(arrayImgs[var])
  439.  
  440.         elif x > 0:
  441.  
  442.             var = randint(0, tamanho)
  443.  
  444.             while np.isin(var ,aux):
  445.  
  446.                 var = randint(0, tamanho)
  447.  
  448.             selecionadas.append(arrayImgs[var])
  449.             aux.append(var)
  450.  
  451.     for x in range(0, tamanho):
  452.         if np.isin(x,aux):
  453.             continue
  454.         else:
  455.             nao_selecionadas.append(arrayImgs[x])
  456.  
  457.     return selecionadas, nao_selecionadas
  458.  
  459.  
  460. def is_similar(image1, image2):
  461.  
  462.     retorno = image1.shape == image2.shape and not(np.bitwise_xor(image1,image2).any())
  463.  
  464.     return retorno
  465.  
  466.  
  467. def create_folder(path):
  468.     x = 0
  469.     try:
  470.         os.mkdir(path)
  471.     except OSError:
  472.        x = -1
  473.     else:
  474.         x = 1
  475.     return x
  476.  
  477.  
  478. def save_images(images, path):
  479.     cont = 0
  480.  
  481.     for i in images:
  482.         y = str(cont)
  483.         cv2.imwrite(path + y + '.jpg', i)
  484.         cont += 1
  485.  
  486.     return 0
  487.  
  488. # checa se o elemento escolhido já existe no array aux para
  489. # evitar elementos duplicados
  490.  
  491. # var = randint(0, tamanho)
  492. #
  493. # for i in range(0, len(aux)):
  494. #     if is_similar(arrayImgs[var], aux[i]):
  495. #         duplicate = 1
  496. #
  497. # while duplicate == 1:
  498.  
  499.  
  500. def delete_folder (path):
  501.     x = 0
  502.     try:
  503.         os.rmdir(path)
  504.     except OSError:
  505.         x = -1
  506.     else:
  507.         x = 1
  508.     return x
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement