def __init__(self, doHSVhist=False): # store the number of points and radius #self.image = image self.doHSVhist = doHSVhist # initialize the local binary pattern descriptor self.desc = LocalBinaryPatterns(24, 8)
def get_LBP_Features(trainingPath, testingPath, p, r): from localbinarypatterns import LocalBinaryPatterns from sklearn.utils import shuffle # initialize the local binary patterns descriptor along with the data and label lists desc = LocalBinaryPatterns(p, r) data = [] labels = [] test_data = [] test_labels = [] start_time = time.time() # loop over the training images for imagePath in paths.list_files(trainingPath, validExts=(".png",".ppm")): # load the image, convert it to grayscale, and describe it image = cv2.imread(imagePath) gray = np.matrix(cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)) resized_image = cv2.resize(gray, (32, 32)) hist = desc.describe(resized_image) hist = hist / max(hist) # extract the label from the image path, then update the # label and data lists labels.append(imagePath.split("/")[-2]) data.append(hist) # loop over the testing images for imagePath in paths.list_files(testingPath, validExts=(".png",".ppm")): # load the image, convert it to grayscale, describe it, and classify it image = cv2.imread(imagePath) gray = np.matrix(cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)) resized_image = cv2.resize(gray, (32, 32)) hist = desc.describe(resized_image) hist = hist / max(hist) # extract the label from the image path, then update the # label and data lists test_labels.append(imagePath.split("/")[-2]) test_data.append(hist) feature_extraction_runtime = (time.time() - start_time) data = np.array(data) labels = np.array(labels) test_data = np.array(test_data) test_labels = np.array(test_labels) data, labels = shuffle(data,labels) print "[INFO] LBP Features are ready!" print "Total image:", len(data) + len(test_data) print "Feature extraction runtime:", feature_extraction_runtime print "Average for one image:", feature_extraction_runtime / (len(data) + len(test_data)) return (data, labels, test_data, test_labels)
def lbp_for_one_image(faces, image): if len(faces) == 0: print "No faces detected." return elif len(faces) > 1: print "Sorry, more than one facial expression is not supported now." return else: x, y, w, h = faces[0] img = image[y: y+h, x: x + w] # face part gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) desc = LocalBinaryPatterns(8, 1) desc.describe(gray, 2)
def __init__(self): # self.cam = cv2.VideoCapture(0) # self.cam.set(3, 320) # self.cam.set(4, 240) self.cam = WebcamVideoStream(src=0, resolution=(640, 480)).start() self.fps = FPS().start() ret, self.frame = self.cam.read() self.conf = { 'ColorFrameNum': 7, 'LBPFrameNum': 7, 'MaxFrameDiffClr': 15, 'MaxLBPFrameUpdate': 30, 'L_Weight': 0.3, 'A_Weight': 0.7, 'B_Weight': 0.7 } self.ColorCheck = AdaptiveThreshold(teta=3, max_lost_cnt=1) self.LBPCheck = AdaptiveThreshold(teta=2, max_lost_cnt=1) self.ColorDistance = LABDistance() self.LBPDistance = LocalBinaryPatterns( numPoints=8, radius=2, update_prev_hist=self.conf['MaxLBPFrameUpdate']) self.isLost = False self.isLBPLost = False self.height, self.width = self.frame.shape[:2] self.kernel_e = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)) self.kernel_d = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (7, 7)) self.kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)) cv2.namedWindow('camshift') self.obj_select = RectSelector('camshift', self.onmouse) self.LAB_CHANNELS = ( (24, [0, 256], "light"), # L (24, [0, 256], "a"), # a (24, [0, 256], "b") # b ) self.show_backproj = False self.track_window = None self.histLAB = [] self.track_box = None
def ExtractFeatures(image): """ Extract Features. -> Features Extracted: * LBP * Bfx_Basicint * Haralick * free Threshold Adjacency Statistics * Zernike Moments * HOG """ gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) #LBP Features desc = LocalBinaryPatterns(12, 4) lbp_hist = desc.describe(gray_image) lbp_hist = lbp_hist.reshape(1, len(lbp_hist)) #Bfx_Basicint R, _, _ = Bim_segbalu(gray_image) options = {'show': True, 'mask': 5} basicint, Xn = Bfx_basicint(gray_image, R, options) #Haralick features haralick = mahotas.features.haralick(gray_image).mean(0) haralick = haralick.reshape(1, len(haralick)) #parameter free Threshold Adjacency Statistics pftas = mahotas.features.pftas(gray_image) pftas = pftas.reshape(1, len(pftas)) #Zernike Moments zernike = mahotas.features.zernike_moments(gray_image, radius=2) zernike = zernike.reshape(1, len(zernike)) #HOG [Fix Dimentionality] HOG = hog(gray_image, orientations=8, pixels_per_cell=(16, 16), cells_per_block=(1, 1), visualise=False) HOG = HOG.reshape(1, len(HOG)) #Join Features features = np.concatenate( (lbp_hist, basicint, haralick, pftas, zernike, HOG), axis=1) return features
from localbinarypatterns import LocalBinaryPatterns from imutils import paths import cv2 import pandas as pd import numpy as np from skimage import feature import matplotlib.pyplot as plt db = 'yale' data_training = 'db/%s' % db P = 8 # number of points R = 8 # radius dataset = [file for file in paths.list_images(data_training)] desc = LocalBinaryPatterns(8, 8) gbr = paths.list_images(data_training) nama_gbr = gbr.__next__() print(nama_gbr) image = cv2.imread(nama_gbr) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) lbp = feature.local_binary_pattern(gray, P, R, method='uniform') hist = np.histogram(lbp.ravel(), bins=range(0, P + 3)) h = hist[0].astype('float') h /= (h.sum()) print(h, h.sum()) plt.bar(np.array(range(0, P + 2)), h) plt.xticks(np.array(range(0, P + 2))) plt.ylabel('Percentage') plt.show()
class App(object): def __init__(self): # self.cam = cv2.VideoCapture(0) # self.cam.set(3, 320) # self.cam.set(4, 240) self.cam = WebcamVideoStream(src=0, resolution=(640, 480)).start() self.fps = FPS().start() ret, self.frame = self.cam.read() self.conf = { 'ColorFrameNum': 7, 'LBPFrameNum': 7, 'MaxFrameDiffClr': 15, 'MaxLBPFrameUpdate': 30, 'L_Weight': 0.3, 'A_Weight': 0.7, 'B_Weight': 0.7 } self.ColorCheck = AdaptiveThreshold(teta=3, max_lost_cnt=1) self.LBPCheck = AdaptiveThreshold(teta=2, max_lost_cnt=1) self.ColorDistance = LABDistance() self.LBPDistance = LocalBinaryPatterns( numPoints=8, radius=2, update_prev_hist=self.conf['MaxLBPFrameUpdate']) self.isLost = False self.isLBPLost = False self.height, self.width = self.frame.shape[:2] self.kernel_e = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)) self.kernel_d = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (7, 7)) self.kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)) cv2.namedWindow('camshift') self.obj_select = RectSelector('camshift', self.onmouse) self.LAB_CHANNELS = ( (24, [0, 256], "light"), # L (24, [0, 256], "a"), # a (24, [0, 256], "b") # b ) self.show_backproj = False self.track_window = None self.histLAB = [] self.track_box = None def onmouse(self, rect): xmin, ymin, xmax, ymax = rect labRoi = self.lab[ymin:ymax, xmin:xmax] bgrRoi = self.frame[ymin:ymax, xmin:xmax] self.calcLABhist(labRoi) self.ColorDistance.init(bgrRoi) self.track_window = (xmin, ymin, xmax - xmin, ymax - ymin) # self.init_suspend(labRoi) self.isLost = False self.isLBPLost = False self.fps.reset() def calcLABhist(self, labRoi): self.histLAB = [] for channel, param in enumerate(self.LAB_CHANNELS): # Init LAB histogram hist = cv2.calcHist([labRoi], [channel], None, [param[0]], param[1]) hist = cv2.normalize(hist, hist, 0, 255, cv2.NORM_MINMAX) self.histLAB.append(hist) # Show hist of each channel separately # self.show_hist(hist, param[2]) def calcBackProjection(self): ch_prob = [] ch_back_proj_prob = [] for channel, param in enumerate(self.LAB_CHANNELS): prob = cv2.calcBackProject([self.lab], [channel], self.histLAB[channel], param[1], 1) cv2.imshow('Back projection ' + str(param[2]), prob) ret, prob = cv2.threshold(prob, 70, 255, cv2.THRESH_BINARY) cv2.imshow('Back projection thresh ' + str(param[2]), prob) # prob = cv2.morphologyEx(prob, cv2.MORPH_ERODE, self.kernel_e, iterations=1) # prob = cv2.morphologyEx(prob, cv2.MORPH_DILATE, self.kernel, iterations=1) prov = cv2.morphologyEx(prob, cv2.MORPH_CLOSE, self.kernel_e, iterations=2) ch_prob.append(prob) ch_back_proj_prob.append( cv2.addWeighted(ch_prob[0], self.conf['L_Weight'], ch_prob[1], self.conf['A_Weight'], 0)) ch_back_proj_prob.append( cv2.addWeighted(ch_prob[0], self.conf['L_Weight'], ch_prob[2], self.conf['B_Weight'], 0)) back_proj_prob = cv2.bitwise_and(ch_back_proj_prob[0], ch_back_proj_prob[1]) ret, back_proj_prob = cv2.threshold(back_proj_prob, 150, 255, cv2.THRESH_BINARY) back_proj_prob = cv2.morphologyEx(back_proj_prob, cv2.MORPH_ERODE, self.kernel_e, iterations=1) back_proj_prob = cv2.morphologyEx(back_proj_prob, cv2.MORPH_DILATE, self.kernel_e, iterations=2) return back_proj_prob @staticmethod def show_hist(hist, channel='None'): bin_count = hist.shape[0] bin_w = 24 img = np.zeros((256, bin_count * bin_w, 3), np.uint8) for i in range(bin_count): h = int(hist[i]) if str(channel) == 'light': cv2.rectangle(img, (i * bin_w + 2, 255), ((i + 1) * bin_w - 2, 255 - h), (int(255.0 * i / bin_count), 255, 255), -1) elif str(channel) == 'a': cv2.rectangle(img, (i * bin_w + 2, 255), ((i + 1) * bin_w - 2, 255 - h), (255, int(255.0 * i / bin_count), 255), -1) elif str(channel) == 'b': cv2.rectangle(img, (i * bin_w + 2, 255), ((i + 1) * bin_w - 2, 255 - h), (255, 255, int(255.0 * i / bin_count)), -1) else: cv2.rectangle(img, (i * bin_w + 2, 255), ((i + 1) * bin_w - 2, 255 - h), (255, 255, 255), -1) img = cv2.cvtColor(img, cv2.COLOR_LAB2BGR) cv2.imshow('hist ' + str(channel), img) def camshift_algorithm(self): prob = self.calcBackProjection() term_crit = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1) self.track_box, self.track_window = cv2.CamShift( prob, self.track_window, term_crit) if self.show_backproj: cv2.imshow("Back Projection", prob[..., np.newaxis]) else: cv2.destroyWindow("Back Projection") def run(self): scaling_factor = 0.5 last_frame_number = 0 while True: if not self.obj_select.dragging: ret, self.frame = self.cam.read() self.frame = cv2.resize(self.frame, None, fx=scaling_factor, fy=scaling_factor, interpolation=cv2.INTER_AREA) self.lab = cv2.cvtColor(self.frame, cv2.COLOR_BGR2LAB) # self.lab = cv2.GaussianBlur(self.lab, (3,3), 0) kernel = np.ones((5, 5), np.float32) / 25 self.lab = cv2.filter2D(self.lab, -1, kernel) self.gray = cv2.cvtColor(self.frame, cv2.COLOR_BGR2GRAY) if ret: vis = self.frame.copy() track_window_condition = ((self.track_window) and (self.track_window[2] > 0) and (self.track_window[3] > 0)) target_lost = self.isLost and self.isLBPLost # Main proccess flow if track_window_condition: if not target_lost: # Apply CamShift algorithm and get new track_box self.camshift_algorithm() if self.fps.NumFrame % self.conf[ 'ColorFrameNum'] == 0 and not self.isLost: color_distance = self.ColorDistance.update( self.frame, self.track_box) self.isLost = self.ColorCheck.target_lost( color_distance) print("[INFO] Color track is lost: '{}'\n".format( self.isLost)) if self.isLost: last_frame_number = self.fps.NumFrame if self.fps.NumFrame % self.conf[ 'LBPFrameNum'] == 0 and not self.isLBPLost: LBP_distance = self.LBPDistance.update( self.gray, self.track_window) self.isLBPLost = self.LBPCheck.target_lost( LBP_distance) print("[INFO] LBP track is lost: '{}'\n".format( self.isLBPLost)) if self.isLBPLost: last_frame_number = self.fps.NumFrame if self.fps.NumFrame - last_frame_number >= self.conf[ 'MaxLBPFrameUpdate']: self.isLBPLost = False self.isLost = False try: cv2.ellipse(vis, self.track_box, (0, 0, 255), 2) pts = cv2.boxPoints(self.track_box) pts = np.int0(pts) cv2.polylines(vis, [pts], True, 255, 2) except: print(self.track_box) else: cv2.putText(vis, 'Target Lost', (10, 230), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 1, cv2.LINE_AA) # print("[INFO] Starting recovery proccess") elif not track_window_condition: cv2.putText(vis, 'Mark area of the object', (10, 230), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1, cv2.LINE_AA) # frame processing throughput rate fps = self.fps.approx_compute() cv2.putText(vis, 'FPS {:.3f}'.format(fps), (10, 10), cv2.FONT_HERSHEY_SIMPLEX, 0.3, (255, 255, 255), 1, cv2.LINE_AA) self.obj_select.draw(vis) cv2.imshow('camshift', vis) ch = 0xFF & cv2.waitKey(1) if ch == 27: break if ch == ord('b'): self.show_backproj = not self.show_backproj cv2.destroyAllWindows()
from sklearn.svm import LinearSVC from localbinarypatterns import LocalBinaryPatterns ap = argparse.ArgumentParser() ap.add_argument("-t", "--treinamento", required=True, help="path to the training images") ap.add_argument("-e", "--teste", required=True, help="path to the testing images") args = vars(ap.parse_args()) #inicializa o descritor LBP com as listas dos dados e das classes desc = LocalBinaryPatterns(8, 4) data = [] labels = [] # para cada imagem no conjunto de treinamento i = 0 for imagePath in paths.list_images(args["treinamento"]): # carrega a imagem da pasta de treinamento, # converte em escala cinza image = cv2.imread(imagePath) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) hist = desc.describe(gray) #extrai a classe do caminho da imagem, no caso, olho aberto e fechado
import dlib data_set = [] labels_set = [] eye_coords_set = [] images_set = [] list_of_eye_coords = [] list_of_hists = [] list_of_images = [] #initialize the classifier model = LinearSVC(C=100.0, random_state=42) #initialize the descriptor model desc = LocalBinaryPatterns(24, 8) #var_initial is 0 only when training var_initial = 1 # initialize haar cascade eye and face detector face_cascade = cv2.CascadeClassifier( 'D:/Thesis/haarcascade_frontalface_default.xml') eye_cascade = cv2.CascadeClassifier('D:/Thesis/haarcascade_eye.xml') # initialize dlib's face detector (HOG-based) and then create # the facial landmark predictor detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor( 'D:/Thesis/shape_predictor_68_face_landmarks.dat')
import pickle import cv2 # --------------------------------------------------- # PROJEKT Z SNR - Zadanie 1. w 3 aktach # by Krzysztof Krupiński 2018 # --------------------------------------------------- # AKT 1: Ekstrakcja cech obrazów za pomocą deskryptora # Ścieżka główna do folderu z liśćmi trainingMainPath = "/home/krzysztof/Dokumenty/SNR_grupa1/Folio Leaf Dataset/Folio" # paths - wszystkie (pełne) ścieżki do zdjęć liści paths = metody.getListOfFiles( trainingMainPath) # Lista wszystkich plików w folderze desc = LocalBinaryPatterns( 16, 2 ) # Obiekt klasy LBP - deksryptor LBP 8 - liczba próbek w sąsiedztwie, 2 - promień sąsiedztwa data = [] labels = [] licznik = 0 # Do wyświetlania postępou ekstracji allFiles = len(paths) print("Ekstrakcja cech\n") for imagePath in paths: image = cv2.imread(imagePath) # Wczytanie obrazu gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Skala szarości hist = desc.describe(gray) # LBP wykonane na obrazie - zwraca histogram labels.append(imagePath.split("/")[-2]) # Tylko nazwa kwiatu data.append(hist)
db = 'jaffe' data_training = 'db/%s' % db points = range(8, 70, 4) radius = range(4, 21) par = list(itertools.product(points, radius)) hasil = [] dataset = [file for file in paths.list_images(data_training)] for p in par: print("##### points: %d, radius:%d #####" % p) # inicializar o descritor de padrões binários locais desc = LocalBinaryPatterns(p[0], p[1]) data = [] labels = [] # loop nas imagens de treinamento print(data_training, len(dataset)) for imagePath in paths.list_images(data_training): # carregue a imagem, convertendo em tons de cinza # print("test:", imagePath) image = cv2.imread(imagePath) try: gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) except: print('ERROR di:', imagePath) hist = desc.describe(gray) # extraia o rótulo do caminho da imagem e atualiza o
# otherwise, the height is None else: # calculate the ratio of the width and construct the # dimensions r = width / float(w) dim = (width, int(h * r)) # resize the image resized = cv2.resize(image, dim, interpolation = inter) # return the resized image return resized # initialize the local binary patterns descriptor along with # the data and label lists desc = LocalBinaryPatterns(24, 8) data_real = [] labels_real = [] data_fake = [] labels_fake = [] detector = cv2.CascadeClassifier("face_detector/haarcascade_frontalface_default.xml") real_id = 0 # loop over the real images for imagePath in paths.list_images("frames_reais/"): real_id += 1 # load the image, convert it to grayscale, and describe it image = cv2.imread(imagePath)
from sklearn.svm import LinearSVC from imutils import paths import argparse import cv2 # construct the argument parse and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-t", "--training", required=True, help="path to the training images") ap.add_argument("-e", "--testing", required=True, help="path to the tesitng images") args = vars(ap.parse_args()) # initialize the local binary patterns descriptor along with # the data and label lists desc = LocalBinaryPatterns(24, 8) data = [] labels = [] # loop over the training images for imagePath in paths.list_images(args["training"]): # load the image, convert it to grayscale, and describe it image = cv2.imread(imagePath) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) hist = desc.describe(gray) # extract the label from the image path, then update the # label and data lists labels.append(imagePath.split("/")[-2]) data.append(hist)
from balu.ImageProcessing import Bim_segbalu from Bfx_basicint import Bfx_basicint from skimage.feature import hog import numpy as np from mahotas.features import surf #Load Image filename = 'Cl_1_2_AB.png' image = cv2.imread(filename) image = image[0:32, 0:32] #convert image to grayscale gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) #LBP Features desc = LocalBinaryPatterns(12, 4) lbp_hist = desc.describe(gray_image) lbp_hist = lbp_hist.reshape(1, len(lbp_hist)) #Bfx_Basicint R, _, _ = Bim_segbalu(gray_image) options = {'show': True, 'mask': 5} basicint, Xn = Bfx_basicint(gray_image, R, options) #Haralick features haralick = mahotas.features.haralick(gray_image).mean(0) haralick = haralick.reshape(1, len(haralick)) #parameter free Threshold Adjacency Statistics pftas = mahotas.features.pftas(gray_image) pftas = pftas.reshape(1, len(pftas))
def main(): # construct the argument parse and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-t", "--training", required=True, help="path to the training images") ap.add_argument("-e", "--testing", required=True, help="path to the tesitng images") args = vars(ap.parse_args()) # initialize the local binary patterns descriptor along with the data and label lists desc = LocalBinaryPatterns(24, 8) data = [] labels = [] # initialize the actual and predicted vectors y_act = [] y_pred = [] # loop over the training images for imagePath in paths.list_files(args["training"], validExts=(".png",".ppm")): # load the image, convert it to grayscale, and describe it image = cv2.imread(imagePath) gray = np.matrix(cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)) resized_image = cv2.resize(gray, (32, 32)) hist = desc.describe(resized_image) hist = hist / max(hist) # extract the label from the image path, then update the # label and data lists labels.append(imagePath.split("/")[-2]) data.append(hist) # shuffle datas and labels before trained a model X = np.array(data) y = np.array(labels) #X, y = shuffle(X,y) # find best parameters before trained a model best_parameters = svc_param_selection(X,y) best_gamma = best_parameters.get("gamma") best_kernel = best_parameters.get("kernel") print str(best_gamma), best_kernel # raw_input() # train a Linear SVM on the data model = svm.NuSVC(nu = 0.01,kernel=best_kernel, gamma=best_gamma) model.fit(X, y) # loop over the testing images for imagePath in paths.list_files(args["testing"], validExts=(".png",".ppm")): # load the image, convert it to grayscale, describe it, and classify it image = cv2.imread(imagePath) gray = np.matrix(cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)) resized_image = cv2.resize(gray, (32, 32)) hist = desc.describe(resized_image) hist = hist / max(hist) # prediction for each test image prediction = model.predict([hist])[0] # prepare data to append into lists inpt = str(imagePath.split("/")[-2]) outpt = str(prediction) y_act.append(int(inpt)) y_pred.append(int(outpt)) # calculate match_count and accuracy to sho test result match_count = sum([int(y==y_) for y, y_ in zip(y_act, y_pred)]) accuracy = float(match_count) / float(len(y_act)) print "\nAccuracy:" + str(accuracy) + "\n"
def get_all_samples(path, p=24, r=8): # initialize the local binary patterns descriptor along with the data and label lists desc = LocalBinaryPatterns(p, r) data = [] labels = [] classSamplesList = [] samples_amount_of_classes = [] currentClass = None flag = False class_list = os.listdir(path) class_list.remove('.DS_Store') class_list.remove('Readme.txt') counter = len(class_list) lastClassPath = '' # loop over the training images for imagePath in paths.list_files(path, validExts=(".png", ".ppm")): if (flag == False): currentClass = imagePath.split("/")[-2] labels.append(currentClass) counter -= 1 flag = True else: if imagePath.split("/")[-2] != currentClass: currentClass = imagePath.split("/")[-2] classSamplesList.append(np.transpose(np.array(data))) samples_amount_of_classes.append(len(data)) data = [] labels.append(currentClass) counter -= 1 if counter == 0: lastClassPath = imagePath break # load the image, convert it to grayscale, and describe it image = cv2.imread(imagePath) gray = np.matrix(cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)) resized_image = cv2.resize(gray, (32, 32)) hist = desc.describe(resized_image) hist = hist / max(hist) # extract the label from the image path data.append(hist) data = [] head, _ = os.path.split(lastClassPath) for imagePath in paths.list_files(head, validExts=(".png", ".ppm")): # load the image, convert it to grayscale, and describe it image = cv2.imread(imagePath) gray = np.matrix(cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)) resized_image = cv2.resize(gray, (32, 32)) hist = desc.describe(resized_image) hist = hist / max(hist) # extract the label from the image path data.append(hist) classSamplesList.append(np.transpose(np.array(data))) samples_amount_of_classes.append(len(data)) all_samples = tuple(classSamplesList) all_samples = np.concatenate(all_samples, axis=1) """ for i, val in enumerate(samples_amount_of_classes): print i, val raw_input() """ return all_samples, labels, samples_amount_of_classes
#from imutils import paths #import paths #imutils module #import argparse import cv2 import os import glob import numpy as np trainingPath = "/Users/fegvilela/Documents/Unb/TCC/baseDados/training1/" testingPath = "/Users/fegvilela/Documents/Unb/TCC/baseDados/testing1/" pngFiles1 = convertImage(trainingPath) # initialize the local binary patterns descriptor along with # the data and label lists desc = LocalBinaryPatterns(30, 5) # LBP 30 pontos e raio 9 = melhor acurácia data = [] labels = [] trueClass = [] predClass = [] # loop over the training images for file in pngFiles1: # load the image, convert it to grayscale, and describe it image = cv2.imread(file) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # call from made lbp class/module = aplica LBP em imegem e retorna o histograma hist = desc.describe(gray) # extract the label from the image path (), then update the # label and data lists file = file.split(".")[0]
# construct the argument parse and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-t", "--training", required=True, help="path to the training images") ap.add_argument("-e", "--testing", required=True, help="path to the tesitng images") args = vars(ap.parse_args()) # initialize the local binary patterns descriptor along with # the data and label lists desc = LocalBinaryPatterns(24, 8) data = [] labels = [] # loop over the training images for imagePath in paths.list_images(args["training"]): # load the image, convert it to grayscale, and describe it image = cv2.imread(imagePath) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) hist = desc.describe(gray) # extract the label from the image path, then update the # label and data lists labels.append(imagePath.split(".")[-2]) # labels.append(os.path.split(os.path.dirname(imagePath))[-1]) data.append(hist)
class CloudFeatureHistogram: def __init__(self, doHSVhist=False): # store the number of points and radius #self.image = image self.doHSVhist = doHSVhist # initialize the local binary pattern descriptor self.desc = LocalBinaryPatterns(24, 8) def get_feature_histogram(self, image): # load the image, convert it to grayscale, describe it, # and classify it # TOO SMOOTH #filtered = cv2.bilateralFilter(image, 7, 75, 75) # Median blur : remove large outliers #filtered = cv2.medianBlur(image, 5) DON'T DO THIS EITHER!!! gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) #gray = cv2.cvtColor(filtered, cv2.COLOR_BGR2GRAY) # Do a histogram equalization to bring out contrast # create a CLAHE object (Arguments are optional). # is this slow???? - NO, SOMETHING ELSE IS MAKING SLIDING WINDOWS SLOW............... clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8)) claheGray = clahe.apply(gray) # show the new image # cv2.imshow('claheGray', claheGray) # cv2.waitKey(0) # cv2.destroyAllWindows() # local binary pattern histogram lbpHist = self.desc.describe(claheGray) logging.debug("lbpHist = %s", lbpHist) # if self.doHSVhist : # # # HSV histogram # # channels = [0, 1] because we need to process both H and S plane. # # bins = [180, 256] 180 for H plane and 256 for S plane. # # range = [0, 180, 0, 256] # # Hue value lies between 0 and 180 & Saturation lies between 0 and 256. # hsv = cv2.cvtColor(filtered, cv2.COLOR_BGR2HSV) # # # hsvHistTest = cv2.calcHist([hsv], [1], None, [256], [0, 255]) # # cv2.normalize(hsvHistTest, hsvHistTest, 0, 255, cv2.NORM_MINMAX) # #logging.debug("hsvHistTest = %s", hsvHistTest) # # # only look at the saturation. Saturation of white/gray < 0.15 * 255 = 38 # (hsvHist, _) = np.histogram(hsv[:,:,1].ravel(), # bins=np.arange(0, 255), # #bins=np.arange(0, 7), # range=(0, 255)) # # # normalize the histogram # eps = 1e-7 # hsvHist = hsvHist.astype("float") # hsvHist /= (hsvHist.sum() + eps) # # logging.debug("hsvHist.sum() = %s", hsvHist.sum()) # logging.debug("hsvHist = %s", hsvHist) # # # Now normalize hsvHist : # # normalize the histogram # # eps = 1e-7 # # hsvHist = hsvHist.astype("float") # # hsvHist /= (hsvHist.sum() + eps) # # #print "hsvHist = " + str(hsvHist) # #print "hsvHist = " + str(hsvHist.flatten) # # # if self.doHSVhist: # # Make a concatenated feature vector of color statistics and lbp # # texture features # # (horizontally stack the two numpy arrays) [1,2,3] [4,5,6] -> [1,2,3,4,5,6] # hist = np.hstack([lbpHist, hsvHist]) # # #logging.debug("hist = %s", hist ) # return hist return lbpHist