Ejemplo n.º 1
0
def readimages(root):
    folderpaths = os.listdir(root)
    allfortrain = {}
    for folder in folderpaths:
        folderpath = os.path.join(root, folder)
        if os.path.isdir(folderpath) == 0:
            continue
        trainingimages = []
        images = os.listdir(folderpath)
        for image in images:
            print "image", image
            fullfilename = os.path.join(folderpath, image)
            # results = my_ocr(fullfilename)
            img = cv2.imread(fullfilename, cv2.IMREAD_GRAYSCALE)
            # for result in results:
            # 	leftup = result['vertexes_location'][3]
            # 	rightdown = result['vertexes_location'][1]
            # 	pt1 = (leftup['x'],leftup['y'])
            # 	pt2 = (rightdown['x'],rightdown['y'])
            # 	color = np.int0((img[pt1[1],pt1[0]]+img[pt2[1],pt2[0]])/2)
            # 	cv2.rectangle(img, pt1, pt2, color,-1)
            try:
                size = max(img.shape[0], img.shape[1])
            except:
                print "gg"
                continue
            img = cv2.resize(img, (size, size))
            size = int(size / 2)
            hog = Hog_descriptor(img, cell_size=size, bin_size=16)
            vector, img = hog.extract()
            vector = vector[0]
            trainingimages.append(vector)
        allfortrain[folder] = trainingimages
    return allfortrain
Ejemplo n.º 2
0
 def calc_energy_map(self):
     '''
     计算此时的能量势函数
     '''
     
     b, g, r = cv2.split(self.out_image)
     if self.energy is 'l2':
         b_energy = np.sqrt(np.absolute(cv2.Scharr(b, -1, 1, 0))**2 + np.absolute(cv2.Scharr(b, -1, 0, 1))**2)
         g_energy = np.sqrt(np.absolute(cv2.Scharr(g, -1, 1, 0))**2 + np.absolute(cv2.Scharr(g, -1, 0, 1))**2)
         r_energy = np.sqrt(np.absolute(cv2.Scharr(r, -1, 1, 0))**2 + np.absolute(cv2.Scharr(r, -1, 0, 1))**2)
     
     
     else:
         # L1 energy
         b_energy = np.absolute(cv2.Scharr(b, -1, 1, 0)) + np.absolute(cv2.Scharr(b, -1, 0, 1))
         g_energy = np.absolute(cv2.Scharr(g, -1, 1, 0)) + np.absolute(cv2.Scharr(g, -1, 0, 1))
         r_energy = np.absolute(cv2.Scharr(r, -1, 1, 0)) + np.absolute(cv2.Scharr(r, -1, 0, 1))
     
     E = b_energy + g_energy + r_energy   
     
     if self.energy is 'hog':
         hog = Hog_descriptor(self.out_image, cell_size=11, bin_size=8)
         histogram = hog.extract()
         histogram = histogram / np.linalg.norm(histogram)
         E = E / histogram
     
     return E
def testsvm(svm, root):
    images = os.listdir(root)
    testimages = []
    for image in images:
        print image, "image"
        fullfilename = os.path.join(root, image)
        img = cv2.imread(fullfilename, cv2.IMREAD_GRAYSCALE)
        size = max(img.shape[0], img.shape[1])
        img = cv2.resize(img, (size, size))
        size = int(img.shape[0] / 2)
        hog = Hog_descriptor(img, cell_size=size, bin_size=16)
        vector, img = hog.extract()
        # vector = np.float32(np.array(vector))
        testimages.append(vector[0])
    testimages = np.float32(np.array(testimages))
    result = svm.predict_all(testimages)
    return result
def readimages(root, attribute):
    folderpaths = os.listdir(root)

    labels = []
    for line in open(attribute):
        labels.append(line)

    allfortrain = {}
    # for folder in folderpaths:
    # folderpath = os.path.join(root,folder)
    # 	if os.path.isdir(folderpath) == 0:
    # 		continue
    trainingimages = []
    images = os.listdir(root)

    cnt = 0
    for image in images:
        print 'training ' + str(cnt) + ' image'
        label = labels[cnt]
        # print "image",image
        fullfilename = os.path.join(root, image)
        # results = my_ocr(fullfilename)
        img = cv2.imread(fullfilename, cv2.IMREAD_GRAYSCALE)
        # for result in results:
        # 	leftup = result['vertexes_location'][3]
        # 	rightdown = result['vertexes_location'][1]
        # 	pt1 = (leftup['x'],leftup['y'])
        # 	pt2 = (rightdown['x'],rightdown['y'])
        # 	color = np.int0((img[pt1[1],pt1[0]]+img[pt2[1],pt2[0]])/2)
        # 	cv2.rectangle(img, pt1, pt2, color,-1)
        if img is not None:
            size = max(img.shape[0], img.shape[1])
            img = cv2.resize(img, (size, size))
            size = int(size / 2)
            hog = Hog_descriptor(img, cell_size=size, bin_size=16)
            vector, img = hog.extract()
            #print "lenin",len(vector)
            vector = vector[0]
            #print "lenin",len(vector)
            trainingimages.append(vector)
            # plt.imshow(img,cmap=plt.cm.gray)
            # plt.show()
            allfortrain[label] = trainingimages
        cnt += 1
    return allfortrain
Ejemplo n.º 5
0
    def preprocess(self, samples, augment_data=False):
        """format the features and labels as necessary for processing"""

        y = []
        x = []
        x_feat = []

        for idx, image in samples.iterrows():
            y.append(int(image.emotion))
            image_pixel = np.asarray(
                [float(pix) for pix in image.pixels.split(" ")])
            x.append(image_pixel)
        """Augmenting dataset for training"""
        if (augment_data):
            da = DataAugmentation()
            x, y = da.augment_dataset(x, y)
        """Extracting HOG Features"""
        for image_pixel in x:
            hog = Hog_descriptor(image_pixel, cell_size=2, bin_size=8)
            vector, image = hog.extract()
            x_feat.append(vector)
        return np.asarray(x), np.asarray(x_feat), np.asarray(y)
Ejemplo n.º 6
0
def get_HOG_Features(trainingPath, testingPath, cell_size=16, bin_size=8):
    from hog import Hog_descriptor

    # initialize the local binary patterns descriptor along with the data and label lists
    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")):
        # open image
        img = cv2.imread(imagePath)
        gray = np.matrix(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY))
        resized_image = cv2.resize(gray, (48, 48))

        # get hog features
        hog = Hog_descriptor(resized_image, cell_size=cell_size, bin_size=bin_size)
        vector = hog.extract()
        v = np.array(vector)

        # extract the label from the image path, then update the
        # label and data lists
        labels.append(int(imagePath.split("/")[-2]))
        data.append(vector)

    # loop over the testing images
    for imagePath in paths.list_files(testingPath, validExts=(".png",".ppm")):
        
        # open image
        img = cv2.imread(imagePath)
        gray = np.matrix(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY))
        resized_image = cv2.resize(gray, (48, 48))

        # get hog features
        hog = Hog_descriptor(resized_image, cell_size=cell_size, bin_size=bin_size)
        vector = hog.extract()

        # extract the label from the image path, then update the
        # label and data lists
        test_labels.append(int(imagePath.split("/")[-2]))
        test_data.append(vector)

    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)

    print "[INFO] HOG 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 get_all_samples_HOG(path, cell_size, bin_size):
	from hog import Hog_descriptor

	data = []
	labels = []
	classSamplesList = []
	samples_amount_of_classes = []
	currentClass = None
	flag = False

	class_list = os.listdir(path)
	if '.DS_Store' in class_list:
		class_list.remove('.DS_Store')
	if 'Readme.txt' in class_list:
		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
					
		# open image
		img = cv2.imread(imagePath)
		gray = np.matrix(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY))
		resized_image = cv2.resize(gray, (48, 48))
		# get hog features
		hog = Hog_descriptor(resized_image, cell_size=cell_size, bin_size=bin_size)
		vector = hog.extract()
		v = np.array(vector)
		# extract the label from the image path, then update the
		# label and data lists
		labels.append(imagePath.split("/")[-2])
		data.append(vector)

	data = []
	head, _ = os.path.split(lastClassPath)

	for imagePath in paths.list_files(head, validExts=(".png", ".ppm")):
		# open image
		img = cv2.imread(imagePath)
		gray = np.matrix(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY))
		resized_image = cv2.resize(gray, (48, 48))
		# get hog features
		hog = Hog_descriptor(resized_image, cell_size=cell_size, bin_size=bin_size)
		vector = hog.extract()
		v = np.array(vector)
		# extract the label from the image path, then update the
		# label and data lists
		labels.append(imagePath.split("/")[-2])
		data.append(vector)


	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)

	return all_samples, labels ,samples_amount_of_classes
Ejemplo n.º 8
0
from hog import Hog_descriptor
import cv2

psw_bob = "This is Bob's psw"
psw_alice = "This is Alice's psw"

Bob_private_key2, Bob_public_key2 = encrypt.create_key(psw_bob)
Alice_private_key2, Alice_public_key2 = encrypt.create_key(psw_alice)

receiver_key = encrypt.encode_key(Alice_public_key2)
sender_key = encrypt.encode_key(Bob_public_key2)

img = cv2.imread(
    '/Users/liyu/Desktop/blockchain/Blockchain/ADE_train_00000158.jpg',
    cv2.IMREAD_GRAYSCALE)
hog = Hog_descriptor(img, cell_size=8, bin_size=8)
vector, image = hog.extract()
msg = vector.__str__()
msg_256 = encrypt.sha_256(msg)

signature = encrypt.sign(nacl.encoding.HexEncoder.encode(msg_256),
                         Bob_private_key2)

transcation = {
    "sender": "d4ee26eee15148ee92c6cd394edd974e",
    "receiver": "someone-other-address",
    "msg": nacl.encoding.HexEncoder.encode(msg_256),
    "signature": signature,
    "receiver_public_key": receiver_key,
    "sender_public_key": sender_key,
    "id": "123174123"
Ejemplo n.º 9
0
from hog import Hog_descriptor
import argparse
import glob
import cv2

# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-d", "--dataset", required = True,
	help = "Path to the directory that contains the images to be indexed")
ap.add_argument("-i", "--index", required = True,
	help = "Path to where the computed index will be stored")
args = vars(ap.parse_args()) 

output = open(args["index"], "w")

for imagePath in glob.glob(args["dataset"] + "/*.jpg"):
    imageID = imagePath[imagePath.rfind("/") + 1:]
    img = cv2.imread(imagePath, cv2.IMREAD_GRAYSCALE)
    hog = Hog_descriptor(img, cell_size=int(8), bin_size=int(8))
    vector, image = hog.extract()
    features=vector

    features = list(chain.from_iterable(features))
    features = [str(f) for f in features]
    
    print(len(features))
    
    output.write("%s,%s,%s\n" % (imageID, str(len(features)), ",".join(features)))
    print("%s",imagePath)

output.close()
Ejemplo n.º 10
0
import cv2

ap = argparse.ArgumentParser()
ap.add_argument("-i",
                "--index",
                required=True,
                help="Path to where the computed index will be stored")
ap.add_argument("-q", "--query", required=True, help="Path to the query image")
ap.add_argument("-r",
                "--result-path",
                required=True,
                help="Path to the result path")
args = vars(ap.parse_args())

query = cv2.imread(args["query"], cv2.IMREAD_GRAYSCALE)
hog = Hog_descriptor(query, cell_size=int(16), bin_size=int(8))
features, image = hog.extract()
cv2.imshow('HOG Features', image)
cv2.waitKey(0)
features = list(chain.from_iterable(features))
features.insert(0, len(features))
print("length is", len(features))

searcher = Similarity(args["index"])
results = searcher.search(features)

cv2.imshow("Query", query)
print("Query is: ", query)
cv2.waitKey(0)
print("result is: ", results[0])
# loop over the results