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
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()
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()
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)
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)
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")
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
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)
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
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
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()
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
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)))
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)
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
### --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)))
# 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((8, 8, 3)) # 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"] + "/*.tiff"): # 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
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]
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
# 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