def search(Image): idealBins = (8, 12, 3) # 设定HSV的bins kps = 100 # 打开图片,由于图名可能为中文,不能用imread queryImage = cv2.imdecode(np.fromfile(Image, dtype=np.uint8), -1) # 初始化颜色特征提取器和结构特征提取器 colorDescriptor = color_descriptor.ColorDescriptor(idealBins) structureDescriptor = structure_descriptor.StructureDescriptor(kps) colorIndexPath = "colorindex.csv" structureIndexPath = "structureindex.csv" #获得目标图片的颜色特征和结构特征 queryFeatures = colorDescriptor.describe(queryImage) queryStructures = structureDescriptor.describe(queryImage) # 初始化搜索器并进行搜索 imageSearcher = searcher.Searcher(colorIndexPath, structureIndexPath) searchResults = imageSearcher.search(queryFeatures, queryStructures) result = [] for imageName, score in searchResults: #queryResult = cv2.imread(resultPath + "/" + imageName) result.append(imageName) return result
def __init__(self): self.list_of_img_ids = os.listdir("./dataset") ## Color Histogram # ColorHist for Train # self.color_hist_searcher = searcher.Searcher("indexfull.csv") # ColorHist for Test self.color_hist_searcher = searcher.Searcher("indextest.csv") ## Visual Keyword from_vis_keyword_dataset_img_file = open( "visual_keyword_des_dataset_images.txt", "r") self.list_surf_des = pickle.load( from_vis_keyword_dataset_img_file) # initialize ## Visual Concept # For train set # self.vconcept_img_vectors = vconcept.load_visual_concept_img_vectors("semanticpickle.txt") # For test set self.vconcept_img_vectors = vconcept.load_visual_concept_img_vectors( "semantictestpickle.txt") ## Text retrieval & Visual Concept (Text) # self.postings_path = "trainset_text_tags_postings.txt" self.postings_path = "testset_text_tags_postings.txt" self.visual_concept_classes = text_engine.load_visual_concept_classes()
def index(): if request.method == 'POST': file = request.files['query_img'] img = Image.open(file.stream) # PIL image uploaded_img_path = "static/query/" + file.filename img.save(uploaded_img_path) idealBins = (8, 12, 3) idealDimension = (16, 16) colorDescriptor = color_descriptor.ColorDescriptor(idealBins) structureDescriptor = structure_descriptor.StructureDescriptor( idealDimension) queryImage = cv2.imread(uploaded_img_path) colorIndexPath = "static/color_index.csv" structureIndexPath = "static/structure_index.csv" resultPath = "static/dataset" queryFeatures = colorDescriptor.describe(queryImage) queryStructures = structureDescriptor.describe(queryImage) imageSearcher = searcher.Searcher(colorIndexPath, structureIndexPath) searchResults = imageSearcher.search(queryFeatures, queryStructures) return render_template('index.html', query_path=uploaded_img_path, scores=searchResults) else: return render_template('index.html')
def __init__(self): """Constructor. Raises: Exception: ROS node does not exist """ argvs = sys.argv argc = len(argvs) # Initialize if not (argc != 5 or argc != 7): raise Exception('Not enough arguments') self.output_path = argvs[1] self.log_dir_path = argvs[2] self.main_func_path = argvs[3] self.fop = file_operator.FileOperator(self.output_path) self.convert_file_path, self.data_file_path = self.fop._getWorkFilesPath( ) self.logger = cfs_logger.CfsLogger(self.log_dir_path) self.searcher = searcher.Searcher() self.topic_manager = topic_manager.TopicManager( self.convert_file_path, self.data_file_path) self.conv = converter.Converter(self.output_path, self.convert_file_path, self.data_file_path, self.fop, self.logger, self.topic_manager) self.nh_name = None
def search(self, image): # cd = colordescriptor.ColorDescriptor((8, 12, 3)) # cd = colordescriptor.ColorDescriptor((8, 4, 4)) cd = graydescriptor.GrayDescriptor((256)) #load the query image and describe it query = cv2.imread(image) features = cd.describe(query) print("query image features extracted") #perform the search # s = searcher.Searcher("color_index.csv") s = searcher.Searcher("gray_index.csv") results = s.search(features) print("search finished") """for (result, idd) in results: cv2.imshow("Result", result) cv2.waitKey(0)""" return results
def find_name(queryImage): idealBins = (8, 12, 3) idealDimension = (16, 16) colorDescriptor = color_descriptor.ColorDescriptor(idealBins) #掩模处理后的直方图 structureDescriptor = structure_descriptor.StructureDescriptor( idealDimension) #HSV色彩空间的矩阵 #queryImage = cv2.imread("query.jpg") colorIndexPath = os.path.abspath("colorindex") structureIndexPath = os.path.abspath("structureindex") queryFeatures = colorDescriptor.describe(queryImage) #掩模处理后的直方图 queryStructures = structureDescriptor.describe(queryImage) #HSV色彩空间的矩阵 imageSearcher = searcher.Searcher(colorIndexPath, structureIndexPath) searchResults = imageSearcher.search(queryFeatures, queryStructures) result = [] #图片名称所在的列表 for imageName, score in searchResults: result.append(imageName) return result
def __init__(self, args): self.clusters = dict() self.tracks = [] self.gallery = [] self.vehicle_size = defaultdict(int) self.track_vehicle = dict() self.topk = args.topk self.reid_threshold = args.reid_threshold self.max_cluster_size = args.max_cluster_size if args.faiss_search_type == 'dot product': self.searcher = searcher.Searcher2(feat_len=256) elif args.faiss_search_type == 'euclid': self.searcher = searcher.Searcher(feat_len=256) with open(args.model_config_path, 'r') as f: args = json.load(fp=f) self.model = Model(args) self.model.restore()
def main(): bot = searcher.Searcher((FIRST_EVALUATOR, SECOND_EVALUATOR)) bot.board.display() bot.expand() if len(sys.argv) == 1: sys.argv.append("black") if sys.argv[1] == "white": computer_move_timed(bot) while not bot.board.is_over(): if sys.argv[1] != "bot": if bot.board.is_over(): break human_move(bot) if bot.board.is_over(): break computer_move_timed(bot) print "Final score:", " - ".join(map(str, bot.board.score()))
information_label.config(text=information) evaluation = "Evaluation: {}".format( round(bot.game_tree.score / 100, 2)) evaluation_label.config(text=evaluation) if __name__ == "__main__": # Suppress the useless output... :D import os import sys sys.stdout = open(os.devnull, "w") bot = searcher.Searcher((EVALUATOR, EVALUATOR)) bot.update_scores() WINDOW_SIZE = 4 button = Tkinter.Button(root, font=("Comic Sans MS", 10, "bold"), foreground="red", width=2 * WINDOW_SIZE - 1, text="QUIT", command=quit) button.grid(row=0, column=7) function_list = [] for row in xrange(8): for column in xrange(8):
ap.add_argument("-i", "--index", required=True, help="Path to storage directory") ap.add_argument("-q", "--query", required=True, help="Path to query directory") ap.add_argument("-r", "--result-path", required=True, help="Path to results directory") args = vars(ap.parse_args()) # initialize colour descriptor cd = colourdescriptor.ColourDescriptor((8, 12, 3)) # load query and get it's features query = cv2.imread(args["query"]) features = cd.describe(query) # perform search searcher = searcher.Searcher(args["index"]) results = searcher.search(features) # display query cv2.imshow("Query", query) # loop over results for (score, result_id) in results: result = cv2.imread(result_id) cv2.imshow("Result", result) cv2.waitKey(0)
import searcher as ac s = ac.Searcher(rulefile="../../test.txt") #s = ac.Searcher(imgfile="./compiled.gz") filename = "../../banned.txt" fp = open(filename, "r") content = fp.read() def callback(s, start, end, level): #v = from_buffer(s) print(s[start:end + 1], level) pass s.search("abcdefgh", 2, callback)
searchArgParser.add_argument("-r", "--resultpath", required=True, help="Path to the result path") searchArguments = vars(searchArgParser.parse_args()) idealBins = (8, 12, 3) idealDimension = (16, 16) colorDescriptor = color_descriptor.ColorDescriptor(idealBins) structureDescriptor = structure_descriptor.StructureDescriptor(idealDimension) queryImage = cv2.imread(searchArguments["query"]) colorIndexPath = searchArguments["colorindex"] structureIndexPath = searchArguments["structureindex"] resultPath = searchArguments["resultpath"] queryFeatures = colorDescriptor.describe(queryImage) queryStructures = structureDescriptor.describe(queryImage) imageSearcher = searcher.Searcher(colorIndexPath, structureIndexPath) searchResults = imageSearcher.search(queryFeatures, queryStructures) for imageName, score in searchResults: queryResult = cv2.imread(resultPath + "/" + imageName) cv2.imshow("Result Score: " + str(int(score)) + " (lower is better)", queryResult) cv2.waitKey(0) cv2.imshow("Query", queryImage) cv2.waitKey(0)
gr = grabber.Grabber() gr.start() gr.join() thread_list = [] each = len(gr.survey_number_list) / settings.THREAD_COUNT id_number = sys.argv[1] for thread_index in xrange(settings.THREAD_COUNT): start_index = each * thread_index end_index = start_index + each - 1 survey_numbers = gr.survey_number_list[start_index:end_index] sr = searcher.Searcher(id_number, survey_numbers) thread_list.append(sr) sr.start() last_survey_numbers = gr.survey_number_list[each * settings.THREAD_COUNT:] last_sr = searcher.Searcher(id_number, last_survey_numbers) thread_list.append(last_sr) last_sr.start() failed_numbers = [] for thread in thread_list: thread.join() for failed_number in thread.failed_numbers: failed_numbers.append(failed_number) while len(failed_numbers) != 0:
while not bot.board.is_over(): if sys.argv[1] != "bot": if bot.board.is_over(): break human_move(bot) if bot.board.is_over(): break computer_move_timed(bot) print "Final score:", " - ".join(map(str, bot.board.score())) if __name__ == "__main__": turn = 0 if STATS: import cProfile import pstats bot = searcher.Searcher(evaluator_ab.evaluate) cProfile.run('main()', 'main.profile') stats = pstats.Stats('main.profile') stats.strip_dirs().sort_stats('time').print_stats() else: main() if GRAPH: pylab.show()
def main(): DIR_PATH_NOTES = os.path.expanduser("~/Dropbox/tbrush_notes") PORT = 38906 dir_path = os.path.expanduser(DIR_PATH_NOTES) if not os.path.exists(dir_path): print("created directory:", dir_path) os.makedirs(dir_path) search_inst = searcher.Searcher(dir_path) app = flask.Flask(__name__) port = int(sys.argv[1]) if len(sys.argv) == 2 else PORT print('Starting httpserver on port', PORT) @app.route('/search', methods=['POST']) def search(): post_dict = request.get_json() query_string = post_dict['query'] selected_index = post_dict.get('selected_index') if selected_index is not None: selected_index = int(selected_index) print('searching for:', query_string) result_dict = search_inst.search(query_string, selected_index) print('results:', result_dict) return json.dumps(result_dict, indent=2) def monitor_filesystem(): class MyHandler(events.PatternMatchingEventHandler): patterns = ["*.txt"] def on_any_event(self, event): if event.event_type == 'moved' or event.event_type == 'deleted': search_inst.delete_path(event.src_path) if event.event_type == 'moved': search_inst.load_path(event.dest_path) if event.event_type == 'created' or event.event_type == 'modified': print('created:', event.src_path) search_inst.load_path(event.src_path) event_handler = MyHandler() observer = observers.Observer() observer.schedule(event_handler, path=DIR_PATH_NOTES, recursive=False) observer.start() print('monitoring:', DIR_PATH_NOTES) try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join() t = threading.Thread(target=monitor_filesystem) t.daemon = True # allow parent process to kill it t.start() app.jinja_env.auto_reload = True app.config['TEMPLATES_AUTO_RELOAD'] = True app.run(host='0.0.0.0', port=port, debug=(port != 80))
def __init__(self, parent=None): super(Interactive, self).__init__(parent) # work_directory = os.path.abspath(os.path.dirname(__file__)) work_directory = os.path.dirname(os.path.realpath(sys.argv[0])) self.data_directory = work_directory + '/data/' self.search = searcher.Searcher(self.data_directory)