def extractimage(imageParam): data = [] # ap = argparse.ArgumentParser() # ap.add_argument("-t", "--training", required=True, # help="path to the training images") # args = vars(ap.parse_args()) face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml') image_scale = 1 # for imagePath in paths.list_images(args["training"]): img = cv2.imdecode(numpy.fromstring(imageParam.read(), numpy.uint8), cv2.IMREAD_UNCHANGED) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.3, 5) for (x, y, w, h) in faces: cv2.rectangle(gray, (x, y), (x + w, y + h), (255, 0, 0), 2) roi_gray = gray[y:y + h, x:x + w] roi_color = img[y:y + h, x:x + w] desc = LocalBinaryPatterns(24, 8) if faces == (): return False else: hist = desc.describe(roi_gray) data.append(hist) return data # print(hist) # for x in hist: # with open('data.txt', 'a') as f: # f.write(str(x)+',') # with open('dataset.csv','wb') as file: # for line in data: # file.write(line)
stepSize=stepSize, windowSize=(winW, winH)): # if the window does not meet our desired window size, ignore it if window.shape[0] != winH or window.shape[1] != winW: continue # THIS IS WHERE YOU WOULD PROCESS YOUR WINDOW, SUCH AS APPLYING A # MACHINE LEARNING CLASSIFIER TO CLASSIFY THE CONTENTS OF THE # WINDOW # WORKS WITH THIS...........BUT NOT THE cloudFeature call ***************** gray = cv2.cvtColor(window, cv2.COLOR_BGR2GRAY) clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8)) claheGray = clahe.apply(gray) hist = desc.describe(claheGray) # set up histogram #hist = cloudFeature.get_feature_histogram(image) prediction = model.predict([hist])[0] # draw the window clone = image.copy() cv2.rectangle(clone, (x, y), (x + winW, y + winH), (0, 255, 0), 2) # display the image and the prediction cv2.putText(clone, prediction, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 255), 3) cv2.imshow("Window", clone)
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) # train a Linear SVM on the data model = LinearSVC(C=100.0, random_state=42) model.fit(data, labels) # loop over the testing images for imagePath in paths.list_images(args["testing"]): # load the image, convert it to grayscale, describe it, # and classify it image = cv2.imread(imagePath)
import cv2 data = [] ap = argparse.ArgumentParser() ap.add_argument("-t", "--training", required=True, help="path to the training images") args = vars(ap.parse_args()) face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml') image_scale = 1 for imagePath in paths.list_images(args["training"]): img = cv2.imread(imagePath) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.3, 5) for (x, y, w, h) in faces: cv2.rectangle(gray, (x, y), (x + w, y + h), (255, 0, 0), 2) roi_gray = gray[y:y + h, x:x + w] roi_color = img[y:y + h, x:x + w] rezise_img = cv2.resize(roi_gray, (300, 300)) desc = LocalBinaryPatterns(24, 8) hist = desc.describe(rezise_img) data.append(hist) # print(faces) for x in data: with open('data.txt', 'a') as f: f.write(str(x) + ',')
def binary_function(type_rec): l = [] # construct the argument parse and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-t", "--training", required=False, default='images/training/', help="path to the training images") ap.add_argument("-e", "--testing", required=False, default='images/testing/', help="path to the tesitng images") args = vars(ap.parse_args()) # initialize the local binary patterns descriptor along with # the data and label lists if type_rec == 'symbol': desc = LocalBinaryPatterns(24, 8) else: desc = LocalBinaryPatterns(24, 3) data = [] labels = [] # loop over the training images for imagePath in paths.list_images(args["training"]): # for imagePath in os.listdir('images/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(os.path.sep)[-2]) data.append(hist) model = DecisionTreeClassifier(random_state=0) model.fit(data, labels) # loop over the testing images for imagePath in paths.list_images(args["testing"]): # for imagePath in os.listdir('images/testing/'): # load the image, convert it to grayscale, describe it, # and classify it image = cv2.imread(imagePath) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) hist = desc.describe(gray) prediction = model.predict(hist.reshape(1, -1)) # display the image and the prediction # cv2.putText(image, prediction[0], (10, 30), cv2.FONT_HERSHEY_SIMPLEX, # 1.0, (0, 0, 255), 3) # cv2.imshow("Image", image) # cv2.waitKey(0) l.append([prediction[0], imagePath]) # print (l) if type_rec == 'symbol': result = symbol(l[0][0]) string = "The symbol is " + str( l[0][0] ) + " Meaning of symbol: " + result[0] + " Reference: " + result[1] else: s_p = [] for i in l: s_p.append(i[0]) patt = ', '.join(s_p) string = "The symbols identified are " + patt return string
help="path to the training 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 = [] print("[INFO] Labeling Images...") # 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, 0) #gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) hist = desc.describe(image) # extract the label from the image path, then update the # label and data lists # label = imagePath.split("\\")[1] labels.append(imagePath.split("\\")[1]) data.append(hist) print("[INFO] Images Labeled...") #data = data.reshape(-1,1) #labels = labels.reshape(-1,1) # train a Linear SVM on the data model = LinearSVC(C=100.0, random_state=42, max_iter=5000) print("[INFO] SVM loaded...") print("[INFO] Model fitting...") model.fit(data, labels) print("[INFO] Model fitted...")
patch_height = (img_height // patch_size) + 1 patch_length = patch_width * patch_height img_name = path.split('.')[0] + ".JPG" img = cv2.imread("data/test_images_site_32/" + img_name) img = imutils.resize(img, width=1024) img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) (img_h, img_s, img_v) = cv2.split(cv2.cvtColor(img, cv2.COLOR_BGR2HSV)) # Store gray patch descriptions for (patch_id, (x, y, win)) in enumerate( sliding_window(img_gray, stepSize=patch_size, windowSize=(win_size, win_size))): hist4 = desc4.describe(win) hist4 /= hist4.sum() hist4 = hist4.reshape(1, -1) proba_4 = model_lbp.predict_proba(hist4) lbp_probas[img_id, patch_id] = proba_4 # Precompute h and s histograms for (patch_id, (x, y, win_h, win_s)) in enumerate( sliding_window_double(img_h, img_s, stepSize=patch_size, windowSize=(win_size, win_size))): h_flat = win_h.reshape(1, win_h.shape[0] * win_h.shape[1]) s_flat = win_s.reshape(1, win_s.shape[0] * win_s.shape[1])
cv2.waitKey(0) elif search == 1: # load the index and initialize the searchers file_rgb = open("index_rgb.cpickle" + ".pkl", 'rb') index_rgb = pickle.load(file_rgb) searcher_rgb = Searcher(index_rgb) desc_rgb = RGBHistogram([8, 8, 8]) queryFeatures_rgb = desc_rgb.describe(queryImage) file_lbp = open("index_lbp.cpickle" + ".pkl", 'rb') index_lbp = pickle.load(file_lbp) searcher_lbp = Searcher(index_lbp) desc_lbp = LocalBinaryPatterns(24, 8) gray_lbp = cv2.cvtColor(queryImage, cv2.COLOR_BGR2GRAY) queryFeatures_lbp = desc_lbp.describe(gray_lbp) file_hog = open("index_hog.cpickle" + ".pkl", 'rb') index_hog = pickle.load(file_hog) searcher_hog = Searcher(index_hog) winSize = (64, 64) blockSize = (16, 16) blockStride = (8, 8) cellSize = (8, 8) nbins = 9 derivAperture = 1 winSigma = 4. histogramNormType = 0 L2HysThreshold = 2.0000000000000001e-01 gammaCorrection = 0 nlevels = 64
# Ensure patch size if flag_resize_patch: window_gray = imutils.resize(window_gray, width=100) window_hsv = imutils.resize(window_hsv, width=100) # Describe gray patch (kps, descs) = dad.describe(window_gray) if kps is None or descs is None: continue hist = bovw.describe(descs) hist /= hist.sum() hist = hist.toarray() # Get lbp descriptions hist4 = desc4.describe(window_gray) hist8 = desc8.describe(window_gray) hist4 /= hist4.sum() hist8 /= hist8.sum() hist4 = hist4.reshape(1, -1) hist8 = hist8.reshape(1, -1) proba_4 = model_lbp4.predict_proba(hist4).flatten() proba_8 = model_lbp8.predict_proba(hist8).flatten() # Apply idf factor to histogram if idf is not None: idf = idf.reshape(1, -1) hist *= idf
trainingPath = "/home/krzysztof/Dokumenty/SNR_grupa1/images/training" keyboard = glob.glob(trainingPath + "/keyboard" + "/*.*") carpet = glob.glob(trainingPath + "/carpet" + "/*.*") area_rug = glob.glob(trainingPath + "/area_rug" + "/*.*") wrapping_paper = glob.glob(trainingPath + "/wrapping_paper" + "/*.*") desc = LocalBinaryPatterns(24, 8) data = [] labels = [] paths = carpet + keyboard + area_rug + wrapping_paper print("Ekstrakcja cech\n") for imagePath in paths: print(imagePath + "\n") image = cv2.imread(imagePath) print(str(image.shape) + "\n") gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Skala szarości hist = desc.describe(gray) # LBP na obrazie - zwraca histogram # extract the label from the image path, then update the # label and data lists labels.append(imagePath.split("/")[-2]) data.append(hist) # Koniec aktu 1: Mamy cechy obrazu. Następnie można użyć ich do rozpoznawania obrazów # Akt 2 print("Uczenie SVC\n") model = LinearSVC(C=100.0, random_state=42) model.fit(data, labels) print("Testowanie\n") # Testing keyboardTestPath = "/home/krzysztof/Dokumenty/SNR_grupa1/images/testing/keyboard.png" carpetTestPath = "/home/krzysztof/Dokumenty/SNR_grupa1/images/testing/carpet.png"
required=True, help="path to the training images") ap.add_argument("-e", "--testing", required=True, help="blah") args = vars(ap.parse_args()) bob = LocalBinaryPatterns(24, 8) data = [] labels = [] for imagePath in paths.list_images(args['training']): # image = io.imread(imagePath) # # stretch = exposure.rescale_intensity(image) # grey = skimage.color.rgb2gray(image) image = cv2.imread(imagePath) grey = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) hist = bob.describe(grey) labels.append(imagePath.split(os.path.sep)[-2]) data.append(hist) StandardScaler.transform(data) model = LinearSVC(C=1000.0, random_state=42) model.fit(data, labels) for imagePath in paths.list_images(args['testing']): # image = io.imread(imagePath) # stretch = exposure.rescale_intensity(image) # grey = skimage.color.rgb2gray(stretch) image = cv2.imread(imagePath) grey = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) hist = bob.describe(grey) prediction = model.predict(hist.reshape(1, -1))
widgets = [ "Analyzing Images: ", progressbar.Percentage(), " ", progressbar.Bar(), " ", progressbar.ETA() ] pbar = progressbar.ProgressBar(maxval=len(training_set), widgets=widgets).start() for i, image_path in enumerate(training_set): # load the image, convert it to grayscale, and describe it image = cv2.imread(image_path) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) hist4 = desc4.describe(gray) hist4 /= hist4.sum() data4.append(hist4) hist8 = desc8.describe(gray) hist8 /= hist8.sum() data8.append(hist8) label = image_path.split(os.path.sep)[-2] labels.append(label) pbar.update(i) pbar.finish() # train a Linear SVM on the data