def Disease_Detection(image_path): # initialize the image descriptor cd = ColorDescriptor((8, 12, 3)) # load the query image and describe it # query = cv2.imread(args["query"]) filenames = listdir(image_path) a = [filename for filename in filenames if filename.endswith('.png')] path = image_path + '/' + a[0] print(path) query = cv2.imread(path) print("query==", query) features = cd.describe(query) # perform the search #searcher = Searcher(args["index"]) searcher = Searcher("../index.csv") results = searcher.search(features) results.pop(0) print("==============", results) print() # disease_name = results[1][1].split("_")[0].split("\\")[1] #.... extracting disease name # print("**********",disease_name) return (results[1][1].split("_")[0]) # Disease_Detection('/home/vishal/Dropbox/ML/Plant_Disease_Detection/queries')
def find_similar(query): """ query (str): path to the img ex : queries2\img_231.jpg return list_img (list) : 3 paths of img similar """ # initialize list list_img = [] # initialize the image descriptor cd = ColorDescriptor((8, 12, 3)) # load the query image and describe it query = cv2.imread(query) features = cd.describe(query) # perform the search searcher = Searcher("index2.csv") results = searcher.search(features) # display the query # cv2.imshow("Query", query) # loop over the results for (score, resultID) in results: # add img to list list_img.append(str(resultID).replace("\\", "/")) return list_img
def check(limit): args = {"query": "queries/a.jpg", "index": "whpu.csv"} #初始化图像描述符 cd = ColorDescriptor((8, 12, 3)) #从磁盘读取待搜索图像 query = cv2.imread(args["query"]) #提取该图像的特征 features = cd.describe(query) #执行搜索 #使用提取到的特征进行搜索,返回经过排序后的结果列表 searcher = Searcher(args["index"]) results = searcher.search(features, limit) #显示出待搜索的图像 #cv2.imshow("Query", query) result_files_data = [] #遍历搜索结果,将相应的图像显示在屏幕上 for (score, resultID) in results: result = "dataset/" + resultID result_files_data.append([score, result]) return result_files_data
def search(): if request.method == "POST": RESULTS_ARRAY = [] # get url image_url = request.form.get('img') try: # initialize the image descriptor ird = ImageRetrieveDeep("", "") path_img = os.path.join(os.getcwd(), image_url[1:]) des = ird.r_mac_descriptor(path_img) # perform the search searcher = Searcher(des) results = searcher.search(des, "static/dataset_jpg", "descriptor") # 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[::-1][:10])) except: # return error jsonify({"sorry": "Sorry, no results! Please try again."}), 500
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)) # load the query image and describe it from skimage import io query = io.imread(image_url) features = cd.describe(query) # perform the search searcher = Searcher(INDEX) results = searcher.search(features) # 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[::-1][:3])) except: # return error jsonify({"sorry": "Sorry, no results! Please try again."}), 500
def search_results(filename, index_file): # load the query image and describe it query = cv2.imread(filename) features = cd.describe(query) # perform the search searcher = Searcher(index_file) results = searcher.search(features)
def show_results_imgs(self): if (self.count == 0 and self.tf_input.get() == ""): tkMessageBox.showwarning( "Alert", "Please enter a search term, or upload image.") else: if (self.filename == self.currFilename): self.isSameFile = True else: self.isSameFile = False # user now wants to commence the search; load frame for displaying results of query self.isUploadingImage = False # flush out old results self.result_img_frame.destroy() self.result_img_frame = Frame(self.master) self.result_img_frame.pack() flags = self.get_options() # print(flags) # perform the search searcher = Searcher("index.csv", "index_semantics.csv", "index_text.csv", "index_deeplearning.csv", flags, self.tf_input.get()) results = searcher.search(self.queryfeatures, self.querysemantics, self.querytext, self.querycategory) if (len(results) == 0): pass else: # show result pictures COLUMNS = 8 image_count = 0 for (score, resultID) in results: # load the result image and display it image_count += 1 r, c = divmod(image_count - 1, COLUMNS) im = Image.open(resultID) resized = im.resize((100, 100), Image.ANTIALIAS) tkimage = ImageTk.PhotoImage(resized) myvar = Label(self.result_img_frame, image=tkimage) myvar.image = tkimage myvar.grid(row=r, column=c) if (self.toLogResults): numRelevant = logResults.get_precision(self.queryImageCategory, results) print(numRelevant) self.currFilename = self.filename self.result_img_frame.mainloop()
def search(): if request.method == "POST": '''file = request.files['file'] filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) RESULTS_ARRAY = [] print(filename)''' RESULTS_ARRAY = [] # get url image_url = request.form.get('img') print(image_url) try: # initialize the image descriptor cd = ColorDescriptor((8, 12, 3)) # load the query image and describe it from skimage import io import cv2 #query = io.imread("/home/kene/Documents/PyImageSearch/3D Histogram Descriptor Method With Web Interface/app/"+image_url) query = cv2.imread("/home/kene/Documents/Projects/Image-Search-Engine/app/static/queries/"+image_url); #query = io.imread(image_url) #query = (query * 255).astype("uint8") #(r, g, b) = cv2.split(query) #query = cv2.merge([b, g, r]) #query = cv2.cvtColor(query, cv2.COLOR_BGR2RGB) features = cd.describe(query) # perform the search searcher = Searcher(INDEX) results = searcher.search(features) # 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[::-1][:101]), preview="queries/"+image_url) #resultSet=jsonify(results=(RESULTS_ARRAY[::-1][:5])) #return render_template('index.html', preview = "static/queries/"+filename, resultSet = jsonify(results=(RESULTS_ARRAY[::-1][:5]))) except Exception, e: print(str(e)) # return error return jsonify({"sorry": "Sorry, no results! Please try again."}), 500
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)) # load the query image and describe it from skimage import io import cv2 # query = io.imread(image_url) # query = (query * 255).astype("uint8") # (r, g, b) = cv2.split(query) # query = cv2.merge([b, g, r]) image_url = "app/" + image_url[1:] # print "图像url路径:", image_url # print os.getcwd() # print sys.path[0] query = cv2.imread(image_url) # print "读取成功!" features = cd.describe(query) # print "描述子生成成功" # perform the search searcher = Searcher(INDEX) results = searcher.search(features) # 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 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)) # load the query image and describe it from skimage import io import cv2 # query = io.imread(image_url) # query = (query * 255).astype("uint8") # (r, g, b) = cv2.split(query) # query = cv2.merge([b, g, r]) image_url = "app/" + image_url[1:] # print "图像url路径:", image_url # print os.getcwd() # print sys.path[0] query = cv2.imread(image_url) # print "读取成功!" features = cd.describe(query) # print "描述子生成成功" # perform the search searcher = Searcher(INDEX) results = searcher.search(features) # 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 predict(self,location): # initialize the image descriptor cd = ColorDescriptor((8, 12, 3)) print(location) query = cv2.imread(location) features = cd.describe(query) searcher = Searcher("index.csv") results = searcher.search(features) final_res = [] for (score, resultID) in results: final_res.append(resultID) print(score,resultID) return final_res[0]
def upload(): file = request.files['file'] print('upload', file) if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) if request.method == "POST": RESULTS_ARRAY = [] # get url try: # initialize the image descriptor cd = ColorDescriptor((8, 12, 3)) # load the query image and describe it from skimage import io filename = os.path.join(app.config['UPLOAD_FOLDER'], filename) print '###' + filename query = io.imread(filename) print 'shape' features = cd.describe(query) # perform the search searcher = Searcher(INDEX) results = searcher.search(features) # 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[::-1][:3]), file=file.filename) except: # return error return jsonify({"sorry": "Sorry, no results! Please try again."}), 500
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)) # load the query image and describe it from skimage import io import cv2 query = io.imread(image_url) # query = (query * 255).astype("uint8") # (r, g, b) = cv2.split(query) # query = cv2.merge([b, g, r]) # cv2.imshow("Image", query) query = cv2.cvtColor(query, cv2.COLOR_BGR2RGB) features = cd.describe(query) # perform the search searcher = Searcher(INDEX) results = searcher.search(features) # 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[::-1])) # return 'ok' except Exception as ex: template = "An exception of type {0} occurred. Arguments:\n{1!r}" message = template.format(type(ex).__name__, ex.args) print(message) return jsonify({"sorry": "Sorry, no results! Please try again."}), 500
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)) # load the query image and describe it from skimage import io import cv2 print("image_url ", image_url) path_img = os.path.join(os.getcwd(), image_url[1:]) query = cv2.imread(path_img, cv2.COLOR_BGR2RGB) print("describe") features = cd.describe(query) print("Searcher") # perform the search searcher = Searcher(INDEX) print("search") results = searcher.search(features) print(INDEX) print("image") # loop over the results, displaying the score and image name for (score, resultID) in results: RESULTS_ARRAY.append({ "image": str(resultID), "score": str(score) }) print("Before success") # return success return jsonify(results=(RESULTS_ARRAY[::-1][:3])) except: # return error jsonify({"sorry": "Sorry, no results! Please try again."}), 500
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)) # load the query image and describe it from skimage import io import cv2 query = cv2.imread( os.path.join(os.path.dirname(__file__), 'static/images/' + image_url)) features = cd.describe(query) # perform the search searcher = Searcher(INDEX) results = searcher.search(features) # 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[:101]), preview="images/" + image_url) except Exception as e: print(str(e)) # return error return jsonify({"sorry": "Sorry, no results! Please try again."}), 500
def func2(command): folder = 'target' command = os.path.join(folder, command) # initialize the image descriptor cd = ColorDescriptor((8, 12, 3)) # load the query image and describe it query = cv2.imread(command) features = cd.describe(query) # perform the search searcher = Searcher("index.csv") results = searcher.search(features) # loop over the results result = [] for (score, resultp) in results: url, imgname, imgurl = resultp doct = {"url": url, 'name': imgname, 'imgurl': imgurl} result.append(doct) return result
def Disease_Detection(image_path): # initialize the image descriptor cd = ColorDescriptor((8, 12, 3)) # load the query image and describe it # query = cv2.imread(args["query"]) filelist = [ file for file in os.listdir(image_path) if file.endswith('.png') ] query = cv2.imread(image_path + filelist[0]) # query = cv2.imread( 'D:\\projects\\Plant_Disease_Detection\\dataset\\CollarRot_1.png' ) features = cd.describe(query) # perform the search #searcher = Searcher(args["index"]) searcher = Searcher(image_path + "/index.csv") results = searcher.search(features) results.pop(0) disease_name = results[1][1].split("_")[0].split("\\")[ 1] #.... extracting disease name return (disease_name)
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", query) c = 0 r = [] # loop over the results for (score, resultID) in results: # load the result image and display it result = cv2.imread(args["result_path"] + "/" + resultID) cv2.imshow("Result", result) r.append(result) cv2.waitKey(0) os.chdir( 'C:\\Users\\Aaron Stone\\Desktop\\Minor Repository\\search-engine\\results' )
# 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",query) # loop over the results for (score, resultID) in results: # load the result image and display it result = cv2.imread(args["result_path"] + "/" + resultID) cv2.imshow("Result", result) cv2.waitKey(0)
#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('monkey.jpg') #%% features = cd.describe(query) #%% # perform the search searcher = Searcher('index.csv') results = searcher.search(features) # display the query cv2.imwrite("Query.jpg", query) #%% # loop over the results import os path = 'C:/Users/User/Documents/fyp/image-extraction/module1/results' length = len(results) with open("C:/Users/User/Documents/fyp/image-extraction/module1/results/candidate.txt","w") as f1: for i, (score,resultID) in zip(range(length),results): x = resultID.split(".") y = str(x[0]) + '.txt' with open(y) as f:
def call_back(imagepath): print(imagepath) # if status.get() == 1: e = tk.StringVar() out = tk.Label(root, textvariable=e) out.grid(row=8, columnspan=5) global i # i += 1 e.set(imagepath) # nowtime = os.popen('date') # print(nowtime.read()) # command like : python search.py --index index.csv --query queries/108100.png --result-path dataset imageID = imagepath[imagepath.rfind("\\") + 1:] querypath = "queries/" + imageID # load the query image and describe it query = cv2.imread(querypath) features = cd.describe(query) # perform the search searcher = Searcher("index.csv") results = searcher.search(features) # display the query # cv2.imshow("Query", query) # testpath = r"C:\Users\DYL18\Desktop\Graduation_design\vacation-image-search-engine\dataset\103500.png" ''' a = Image.open(testpath) b = resize(w_box, h_box, a) d = ImageTk.PhotoImage(image=b) # imageOutput = tk.Button(root,text = "haha") imageOutput = tk.Button(root, image=d, width=w_box, height=h_box) imageOutput.grid(row=12, column=0, rowspan=6) print("hahaha") ''' j = 0 k = 0 #destroy all of button or label here: global tk_button for a in tk_button: print(a) a.destroy() tk_button = [] ''' global button_num if button_num > 0: button_num = button_num - 1 while button_num != 0: tk_button[button_num].destroy() button_num = button_num - 1 # for but in button_num: # tk_button[but].destroy() button_num = 0 ''' # tk_im_path = [] # loop over the results for (score, resultID) in results: # load the result image and display it # path2 = "dataset" + "\\" + resultID path2 = datapath + "\\" + resultID print(path2) pil_image2 = Image.open(path2) # tk_im_path.append(pil_image2) pil_image_resized2 = resize(w_box, h_box, pil_image2) # photograph = ImageTk.PhotoImage(pil_image_resized2) tk_im.append(ImageTk.PhotoImage(pil_image_resized2)) imageOutput = tk.Button(root, image=tk_im[j], width=w_box, height=h_box) tk_button.append(imageOutput) tk_button[j].image = tk_im[j] tk_button[j].grid(row=int(9 + (k * 8)), column=int(j % 6), rowspan=6) # button_num = button_num + 1 # imageOutput.configure(image=tk_im[j]) # imageOutput.image = tk_im[j] # imageOutput.grid(row=int(9 + (k * 8)), column=int(j % 6), rowspan=6) # imageOutput.destroy() j = j + 1 k = int(j / 6) # root.update_idletasks() for a in tk_button: print(a) '''
def call_back(self, imagepath): print(imagepath) e = tk.StringVar() out = tk.Label(self.canvas2, textvariable=e) # self.canvas.create_window(300, 200, window=out) # self.canvas.grid(row=0, column=0) global i e.set(imagepath) # command like : python search.py --index index.csv --query queries/108100.png --result-path dataset imageID = imagepath[imagepath.rfind("\\") + 1:] # * querypath = "queries/" + imageID # querypath = self.root.queryfolder + "\\" + imageID querypath = self.root.indexcsvpath + imageID querypath = imagepath print("Attention !! this is the query path: ") print(querypath) # load the query image and describe it query = cv2.imread(querypath) print(query) # 调试 cv2.imshow("Result", query) cv2.waitKey(0) features = cd.describe(query) # perform the search # searcher = Searcher("index.csv") p = self.root.indexcsvpath + "index.csv" searcher = Searcher(p) results = searcher.search(features) j = 0 k = 0 # destroy all of button or label here: global button_list for a in button_list: print(a) a.destroy() button_list = [] # tk_im_path = [] # loop over the results for (score, resultID) in results: # load the result image and display it # 必须要选择数据集才能得到正确的datafolder路径并因此得出结果 path2 = self.root.datafolder + "\\" + resultID print(path2) pil_image2 = Image.open(path2) pil_image_resized2 = self.resize(w_box, h_box, pil_image2) # tk_im.append(ImageTk.PhotoImage(pil_image_resized2)) # imageOutput = tk.Button(root, image=tk_im[j], width=w_box, height=h_box) a = ImageTk.PhotoImage(pil_image_resized2) imageOutput = tk.Button(self.canvas2, image=a, width=w_box, height=h_box) button_list.append(imageOutput) # button_list[j].image = tk_im[j] button_list[j].image = a self.canvas2.create_window(150+250*(int(j % 6)), 100 + 250 * k, window=button_list[j]) # self.canvas2.create_window(350 + 250 * k, 100*(int(j % 6)), window=button_list[j]) # button_list[j].grid(row=int(9 + (k * 8)), column=int(j % 6), rowspan=6) j = j + 1 k = int(j / 6) for a in button_list: print(a)
import numpy as np import argparse import cPickle 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 we just indexed") ap.add_argument("-i", "--index", required = True, help = "Path to where we stored our index") args = vars(ap.parse_args()) # load the index and initialize our searcher index = cPickle.loads(open(args["index"]).read()) searcher = Searcher(index) # loop over images in the index -- we will use each one as # a query image for (query, queryFeatures) in index.items(): # perform the search using the current query results = searcher.search(queryFeatures);print("query :"+str(query)) # load the query image and display it path = str(query)#args["dataset"] + "/%s" % (query) queryImage = cv2.imread(path) cv2.imshow("Query", queryImage) print "query: %s" % (query) # initialize the two montages to display our results -- # we have a total of 25 images in the index, but let's only # display the top 10 results; 5 images per montage, with # images that are 400x166 pixels
def searchVideo(query): index = "index.csv" # initialize the image descriptor cd = ColorDescriptor((8, 12, 3)) # load the query video and describe it temp = "/home/ankita/btp7/CBVR/temp" i = 0 # print path_video cap = cv2.VideoCapture("uploadedFiles/" + query) if cap.isOpened(): rval, frame = cap.read() else: rval = False # print rval # print query while rval: rval, frame = cap.read() if not rval: break name = str(i) + '.png' cv2.imwrite(os.path.join(temp, name), frame) i = i + 1 if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() avg_int = [] no_frames = i # print no_frames for img in glob.glob(temp + '/*png'): image = io.imread(img) im = rgb2gray(image) avg_int.append(np.mean(im)) # print(np.mean(im)) # for i in avg_int: # print i diff = [avg_int[p + 1] - avg_int[p] for p in range(len(avg_int) - 1)] # y = diff # plt.plot(y) # plt.show() # print diff.index(min(diff)) name1 = temp + '/' + str(diff.index(min(diff))) + '.png' # print diff.index(max(diff)) name2 = temp + '/' + str(diff.index(max(diff))) + '.png' # image1 = cv2.imread(name1) # save_name = fold +"#"+ video.split('.')[0]+'_1.png' # cv2.imwrite(os.path.join(data ,save_name ), image1) # image2 = cv2.imread(name2) # save_name = fold +"#"+ video.split('.')[0]+'_2.png' # cv2.imwrite(os.path.join(data ,save_name ), image2) query_image = cv2.imread(name2) for the_file in os.listdir(temp): file_path = os.path.join(temp, the_file) try: if os.path.isfile(file_path): os.unlink(file_path) #elif os.path.isdir(file_path): shutil.rmtree(file_path) except Exception as e: print(e) # query = cv2.imread(args["query"]) features = cd.describe(query_image) # perform the search searcher = Searcher(index) results = searcher.search(features) result_images = [] # display the query # cv2.imshow("Query", query_image) # loop over the results path_video = [] # path_video.append("uploadedFiles/"+query) for (score, resultID) in results: # load the result image and display it result = cv2.imread("data/" + resultID) result_images.append(result) fold = resultID.split('#')[0] x = resultID.split('#')[1] name = x.rsplit('_', 1)[0] # print fold arr = os.listdir('data/' + fold) ext = arr[0].split('.')[1] video = 'data/' + fold + '/' + name + '.' + ext path_video.append(video) # print video # cv2.imshow("Result", result) # cv2.waitKey(0) return path_video
def main(): images=glob.glob("uploads\\*.jpg") for image_file in images: # img_bgr = cv2.imread(image_file) # height, width, channel = img_bgr.shape # img = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2GRAY) # k=img.shape[0] # l=img.shape[1] # original = np.zeros((height, width,3), np.uint8) # encrypted = np.zeros((height, width,3), np.uint8) # decrypted = np.zeros((height, width,3), np.uint8) # img_lbp = np.zeros((height, width,3), np.uint8) # enc_img_lbp = np.zeros((height, width,3), np.uint8) # randomnumber={} # for i in range (k):#traverses through height of the image # for j in range (l): #traverses through width of the image # # original[i,j]=img[i,j] # randomnumber[i,j]=np.random.randint(0,255) # # img_lbp[i, j] = lbp_calculated_pixel(img, i, j) # # Encryption # if(((randomnumber[i,j]>=128) and (img[i,j]>=128))): # encrypted[i,j]=img[i,j]-128 # temp=img[i,j]-128 # elif(((randomnumber[i,j]<128) and (img[i,j]<128))): # encrypted[i,j]=img[i,j] # temp=img[i,j] # elif(((randomnumber[i,j]>=128) and (img[i,j]<128))): # encrypted[i,j]=img[i,j]+128 # temp=img[i,j]+128 # else: # encrypted[i,j]=img[i,j] # temp=img[i,j] # # enc_img_lbp[i, j] = lbp_calculated_pixel(img, i, j) DoG(image_file) key=cv2.imread('DoG\\'+image_file.split('\\')[1]) img1 = cv2.cvtColor(key, cv2.COLOR_BGR2GRAY) # cv2.imshow("k",img1) # cv2.waitKey(0) # cv2.destroyAllWindows() height, width, channel = key.shape k1=img1.shape[0] l1=img1.shape[1] key_lbp = np.zeros((height, width,3), np.uint8) for i in range (k1):#traverses through height of the image for j in range (l1): key_lbp[i, j] = lbp_calculated_pixel(img1, i, j) hist_lbp = cv2.calcHist([key_lbp], [0], None, [256], [0, 256]) features = [str(i)[1:-2] for i in hist_lbp] searcher = Searcher("index.csv") results = searcher.search(features) #saving encrypted image #print(image_file); # encrypt_image=Image.fromarray(encrypted) #imageID = image_file[image_file.rfind("/") + 1:] #encrypt_image.save("encryptedimages\\"+image_file.split('\\')[1]) # output.write("%s,%s\n" % (image_file.split('\\')[1],",".join(features))) #cv2.imshow("Query", img_bgr) for (score, resultID) in results: # load the result image and display it #print(resultID) result = cv2.imread("encryptedimages"+ "\\" + resultID.split(".")[0]+".bmp") random_re2=cv2.imread("random\\"+resultID.split(".")[0]+".bmp") random_re1 = cv2.cvtColor(random_re2, cv2.COLOR_BGR2GRAY) en_re1 = cv2.cvtColor(result, cv2.COLOR_BGR2GRAY) height, width, channel = result.shape k2=random_re1.shape[0] l2=random_re1.shape[1] decrypted = np.zeros((height, width,3), np.uint8) for i in range (k2):#traverses through height of the image for j in range (l2): if(((random_re1[i,j]<128) and (en_re1[i,j]<128))): decrypted[i,j]=en_re1[i,j] elif(((random_re1[i,j]>=128) and (en_re1[i,j]<128))): decrypted[i,j]=en_re1[i,j]+128 elif(((random_re1[i,j]>=128) and (en_re1[i,j]>=128))): decrypted[i,j]=en_re1[i,j]-128 else: decrypted[i,j]=en_re1[i,j] cv2.imwrite("resultimages\\"+resultID,decrypted) # cv2.imshow(resultID, result) # cv2.waitKey(0) # encrypt_image.save("resultimages\\"+image_file.split('\\')[1]) #output.close() # caluclate histogram and plot it # hist_lbp = cv2.calcHist([img_lbp], [0], None, [256], [0, 256]) # enc_hist_lbp = cv2.calcHist([enc_img_lbp], [0], None, [256], [0, 256]) end=time.time() print(end-start )
hog = cv2.HOGDescriptor(winSize, blockSize, blockStride, cellSize, nbins, derivAperture, winSigma, histogramNormType, L2HysThreshold, gammaCorrection, nlevels) queryFeatures = hog.compute(queryImage, winStride, padding, locations) eps = 1e-7 queryFeatures = queryFeatures.astype("float") queryFeatures /= (queryFeatures.sum() + eps) # load the index perform the search file = open(args["index"] + ".pkl", 'rb') index = pickle.load(file) searcher = Searcher(index) results = searcher.search(queryFeatures) # initialize the two montages to display our results -- # we have a total of 25 images in the index, but let's only # display the top 10 results; 5 images per montage, with # images that are 400x166 pixels montageA = np.zeros((166 * 5, 400, 3), dtype="uint8") montageB = np.zeros((166 * 5, 400, 3), dtype="uint8") # loop over the top ten results for j in range(0, 10): # grab the result (we are using row-major order) and # load the result image (score, imageName) = results[j] path = args["dataset"] + os.sep + "%s" % (imageName)
def searcher(): return Searcher(indexPath, verbose)
output.write(str(args["my_query"])+"\n") output.write(str(args["l5"])+"\n") elif(int(args["l0"]) == 5): output.write(str(args["l0"])+"\n") output.write(str(args["l1"])+"\n") output.write(str(args["l2"])+"\n") output.write(str(args["l3"])+"\n") output.write(str(args["l4"])+"\n") output.write(str(args["my_query"])+"\n") # output.write(str(features)+"\n") # perform the search #client = pymongo.MongoClient("localhost", 27017) #db = client.mm #row = db.index.find({ "tags" : args["tags"] }) searcher = Searcher() results = searcher.search(args["my_query"], 8, args["descript"]) # display the query #cv2.imshow("Query", query) #for (score, resultID) in results: #print(resultID) # loop over the results i = 0
def call_back(imagepath): print(imagepath) e = tk.StringVar() out = tk.Label(root, textvariable=e) out.grid(row=8, columnspan=5) global i e.set(imagepath) # command like : python search.py --index index.csv --query queries/108100.png --result-path dataset imageID = imagepath[imagepath.rfind("\\") + 1:] querypath = "queries/" + imageID # load the query image and describe it query = cv2.imread(querypath) features = cd.describe(query) # perform the search searcher = Searcher("index.csv") results = searcher.search(features) j = 0 k = 0 #destroy all of button or label here: global button_list for a in button_list: print(a) a.destroy() button_list = [] # tk_im_path = [] # loop over the results for (score, resultID) in results: # load the result image and display it path2 = datapath + "\\" + resultID print(path2) pil_image2 = Image.open(path2) pil_image_resized2 = resize(w_box, h_box, pil_image2) # tk_im.append(ImageTk.PhotoImage(pil_image_resized2)) # imageOutput = tk.Button(root, image=tk_im[j], width=w_box, height=h_box) a = ImageTk.PhotoImage(pil_image_resized2) imageOutput = tk.Button(root, image=a, width=w_box, height=h_box) button_list.append(imageOutput) # button_list[j].image = tk_im[j] button_list[j].image = a button_list[j].grid(row=int(9 + (k * 8)), column=int(j % 6), rowspan=6) j = j + 1 k = int(j / 6) for a in button_list: print(a)
import argparse import cv2 import numpy from sklearn import datasets, svm, metrics import tensorflow==2.0 # 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 cd = ColorDescriptor((8, 12, 3)) query = cv2.imread(args["query"]) # load query image and describe it features = cd.describe(query) searcher = Searcher(args["index"]) # perform the search process results = searcher.search(features) cv2.imshow("Query", query) # display query for (score, resultID) in results: result = cv2.imread(args["result_path"] + "/" + resultID) # load the result cv2.imshow("Result", result) # display it cv2.waitKey(0)
def search(): # --- argument list --- # # construct the argument parse and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-prediction", "--prediction_file", required=True, help="path to the prediction file to be parsed") ap.add_argument("-exif", "--exif_file", required=True, help="path to the exif file to be parsed") # mode to search for guns or just objects ap.add_argument("-s", "--search_list", type=str, default="gun", help="list of search items delimited by comma") ap.add_argument('-v', '--verbose', action='store_true', help="Print lots of debugging statements") ap.add_argument("-k", "--top_k", type=int, default=20, help="retrieve the top-k predictions, default is 20") ap.add_argument("-t", "--threshold", type=float, help="probability threshold value in decimals ex. 0.75, default is 0.50") args = vars(ap.parse_args()) # --- validation --- # # ensure that the arguments supplied are pathnames if not os.path.isfile(args["prediction_file"]): raise AssertionError("The --prediction_file command line argument should exist and should be write-able.") # ensure that the path is write-able or exists if not os.path.isfile(args["exif_file"]): raise AssertionError("The --exif_file command line argument should exist and should be write-able.") pred_file = args["prediction_file"] exif_file = args["exif_file"] verbose = False if args["verbose"]: verbose = True threshold = None if args["threshold"]: threshold = args["threshold"] top_k = 20 if args["top_k"]: top_k = args["top_k"] always_verbose = True # show argument list s = "[INFO] Argument List:\n" + "\n".join([("-->{}: {}".format(x, args[x])) for x in args]) log(s, always_verbose) # always display # TODO - list suggestion from imagenet 1000 classes # DEBUG: # args["search_list"] = "gun,water,SCUBA diver, van" mode, search_list = validate_search_items(args["search_list"]) log("[INFO] Starting to load prediction file {} and exif file {} ...".format(pred_file, exif_file), always_verbose) index_path = os.path.dirname(__file__) s = Searcher(index_path, verbose) image_list = [] image_path_list = [] ## --------------- prediction --------------- ## if 1 == mode: # guns image_list = s.search_gun(pred_file, top_k, threshold) elif 2 == mode: # others image_list = s.search_list(pred_file, search_list, top_k, threshold) else: print("[INFO] Dont waste my time, nothing to search so no results found") if len(image_list) > 0: image_path_list = list(map(lambda x: x[0], image_list)) if verbose: for img in image_list: log("\t{} | {} | {:.2f}%".format(img[0], img[1], float(img[2]) * 100), verbose) log("[INFO] Total images found: {}".format(len(image_path_list)), always_verbose) ## --------------- exif info --------------- ## exif_info = parse_exif(exif_file, image_path_list, verbose) log("[INFO] Total exif information: {}".format(len(exif_info)), always_verbose) # print("length exif_info=",len(exif_info)) # print(image_list) # TODO: Convert to json results log("[INFO] Completed Search ", always_verbose)
from pyimagesearch import logger conf = logger.Logger() # 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 we just indexed") ap.add_argument("-i", "--index", required=True, help="Path to where we stored our index") args = vars(ap.parse_args()) print 'start waiting:', time.strftime('%H:%M:%S') # load the index and initialize our searcher index = cPickle.loads(open(args["index"]).read()) searcher = Searcher(index) # loop over images in the index -- we will use each one as # a query image for (query, queryFeatures) in index.items(): # perform the search using the current query results = searcher.search(queryFeatures) # load the query image and display it path = args["dataset"] + "/%s" % (query) queryImage = cv2.imread(path) # cv2.imshow("Query", queryImage) print "query: %s" % (query) # # initialize the two montages to display our results -- # # we have a total of 25 images in the index, but let's only
# import the necessary packages from pyimagesearch.colordescriptor import ColorDescriptor from pyimagesearch.searcher import Searcher import cv2 query = raw_input("Query:") # initialize the image descriptor cd = ColorDescriptor((8, 12, 3)) # load the query image and describe it query = cv2.imread(query) features = cd.describe(query) # perform the search searcher = Searcher("index.csv") results = searcher.search(features) # display the query cv2.imshow("Query", query) # loop over the results for (score, result) in results: url,resultname,resulturl = result print url,resultname,resulturl
# load the query image and show it queryImage = cv2.imread(args["query"]) cv2.imshow("Query", queryImage) print("queryImage " + str(queryImage)) print "query: %s" % (args["query"]) # describe the query in the same way that we did in # index.py -- a 3D RGB histogram with 8 bins per # channel desc = RGBHistogram([8, 8, 8]) queryFeatures = desc.describe(queryImage) # load the index perform the search index = cPickle.loads(open(args["index"]).read()) searcher = Searcher(index) results = searcher.search(queryFeatures) # initialize the two montages to display our results -- # we have a total of 25 images in the index, but let's only # display the top 10 results; 5 images per montage, with # images that are 400x166 pixels montageA = np.zeros( (len(queryImage) * 5, len(queryImage[0]), 3), dtype="uint8") #np.zeros((166 * 5, 400, 3), dtype = "uint8") montageB = np.zeros( (len(queryImage) * 5, len(queryImage[0]), 3), dtype="uint8") #np.zeros((166 * 5, 400, 3), dtype = "uint8") # loop over the top ten results for j in xrange(0, 10):
def callback(file): args={'result_path': 'dataset', 'index': 'index.csv', 'query': ''} args['query']=file # # 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) # return results # display the query #cv2.imshow("Query", query) #loop over the results # count=0 # print "Note: lower % of matching shows maximum similarity." # for (score, resultID) in results: # # load the result image and display it # i=0 # total=100 # perc=int(score) # while(i<=perc): # total-=5+i; # i+=1 # print "Image "+resultID +" got "+str(total+5)+"% similarity and "+'%2.3f'%score+" score.." # result = cv2.imread(args["result_path"] + "/" + resultID) # cv2.imwrite("/home/venkat/Review/output/"+str(score)+" "+resultID, result) # count+=1 # print "Got "+str(count)+" similer results...." # root = Tk() # root.geometry('{}x{}'.format(1330, 760)) # root.title("Content Based Image Retrieval") # label=Label(root,text = 'Resultant similer images..') # label.bind() # c=0 # r=0 # path='/home/venkat/CBIR/dataset/' # output='/home/venkat/CBIR/' # print "Note: lower % of matching shows maximum similarity." # for (score, resultID) in results: # # load the result image and display it # i=0 # total=100 # perc=int(score) # while(i<=perc): # total-=5; # i+=1 # print "Image "+resultID +" got "+str(total)+"% similarity and "+'%2.3f'%score+" score.." # path1 = Image.open("/home/venkat/Review/dataset/"+resultID) # path1=path1.resize((250, 250),Image.ANTIALIAS) # img1 = ImageTk.PhotoImage(path1) # myvar=Label(root,image = img1) # myvar.image = img1 # myvar.grid(row=r,column=c) # c+=250 # if(c>1000): # r+=250 # c=0 # root.mainloop() # USAGE # python search.py --index index.csv --query queries/103100.png --result-path dataset