def testing(testing_set_path, serialized_data): X_name, X_test, y_test = joblib.load(serialized_data) test_images = cvutils.imlist(testing_set_path) results_all = {} for test_image in test_images: print("\nCalculating Normalized LBP Histogram for {}".format(test_image)) im = cv2.imread(test_image) im_gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) radius = 3 no_points = 8 * radius lbp = local_binary_pattern(im_gray, no_points, radius, method='uniform') x = itemfreq(lbp.ravel()) hist = x[:, 1]/sum(x[:, 1]) results = [] """ Methods for comparing histograms: 0: correlation 1: chi-square 2: intersection 3/4: computes Bhattacharyya distance, which is related to Bhattacharyya coefficient Calculate the chi-squared distance and then sort the values(the lower the distance -> better result) """ for index, x in enumerate(X_test): score = cv2.compareHist(np.array(x, dtype=np.float32), np.array(hist, dtype=np.float32), method=1) results.append((X_name[index], round(score, 3))) results = sorted(results, key=lambda score: score[1]) results_all[test_image] = results print("Displaying scores for {} ** \n".format(test_image)) for image, score in results: print("[SCORES] [{} has score {}".format(image, score)) return results_all
def train_save(train_set_path): train_hist = [] train_name = [] train_images = cvutils.imlist(train_set_path) for ti in train_images: im = cv2.imread(ti) hist = calculate_hist(im) train_name.append(ti) train_hist.append(hist) cPickle.dump(train_name, open('train_name.p', 'wb')) cPickle.dump(train_hist, open('train_hist.p', 'wb')) return train_name, train_hist
def parse_img(): X_name, X_test, y_test = joblib.load("lbp.pkl") test_images = cvutils.imlist('data/lbp/test/leisi/') results_all = {} matched = [] for test_image in test_images: if not isimg(test_image): continue print "\nCalculating Normalized LBP Histogram for {}".format( test_image) # Read the image im = cv2.imread(test_image) # Convert to grayscale as LBP works on grayscale image im_gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) radius = 3 # Number of points to be considered as neighbourers no_points = 8 * radius # Uniform LBP is used lbp = local_binary_pattern(im_gray, no_points, radius, method='uniform') # Calculate the histogram x = itemfreq(lbp.ravel()) # Normalize the histogram hist = x[:, 1] / sum(x[:, 1]) # Display the query image results = [] # For each image in the training dataset # Calculate the chi-squared distance and the sort the values for index, x in enumerate(X_test): score = cv2.compareHist(np.array(x, dtype=np.float32), np.array(hist, dtype=np.float32), cv2.cv.CV_COMP_CHISQR) results.append((X_name[index], round(score, 3))) results = sorted(results, key=lambda score: score[1]) results_all[test_image] = results print "Displaying scores for {} ** \n".format(test_image) for image, score in results: if score < 0.012: print "{} has score {}".format(image, score) matched.append(image) return matched
def parse_img(): X_name, X_test, y_test = joblib.load("lbp.pkl") test_images = cvutils.imlist('data/lbp/test/leisi/') results_all = {} matched = [] for test_image in test_images: if not isimg(test_image): continue print "\nCalculating Normalized LBP Histogram for {}".format(test_image) # Read the image im = cv2.imread(test_image) # Convert to grayscale as LBP works on grayscale image im_gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) radius = 3 # Number of points to be considered as neighbourers no_points = 8 * radius # Uniform LBP is used lbp = local_binary_pattern(im_gray, no_points, radius, method='uniform') # Calculate the histogram x = itemfreq(lbp.ravel()) # Normalize the histogram hist = x[:, 1]/sum(x[:, 1]) # Display the query image results = [] # For each image in the training dataset # Calculate the chi-squared distance and the sort the values for index, x in enumerate(X_test): score = cv2.compareHist(np.array(x, dtype=np.float32), np.array(hist, dtype=np.float32), cv2.cv.CV_COMP_CHISQR) results.append((X_name[index], round(score, 3))) results = sorted(results, key=lambda score: score[1]) results_all[test_image] = results print "Displaying scores for {} ** \n".format(test_image) for image, score in results: if score < 0.012: print "{} has score {}".format(image, score) matched.append(image) return matched
parser = ap.ArgumentParser() parser.add_argument("-t", "--testingSet", help="Path to Testing Set", required="True") parser.add_argument("-l", "--imageLabels", help="Path to Image Label Files", required="True") args = vars(parser.parse_args()) # Load the List for storing the LBP Histograms, address of images and the corresponding label X_name, X_test, y_test = joblib.load("lbp.pkl") # Store the path of testing images in test_images test_images = cvutils.imlist(args["testingSet"]) # Dictionary containing image paths as keys and corresponding label as value test_dic = {} with open(args["imageLabels"], 'rt') as csvfile: reader = csv.reader(csvfile, delimiter=' ') for row in reader: test_dic[row[0]] = int(row[1]) # Dict containing scores results_all = {} for test_image in test_images: print("\nCalculating Normalized LBP Histogram for {}".format(test_image)) # Read the image im = cv2.imread(test_image) # Convert to grayscale as LBP works on grayscale image
import numpy as np # For saving histogram values import joblib # For command line input import argparse as ap # Utility Package import cvutils # Get the path of the training set parser = ap.ArgumentParser() parser.add_argument("-t", "--trainingSet", help="Path to Training Set", required="True") parser.add_argument("-l", "--imageLabels", help="Path to Image Label Files", required="True") args = vars(parser.parse_args()) # Store the path of training images in train_images train_images = cvutils.imlist(args["trainingSet"]) # Dictionary containing image paths as keys and corresponding label as value train_dic = {} with open(args['imageLabels'], 'rt') as csvfile: reader = csv.reader(csvfile, delimiter=' ') for row in reader: train_dic[row[0]] = int(row[1]) # List for storing the LBP Histograms, address of images and the corresponding label X_test = [] X_name = [] y_test = [] # For each image in the training set calculate the LBP histogram # and update X_test, X_name and y_test for train_image in train_images:
def trainproc(): train_imgs1 = cvutils.imlist("train_images\\500") train_imgs2 = cvutils.imlist("train_images\\2000") k = 0 for tr in train_imgs1: pth = tr # Reading the image out = "train\\500" img = cv2.imread(pth) # resizing img = cv2.resize(img, (1200, 512), interpolation=cv2.INTER_LINEAR) # Denoising image img = cv2.fastNlMeansDenoisingColored(img, None, 10, 10, 7, 21) # Converting to grayscale img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) # compute the median of the single channel pixel intensities v = np.median(img) sigma = 0.33 # apply automatic Canny edge detection using the computed median lower = int(max([0, (1.0 - sigma) * v])) upper = int(min([255, (1.0 + sigma) * v])) img = cv2.Canny(img, lower, upper) # Extracting features id1 = img[195:195 + 170, 190:190 + 85] id2 = img[330:330 + 105, 720:720 + 105] id3 = img[320:320 + 90, 865:865 + 205] id4 = img[250:250 + 40, 1120:1120 + 40] id5 = img[5:5 + 405, 660:660 + 40] id6 = img[284:284 + 132, 1090:1090 + 90] # Saving the features ids = [id1, id2, id3, id4, id5, id6] out1 = "\\demo" + str(k) + ".jpg" d = 1 for i in ids: cv2.imwrite(out + "\\id%d" % d + out1, i) d = d + 1 k = k + 1 k = 0 for tr in train_imgs2: pth = tr # Reading the image out = "train\\2000" img = cv2.imread(pth) # resizing img = cv2.resize(img, (1200, 512), interpolation=cv2.INTER_LINEAR) # Denoising image img = cv2.fastNlMeansDenoisingColored(img, None, 10, 10, 7, 21) # Converting to grayscale img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) # compute the median of the single channel pixel intensities v = np.median(img) sigma = 0.33 # apply automatic Canny edge detection using the computed median lower = int(max([0, (1.0 - sigma) * v])) upper = int(min([255, (1.0 + sigma) * v])) img = cv2.Canny(img, lower, upper) # Extracting features id1 = img[195:195 + 165, 225:225 + 55] id2 = img[330:330 + 95, 760:760 + 90] id3 = img[335:335 + 80, 890:890 + 205] id4 = img[255:255 + 25, 1105:1105 + 53] id5 = img[10:10 + 480, 726:726 + 35] id6 = img[280:280 + 140, 1100:1100 + 75] # Saving the features ids = [id1, id2, id3, id4, id5, id6] out1 = "\\demo" + str(k) + ".jpg" d = 1 for i in ids: cv2.imwrite(out + "\\id%d" % d + out1, i) d = d + 1 k = k + 1
import argparse as ap # Utility Package import cvutils # Get the path of the training set parser = ap.ArgumentParser() parser.add_argument("-t", "--testingSet", help="Path to Testing Set", required="True") parser.add_argument("-l", "--imageLabels", help="Path to Image Label Files", required="True") args = vars(parser.parse_args()) # Load the List for storing the LBP Histograms, address of images and the corresponding label X_name, X_test, y_test = joblib.load("lbp.pkl") # Store the path of testing images in test_images test_images = cvutils.imlist(args["testingSet"]) print test_images # Dictionary containing image paths as keys and corresponding label as value test_dic = {} with open(args["imageLabels"], "rb") as csvfile: reader = csv.reader(csvfile, delimiter=" ") for row in reader: test_dic[row[0]] = int(row[1]) # Dict containing scores results_all = {} for test_image in test_images: def isimg(impth): return impth.endswith("jpg") or impth.endswith("jpeg")
cv2.destroyAllWindows() def genuine_img(): pth = "genuine.jpg" img = cv2.imread(pth) cv2.imshow('GENUINE!!!!', img) cv2.waitKey(0) cv2.destroyAllWindows() # Load the List for storing the LBP Histograms, address of images and the corresponding label X_test500, X_test2000, n = joblib.load("lbp.pkl") # Store the path of testing images in test_images test_images500 = cvutils.imlist("test/ids1") test_images2000 = cvutils.imlist("test/ids2") # Dict containing scores results_all500 = {} results_all2000 = {} # total scores tot500 = 0 tot2000 = 0 for i in range(6): # Read the image im = cv2.imread(test_images500[ i ], 0) radius = 3
import matplotlib.pyplot as plt # For array manipulations import numpy as np # For saving histogram values from sklearn.externals import joblib # For command line input import argparse as ap # Utility Package import cvutils # Get the path of the input image parser = ap.ArgumentParser() parser.add_argument("-i", "--inputimage", help="Path to Input Image folder", required="True") args = vars(parser.parse_args()) train_images = cvutils.imlist(args["inputimage"]) X_name= [] X_hist=[] for train_image in train_images: # Read the image im = cv2.imread(train_image) # Convert to grayscale as LBP works on grayscale image im_gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) cv2.imshow('',im_gray) radius = 3 # Number of points to be considered as neighbourers no_points = 8 * radius # Uniform LBP is used lbp = local_binary_pattern(im_gray, no_points, radius, method='uniform') # Calculate the histogram
import numpy as np # For saving histogram values from sklearn.externals import joblib # For command line input import argparse as ap # Utility Package import cvutils # Get the path of the training set parser = ap.ArgumentParser() parser.add_argument("-t", "--trainingSet", help="Path to Training Set", required="True") parser.add_argument("-l", "--imageLabels", help="Path to Image Label Files", required="True") args = vars(parser.parse_args()) # Store the path of training images in train_images train_images = cvutils.imlist(args["trainingSet"]) # Dictionary containing image paths as keys and corresponding label as value train_dic = {} with open(args['imageLabels'], 'rb') as csvfile: reader = csv.reader(csvfile, delimiter=' ') for row in reader: train_dic[row[0]] = int(row[1]) # List for storing the LBP Histograms, address of images and the corresponding label X_test = [] X_name = [] y_test = [] # For each image in the training set calculate the LBP histogram # and update X_test, X_name and y_test for train_image in train_images:
def set_train_images(self, training_set_path): try: self._train_images = cvutils.imlist(training_set_path) except AssertionError as ae: print(ae)
score = cv2.compareHist(np.array(train_hist, dtype=np.float32), \ np.array(test_hist, dtype=np.float32),cv2.cv.CV_COMP_CHISQR) results.append((train_name[index], round(score,3))) # print('==============') results = sorted(results, key=lambda score: score[1]) # print(results[0:20]) # print(results[0][0]) label = results[0][0].split('/')[-1].split('.')[0].split('-')[0] # print('label:',label) return label if __name__ == '__main__': test_checkcodes = cvutils.imlist('./test_checkcode/') time = 0 accu = 0 for file in test_checkcodes: time = time + 1 print('checkcode:',file) im = Image.open(file) result = test(im, './template_rgb/') print('result:', result) if result == file.split('/')[-1].split('.')[0]: accu = accu + 1 else: print('error!', time - accu) print('accuracy:%d / %d = %f'%(accu, time, float(accu)/ time))
import matplotlib.pyplot as plt from skimage import segmentation, color, measure from skimage.future import graph from skimage.exposure import rescale_intensity from skimage.morphology import remove_small_objects, label from skimage.feature import daisy from skimage.color import rgb2gray from datasets import * path="C:\\Users\\Saksham\\Desktop\\Research AI 2\\Python codes" os.chdir(path) train_images = cvutils.imlist("C:/Users/Saksham/Desktop/research-AI 1/python codes/images-corel1K/") nmb_seg=100 all_features = [] for train_image in train_images: image = cv2.imread(train_image) #image = cv2.resize(image, (384, 255)) # by default slic computes ~100 superpixels. # compactness controls the shape of the superpixels. segmentation = slic(image, n_segments=nmb_seg, compactness=20, sigma=0) fig, axes = plt.subplots(3, 1, figsize=(20, 10))
# OpenCV bindings import cv2 # Utility package -- use pip install cvutils to install import cvutils # To read class from file import csv import numpy as np cap = cv2.VideoCapture(1) train_images = cvutils.imlist( "C:/Users/Petran/PycharmProjects/untitled3/Train/") train_dic = {} with open('C:\Users\Petran\PycharmProjects\untitled3\class_train.txt', 'rb') as csvfile: reader = csv.reader(csvfile, delimiter=' ') for row in reader: train_dic[row[0]] = int(row[1]) X_test = [] X_name = [] sift = cv2.ORB() MIN_MATCH_COUNT = 10 for train_image in train_images: # Read the image im = cv2.imread(train_image) # Convert to grayscale as LBP works on grayscale image im_gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) kp1, des1 = sift.detectAndCompute(im_gray, None) # Append image path in X_name X_name.append(train_image) # Append histogram to X_name
from sklearn.preprocessing import normalize # Utility package -- use pip install cvutils to install import cvutils # To read class from file import csv import matplotlib.pyplot as plt import numpy as np ########################### # CODE FROM: http://hanzratech.in/2015/05/30/local-binary-patterns.html ########################### # List for storing the LBP Histograms, address of images and the corresponding label train_images = cvutils.imlist("input/") # List for storing the LBP Histograms, address of images and the corresponding label X_test = [] X_name = [] # y_test = [] # For each image in the training set calculate the LBP histogram # and update X_test, X_name and y_test import scipy.misc for radius in [3]: print radius for train_image in train_images:
# Local Binary Pattern function from skimage.feature import local_binary_pattern # For plotting import matplotlib.pyplot as plt # For array manipulations import numpy as np # For saving histogram values from sklearn.externals import joblib # Utility Package import cvutils # Store the path of training images in train_images train_images500 = [] for d in range(6): i = d + 1 ti = cvutils.imlist("train/500/id%i" % i) train_images500.append(ti) n = len(train_images500[0]) train_images2000 = [] for d in range(6): i = d + 1 ti = cvutils.imlist("train/2000/id%i" % i) train_images2000.append(ti) n = len(train_images2000[0]) X_test500 = [] X_test2000 = [] # For each image in the training set calculate the LBP histogram # and update X_test, X_name and y_test
# To performing path manipulations import os # Local Binary Pattern function from skimage.feature import local_binary_pattern # To calculate a normalized histogram from scipy.stats import itemfreq from sklearn.preprocessing import normalize # Utility package -- use pip install cvutils to install from matplotlib import pyplot as plt import cvutils # To read class from file import csv import pandas as pd # Store the path of training images in train_image/ train_images = cvutils.imlist("C:/Users/Shristi Gupta/Desktop/research-AI/python codes/images-corel1K/") # Dictionary containing image paths as keys and corresponding label as value Y_test = [] Y_name = [] ##### testing lbp code on the database for train_image in train_images: # Read the image im = cv2.imread(train_image) # Convert to grayscale as LBP works on grayscale image im_gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) radius = 1 # Number of points to be considered as neighbourers no_points = 8 * radius