Ejemplo n.º 1
0
	def searchimg(self, index1='index1.csv', index2='index2.csv', result_path='jpg'):
		cd = ColorDescriptor((8,12,3))
		vd = Vgg16Descriptor((224,224,3))
		query = cv2.imread("./query/" + self.filename)
		feature1 = cd.describe(query)
		feature2 = vd.describe(self.querypath)

		searcher = Searcher(index1,index2)
		results = searcher.search(feature1,feature2)

		result0 = cv2.resize(query,(128,128),interpolation=cv2.INTER_CUBIC)	

		name = locals()
		i = 1

		for (score, resultID) in results:
			name['result%d'%i] = cv2.imread(result_path + "/" + resultID)
			name['result%d'%i] = cv2.resize(name['result%d'%i],(128,128),interpolation=cv2.INTER_CUBIC)	
			i = i + 1
			
		result_0 = np.hstack(name['result%d'%i] for i in range(1,6))
		result_1 = np.hstack(name['result%d'%i] for i in range(6,11))
		result = np.vstack((result_0,result_1))
		cv2.imwrite("./result/%s" % self.filename, result)
		return self.filename
Ejemplo n.º 2
0
	def cal_center_region_hist(self, image):
		# initialize the color descriptor
		# using 8 Hue bins, 12 Saturation bins, and 3 Value bins
		cd = ColorDescriptor((8, 12, 3))
		
		# convert the image to the HSV color space and initialize
		# the features used to quantify the image
		image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
		features = []

		# grab the dimensions and compute the center of the image
		(h, w) = image.shape[:2]
		(cX, cY) = (int(w * 0.5), int(h * 0.5))

		# construct an elliptical mask representing the center of the image
		(axesX, axesY) = (int(w * 0.75) / 2, int(h * 0.75) / 2)
		ellipMask = np.zeros(image.shape[:2], dtype = "uint8")
		cv2.ellipse(ellipMask, (cX, cY), (axesX, axesY), 0, 0, 360, 255, -1)

		# extract a color histogram from the elliptical region and
		# update the feature vector
		hist = cd.histogram(image, ellipMask)
		hist = self.kmeans_region_features(hist)
		features.extend(hist.flatten())

		# return the feature vector
		return features
Ejemplo n.º 3
0
    def main_fun(self):
        # initialize the color descriptor
        cd = ColorDescriptor((8, 12, 3))

        # open the output index file for writing
        output = open(self.path, "w")
        #data contains the path to your images folder
        data = '/home/farhan/project/CBIR/my_contrib/test_dataset'
        # use glob to grab the image paths and loop over them
        types = ['/*.png', '/*.jpg']
        # os.chdir(data)
        for filetype in types:
            for imagePath in glob.glob(data + filetype):
                # extract the image ID (i.e. the unique filename) from the image
                # path and load the image itself
                imageID = imagePath[imagePath.rfind("/") + 1:]
                image = cv2.imread(imagePath)

                # describe the image
                features = cd.describe(image)

                # write the features to file
                features = [str(f) for f in features]
                output.write("%s,%s\n" % (imageID, ",".join(features)))

            # close the index file
        output.close()
Ejemplo n.º 4
0
	def main_fun(self):
		# initialize the color descriptor
		cd = ColorDescriptor((8, 12, 3))

		# open the output index file for writing
		output = open(self.path, "w")
		#data contains the path to your images folder
		data='/home/farhan/project/CBIR/my_contrib/test_dataset'
		# use glob to grab the image paths and loop over them
		types=['/*.png','/*.jpg']
		# os.chdir(data)
		for filetype in types:
			for imagePath in glob.glob(data+filetype):
				# extract the image ID (i.e. the unique filename) from the image
				# path and load the image itself
				imageID = imagePath[imagePath.rfind("/") + 1:]
				image = cv2.imread(imagePath)

				# describe the image
				features = cd.describe(image)

				# write the features to file
				features = [str(f) for f in features]
				output.write("%s,%s\n" % (imageID, ",".join(features)))

			# close the index file
		output.close()
Ejemplo n.º 5
0
def indexpy(dataset, index):
    print('hello')
    cd = ColorDescriptor((8, 12, 3))
    output = open(index, "w")
    for imagePath in glob.glob(dataset + "/*.jpg"):
        imageId = imagePath[imagePath.rfind("/") + 1:]
        image = cv2.imread(imagePath)
        features = cd.describe(image)
        features = [str(f) for f in features]
        output.write("%s,%s\n" % (imageId, ",".join(features)))
    output.close()
Ejemplo n.º 6
0
	def cal_region_hist(self, image):
		# initialize the color descriptor
		# using 8 Hue bins, 12 Saturation bins, and 3 Value bins
		cd = ColorDescriptor((8, 12, 3))
		
		# convert the image to the HSV color space and initialize
		# the features used to quantify the image
		image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
		features = []

		# grab the dimensions and compute the center of the image
		(h, w) = image.shape[:2]
		(cX, cY) = (int(w * 0.5), int(h * 0.5))

		# divide the image into four rectangles/segments (top-left,
		# top-right, bottom-right, bottom-left)
		segments = [(0, cX, 0, cY), (cX, w, 0, cY), (cX, w, cY, h),
			(0, cX, cY, h)]

		# construct an elliptical mask representing the center of the
		# image
		(axesX, axesY) = (int(w * 0.75) / 2, int(h * 0.75) / 2)
		ellipMask = np.zeros(image.shape[:2], dtype = "uint8")
		cv2.ellipse(ellipMask, (cX, cY), (axesX, axesY), 0, 0, 360, 255, -1)

		# loop over the segments
		for (startX, endX, startY, endY) in segments:
			# construct a mask for each corner of the image, subtracting
			# the elliptical center from it
			cornerMask = np.zeros(image.shape[:2], dtype = "uint8")
			cv2.rectangle(cornerMask, (startX, startY), (endX, endY), 255, -1)
			cornerMask = cv2.subtract(cornerMask, ellipMask)

			# extract a color histogram from the image, then update the
			# feature vector
			hist = cd.histogram(image, cornerMask)
			hist = self.kmeans_region_features(hist)
			features.extend(hist.flatten())

		# extract a color histogram from the elliptical region and
		# update the feature vector
		hist = cd.histogram(image, ellipMask)
		hist = self.kmeans_region_features(hist)
		features.extend(hist.flatten())

		# return the feature vector
		return features
Ejemplo n.º 7
0
    def search(img):

        # initialize the image descriptor
        cd = ColorDescriptor((8, 12, 3))

        # load the query image and describe it
        #query = cv2.imread(args["query"])
        #query = cv2.imread("queries/2.png")

        features = cd.describe(img)

        # perform the search

        searcher = Searcher("feature.csv")

        results = searcher.search(features)
        return results
Ejemplo n.º 8
0
def create_features(path):
    # initialize the color descriptor
    cd = ColorDescriptor((4, 4, 2))
     
    # use glob to grab the image paths and loop over them
    image_names, X = [], []
    for imagePath in listdir(path): 
        # extract the image ID (i.e. the unique filename) from the image
        # path and load the image itself
        imageID = basename(imagePath).split('.')[0] 
        image = cv2.imread(join(path,imagePath))

        # describe the image
        features = cd.describe(image)

        image_names.append(imageID)
        X.append(features)
    return np.array(image_names), np.array(X)
Ejemplo n.º 9
0
    def search_cut(self):
        # initialize the image descriptor
        cd = ColorDescriptor((8, 12, 3))

        # load the query image and describe it
        query = cv2.imread("out.jpg")
        features = cd.describe(query)

        # perform the search
        searcher = Searcher("index.csv")
        results = searcher.search(features)

        # loop over the results
        for (score, resultID) in results:
            # load the result image and display it
            result = cv2.imread(resultID)
            cv2.imshow("Result", result)
            cv2.waitKey(0)
Ejemplo n.º 10
0
def create_features(path):
    # initialize the color descriptor
    cd = ColorDescriptor((4, 4, 2))

    # use glob to grab the image paths and loop over them
    image_names, X = [], []
    for imagePath in listdir(path):
        # extract the image ID (i.e. the unique filename) from the image
        # path and load the image itself
        imageID = basename(imagePath).split('.')[0]
        image = cv2.imread(join(path, imagePath))

        # describe the image
        features = cd.describe(image)

        image_names.append(imageID)
        X.append(features)
    return np.array(image_names), np.array(X)
Ejemplo n.º 11
0
def search(index, query, result_path):
    # initialize the image descriptor
    cd = ColorDescriptor((8, 12, 3))
    # load the query image and describe it
    query1 = cv2.imread(query)
    features = cd.describe(query1)
    # perform the search
    searcher = Searcher(index)
    results = searcher.search(features)
    # display the query
    #cv2.imshow("Query", query1)
    search_output = []
    for (score, resultID) in results:
        #print(result_path+"/"+resultID)
        full_path = result_path + "/" + resultID
        #result=cv2.imread(result_path+"/"+resultID)
        #cv2.imshow("Result", result)
        #cv2.waitKey(0)
        search_output.append(resultID)
    #print(search_output)
    return search_output
Ejemplo n.º 12
0
def upload_file():
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        if file.filename == '':
            flash('No file selected for uploading')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

            # initialize the image descriptor
            cd = ColorDescriptor((8, 12, 3))
            # load the query image and describe it
            photos_result = []
            query = cv2.imread(app.config['UPLOAD_FOLDER']+"/"+filename)
            features = cd.describe(query)

            query_photo = {"score": 100, "photo": "queries/"+filename}
            photos_result.append(query_photo)
            # perform the search
            searcher = Searcher("./index.csv")
            results = searcher.search(features)

            # loop over the results
            for (score, resultID) in results:
                score = log10(abs(score))
                # load the result image and display it
                result = {"score": score, "photo": "dataset/"+resultID}
                photos_result.append(result)
            return render_template('result.html', results=photos_result)

        else:
            flash('Allowed file types are txt, pdf, png, jpg, jpeg, gif')
            return redirect(request.url)
Ejemplo n.º 13
0
def func3(command):
    findresult = []
    cd = ColorDescriptor((8, 12, 3))
    query = cv2.imread(command)
    features = cd.descriptor(query)
    searcher1 = Searcher("index.csv")
    results = searcher1.search(features)
    for (score, resultID) in results:
        findresult.append(resultID[:-4])

    STORE_DIR = "index1"
    vm_env = lucene.getVMEnv()
    vm_env.attachCurrentThread()
    directory = SimpleFSDirectory(File(STORE_DIR))
    searcher = IndexSearcher(DirectoryReader.open(directory))
    analyzer = WhitespaceAnalyzer(Version.LUCENE_CURRENT)
    res = []
    for imgID in findresult:
        if imgID == '':
            return
        query = QueryParser(Version.LUCENE_CURRENT, "name",
                            analyzer).parse(imgID)
        scoreDocs = searcher.search(query, 9).scoreDocs
        for scoreDoc in scoreDocs:
            doc = searcher.doc(scoreDoc.doc)
            try:
                res.append([
                    doc.get("name"),
                    doc.get("collect_num"),
                    doc.get("zhuliao").split(' '),
                    doc.get("zuofa").split('\n'),
                    doc.get("img_url"),
                    doc.get("url")
                ])
            except:
                pass
    return res
Ejemplo n.º 14
0
def search(filename):
    #print(query)
    cd = ColorDescriptor((8, 12, 3))
    query = cv2.imread(filename)
    query = cv2.resize(query, (416, 416))
    filepath = 'static/' + filename
    cv2.imwrite(filepath, query)
    features = cd.describe(query)
    searcher = Searcher()
    results = searcher.search(features)

    #cv2.imshow("Query", query)
    # loop over the results
    for (score, resultID) in results:
        # load the result image and display it
        #print(resultID)
        img = mongo.db.myImages.find({'filename': resultID}, {
            "_id": 0,
            "name": 0,
            "filename": 0
        })
        l = []
        for x in img:
            #print(x)
            x = x['images'][0]

            #print('hey')
            #print(x)
            fout = fs.get(x['imageID'])

            im = np.frombuffer(fout.read(), dtype=np.uint8)
            im = np.reshape(im, x['shape'])
        # cv2.imshow("Result", im)
        # cv2.waitKey(0)

    return results
Ejemplo n.º 15
0
	def main_search(self):
		cd = ColorDescriptor((8, 12, 3))

		# load the query image and describe it
		query = cv2.imread('test_dataset/'+self.name)
		features = cd.describe(query)

		# perform the search
		searcher = Searcher(self.file_path)
		results = searcher.search(features)

		# display the query
		cv2.imshow("Query",query)

		# loop over the results
		for (score, resultID) in results:
			# load the result image and display it
			result = cv2.imread(self.data_path + "/" + resultID)
			r=300.0/result.shape[1]
			dim=(300,int(result.shape[0]*r))
			resized = cv2.resize(result, dim, interpolation = cv2.INTER_AREA)
			cv2.imshow("RESULT", resized)
			cv2.waitKey(0)
			cv2.destroyAllWindows()	
Ejemplo n.º 16
0
    def main_search(self):
        cd = ColorDescriptor((8, 12, 3))

        # load the query image and describe it
        query = cv2.imread('test_dataset/' + self.name)
        features = cd.describe(query)

        # perform the search
        searcher = Searcher(self.file_path)
        results = searcher.search(features)

        # display the query
        cv2.imshow("Query", query)

        # loop over the results
        for (score, resultID) in results:
            # load the result image and display it
            result = cv2.imread(self.data_path + "/" + resultID)
            r = 300.0 / result.shape[1]
            dim = (300, int(result.shape[0] * r))
            resized = cv2.resize(result, dim, interpolation=cv2.INTER_AREA)
            cv2.imshow("RESULT", resized)
            cv2.waitKey(0)
            cv2.destroyAllWindows()
Ejemplo n.º 17
0
def query():
    if request.method == "POST":
        f = request.files["file"]

        if not (f and allowed_file(f.filename)):
            return jsonify({
                "error": 1001,
                "msg": "请检查上传的图片类型,仅限于png、PNG、jpg、JPG、bmp"
            })

        basepath = os.path.dirname(__file__)  # 当前文件所在路径

        # 注意:没有的文件夹一定要先创建,不然会提示没有该路径
        upload_path = os.path.join(basepath, "static/queries",
                                   secure_filename(f.filename))
        # upload_path = os.path.join(basepath, 'static/images','test.jpg')  #注意:没有的文件夹一定要先创建,不然会提示没有该路径
        f.save(upload_path)
        import cv2

        # 使用Opencv转换一下图片格式和名称
        img = cv2.imread(upload_path)
        cv2.imwrite(os.path.join(basepath, "static/queries", "test.jpg"), img)

        RESULTS_ARRAY = []
        SCORE_ARRAY = []
        cd = ColorDescriptor((8, 12, 3))
        features = get_features(cd, FEATURES, img)
        searcher = Searcher(INDEX)
        results = searcher.search(features, SEARCHER)
        # loop over the results, displaying the score and image name
        for (score, resultID) in results:
            RESULTS_ARRAY.append(resultID)
            SCORE_ARRAY.append(score)

        return render_template(
            "query_ok.html",
            results=(RESULTS_ARRAY[:5]),
            scores=(SCORE_ARRAY[:5]),
            name=f.filename,
        )

    return render_template("query.html")
Ejemplo n.º 18
0
def search():

    if request.method == "POST":

        RESULTS_ARRAY = []

        # get url
        image_url = request.form.get("img")

        try:
            # initialize the image descriptor
            cd = ColorDescriptor((8, 12, 3))

            import cv2

            image_url = "polydomino/" + image_url[1:]
            query = cv2.imread(image_url)
            features = get_features(cd, FEATURES, query)

            # perform the search
            searcher = Searcher(INDEX)
            results = searcher.search(features, SEARCHER)

            # loop over the results, displaying the score and image name
            for (score, resultID) in results:
                RESULTS_ARRAY.append({
                    "image": str(resultID),
                    "score": str(score)
                })

            # return success
            return jsonify(results=(RESULTS_ARRAY[:5]))

        except:

            # return error
            jsonify({"sorry": "Sorry, no results! Please try again."}), 500
Ejemplo n.º 19
0
import cv2
import json
import csv
from scipy.stats.mstats import kruskalwallis
"""
Indexes a set of images by corner and center using a HSV color histogram and stores indices. Requires colordescriptor.py.
"""
# 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())
dataset = 'Opistognathidae'
# initialize the color descriptor
cd = ColorDescriptor(
    (8, 12, 3))  # HSV binning -- 8 hue, 12 saturation, 3 value

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

kw = []

# loop over images
# for imagePath in glob.glob(args["dataset"] + "/*.jpg"):
for imagePath in glob.glob(dataset + "/*.jpg"):

    imageID = imagePath[imagePath.rfind("/") + 1:]
    image = cv2.imread(imagePath)

    # describe image
    features = cd.describe(image)
Ejemplo n.º 20
0
import argparse
import cv2
import time
# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--index", default='index.csv',
                help="Path to where the computed index will be stored")
ap.add_argument("-l", "--limit", default=10,
                help="Query result limit")
ap.add_argument("-d", "--dist", default='euclidean',
                help="Distance model")
ap.add_argument("-q", "--query", required=True,
                help="Path to the query image")
args = vars(ap.parse_args())

# initialize the image descriptor
cd = ColorDescriptor((8, 12, 3))

# load the query image and describe it
query = cv2.imread(args["query"])
features = cd.describe(query)

# perform the search
searcher = Searcher(args["index"])
results = searcher.search(features, int(args["limit"]), args["dist"])

# loop over the results
for (score, resultID) in results:
    # load the result image and display it
    print resultID
Ejemplo n.º 21
0
# import the necessary packages
from colordescriptor import ColorDescriptor
import os
import matplotlib.pyplot as plt
from datetime import datetime as d

# initialize the color descriptor
cd = ColorDescriptor()

dir_images = 'Corel'

imgs = os.listdir(dir_images)

# Set the timer
now = d.now()
current = now.strftime("%H:%M:%S")
print(current)

# Store imageID and LBP features

output = open("lbp_value.csv", "w")
for imgnm in imgs:
	img_rgb = plt.imread(os.path.join(dir_images,imgnm))
	imageID = imgnm
	features = cd.calculate_lbp(img_rgb)
    
	# write the features to file
	features = [str(f) for f in features]
	output.write("%s,%s\n" % (imageID, ",".join(features)))

output.close()
Ejemplo n.º 22
0
from colordescriptor import ColorDescriptor
import argparse
import glob
import cv2

# construct an argument parser
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 of file where the computed index will be stored")
# vars() return a dict, it can be retrieved as args[dataset]/args[index]
args = vars(ap.parse_args())

# in HSV, 8 bins for hue, 12 bins for saturation, 3 for values(brightness)
cd = ColorDescriptor((8, 12, 3))

# open output index file for writing
output = open(args["index"], "w")

# use glob to grab the image files in path and iterate them
for imagePath in glob.glob(args["dataset"] + "/*.jpg"):
    # extract the image ID(i.e. the unique filename)
    imageID = imagePath[imagePath.rfind('/') + 1 :]
    image = cv2.imread(imagePath)

    features = cd.describe(image)

    # write the features to file
    features = [str(f) for f in features]
    output.write("%s,%s\n" % (imageID, ",".join(features)))
Ejemplo n.º 23
0
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())

# initialize the image descriptor
#cd = ShapeDescriptor()
#cd = ZernikeMoments(50)
#cd = HogDescriptor()
cd = ColorDescriptor()
# load the query image and describe it
query = cv2.imread(args["query"])
query = cv2.cvtColor(query, cv2.COLOR_BGR2GRAY)
# pad the image with extra white pixels to ensure the
# edges of the pokemon are not up against the borders
# of the image
#query = cv2.copyMakeBorder(query, 15, 15, 15, 15,
#	cv2.BORDER_CONSTANT, value = 255)

# invert the image and threshold it
#thresh = cv2.bitwise_not(query)
#thresh[thresh > 0] = 255

# initialize the outline image, find the outermost
# contours (the outline) of the pokemone, then draw
Ejemplo n.º 24
0
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")
ap.add_argument("-m", "--mask", required = True,
	help = "Path to image mask (same size as images) to break into a grid")
args = vars(ap.parse_args())
 
print args
# initialize the color descriptor
cd = ColorDescriptor((8, 12, 3),args.mask)

# open the output index file for writing
output = open(args["index"], "w")

# use glob to grab the image paths and loop over them
for imagePath in glob.glob(args["dataset"] + "/*.png"):
	# extract the image ID (i.e. the unique filename) from the image
	# path and load the image itself
	imageID = imagePath[imagePath.rfind("/") + 1:]
	image = cv2.imread(imagePath)
 
	# describe the image
	features = cd.describe(image)
 
	# write the features to file
Ejemplo n.º 25
0
### --dataset: the path to our dog images directory
### --index: the output CSV file containing the image filename and the features associated with each image
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())

# Initialzie the color descriptor - Extract the features
cd = ColorDescriptor((8, 12, 3))  # (Hue, Saturation, Value)

# Write the extracted features into a CSV file
csv = open(args["index"], "w")

for imagePath in glob.glob(args["dataset"] + "/*.png"):

    # Assign a unique ID to the extracted images
    imageID = imagePath[imagePath.rfind("/") + 1:]
    image = cv2.imread(imagePath)

    features = cd.describe(image)

    features = [str(f) for f in features]
    csv.write("%s,%s\n" % (imageID, ",".join(features)))
Ejemplo n.º 26
0
from searcher import Searcher
import argparse
import cv2

# construct the argument parser and parse the arguments
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())

# initialize the image descriptor
cd = ColorDescriptor((8, 12, 3))

# load the query image and describe it
query = cv2.imread(args["query"])
features = cd.describe(query)

# perform the search
searcher = Searcher(args["index"])
results = searcher.search(features)

# display the query
cv2.imshow("Query", cd.image_resizer(query))


# loop over the results
for (score, resultID) in results:
Ejemplo n.º 27
0
import glob
import cv2

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())

cd = ColorDescriptor((8, 12, 3))

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

# use glob to grab the image paths and loop over them
for imagePath in glob.glob(args["dataset"] + "/*.png"):

    imageID = imagePath[imagePath.rfind("/") + 1:]
    image = cv2.imread(imagePath)

    # describe the image
    features = cd.describe(image)

    # write the features to file
    features = [str(f) for f in features]
    output.write("%s,%s\n" % (imageID, ",".join(features)))
Ejemplo n.º 28
0
from colordescriptor import ColorDescriptor
from searcher import Searcher
import argparse
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())

cd = ColorDescriptor((8, 12, 3))

query = cv2.imread(args["query"])
features = cd.describe(query)

searcher = Searcher(args["index"])
results = searcher.search(features)
query = cv2.resize(query, (960, 540))
cv2.namedWindow("Query", cv2.WINDOW_NORMAL)
cv2.imshow("Query", query)
cv2.waitKey(0)
for (score, resultID) in results:
    result = cv2.imread(args["result_path"] + "/" + resultID)
    #result = cv2.resize(result, (960, 540))
    cv2.namedWindow("Result", cv2.WINDOW_NORMAL)
    cv2.imshow("Result", result)
    #print(args["result_path"] + "/" + resultID)
    cv2.waitKey(0)
Ejemplo n.º 29
0
# import the necessary packages
from colordescriptor import ColorDescriptor
from searcher import Searcher
import cv2, numpy as np
import matplotlib.pyplot as plt
from datetime import datetime as d

# initialize the image descriptor
cd = ColorDescriptor()

# load the query image
query = cv2.imread('queries/3_301.jpg')

# Set the timer
now = d.now()
current = now.strftime("%H:%M:%S")
print(current)

# describe LBP features and perform the search
lbp_features = cd.calculate_lbp(query)
lbp_searcher = Searcher("lbp_value.csv")
lbp_results = lbp_searcher.search(lbp_features)
print(lbp_results)

# Set the timer
now = d.now()
current = now.strftime("%H:%M:%S")
print(current)

# Plot result images from LBP
Ejemplo n.º 30
0
from dbhelper import DBHelper
DB = DBHelper()

from sklearn.externals import joblib
from sklearn.preprocessing import scale

from utilities.generateSiftFeatures import generateSiftFeatures
from utilities.generateORBFeatures import generateORBFeatures

from utilities.readImage import readImage
from utilities.showImage import showImage
from utilities.getOpening import getOpening

# initialize the color descriptor
cd = ColorDescriptor((8, 12, 3))

def chi2_distance(feature_vector, features, eps = 1e-10):
    dists = []
    # compute the chi-squared distance
    for i in range(0,len(features)):
        try:
            d = 0.5 * np.sum([((a - b) ** 2) / (a + b + eps) for (a, b) in zip(feature_vector, features[i])])
            dists.append(d)
        except:
            print features[i], type(features[i])
    # return the chi-squared distance
    return np.asarray(dists)


Ejemplo n.º 31
0
"""

ap = argparse.ArgumentParser()
ap.add_argument("-d", "--dataset", required = True,
	help = "Path to the directory that contains the images to be indexed")
args = vars(ap.parse_args())

folderPath = args["dataset"]

if not os.path.exists(folderPath + '/Pass'):
	os.makedirs(folderPath + '/Pass')
if not os.path.exists(folderPath + '/Fail'):
	os.makedirs(folderPath + '/Fail')

# initialize the color descriptor
cd = ColorDescriptor((8, 12, 3)) # HSV binning -- 8 hue, 12 saturation, 3 value

features = []
ctrcorr = []
images = glob.glob(folderPath+'/*.jpg')

for pic in images:

	image = cv2.imread(pic)
	image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
	ctr = []

	temp = cd.describe(image)
	features.append(temp)

	for i in temp[0:4]:
Ejemplo n.º 32
0
from zernika import ZernikeMoments
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())

# initialize the Shape descriptor
cd = ColorDescriptor(21)

# open the output index file for writing
output = open(args["index"], "w")

# use glob to grab the image paths and loop over them
for imagePath in glob.glob(args["dataset"] + "/*.png"):
	# extract the image ID (i.e. the unique filename) from the image
	# path and load the image itself
	imageID = imagePath[imagePath.rfind("/") + 1:]
	image = cv2.imread(imagePath)

	# describe the image
	features = cd.describe()

	# write the features to file
# import the necessary packages
from colordescriptor import ColorDescriptor
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())

# initialize the color descriptor
cd = ColorDescriptor((4, 8, 2))

# open the output index file for writing
output = open(args["index"], "w")

# use glob to grab the image paths and loop over them
for imagePath in glob.glob(args["dataset"] + "/*.jpg"):
	# extract the image ID (i.e. the unique filename) from the image
	# path and load the image itself
	imageID = imagePath[imagePath.rfind("/") + 1:]
	image = cv2.imread(imagePath)

	# describe the image
	features = cd.describe(image)

	# write the features to file
Ejemplo n.º 34
0
                required=True,
                help="Path to the result path")
ap.add_argument(
    "-m",
    "--mask",
    required=True,
    help="Path to image mask (same size as images) to break into a grid")
ap.add_argument(
    "-g",
    "--gridsize",
    required=True,
    help="Dimension for a single width/height for the square grid mask")
args = vars(ap.parse_args())

# initialize the image descriptor
cd = ColorDescriptor((8, 12, 3), args["mask"], args["gridsize"])

# load the query image and describe it
query = cv2.imread(args["query"])
features = cd.describe(query)

# perform the search
searcher = Searcher(args["index"])
scores, image_names = searcher.search(features)

# display the query
cv2.imshow("Query", query)

# loop over the results
for x in range(0, len(scores)):
    resultID = image_names[x]
Ejemplo n.º 35
0
# -u = path to the image you want to upload
# -i = path to the csv index containing all feature vectors

from colordescriptor import ColorDescriptor
from searcher import Searcher
from imutils import build_montages
import argparse
import cv2

ap = argparse.ArgumentParser()
ap.add_argument("-i", "--index", type=str, default="index.csv")
ap.add_argument("-u", "--upload", required=True)
args = vars(ap.parse_args())

cd = ColorDescriptor((8, 12, 3))
upload = cv2.imread(args["upload"])
features = cd.describe(upload)
searcher = Searcher(args["index"])
results = searcher.search(features)

i = 0
locs = []
similars = []
for (score, resultID) in results:
    result = cv2.imread(resultID)
    if (i < 1):
        if score < 1.0:
            title = "Found: " + resultID
        else:
            title = "Not Found - Best Match: " + resultID