Python cv2.compareHist() Examples
The following are 19
code examples of cv2.compareHist().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
cv2
, or try the search function
.
Example #1
Source File: sort.py From faceswap with GNU General Public License v3.0 | 7 votes |
def sort_hist_dissim(self): """ Sort by image histogram dissimilarity """ logger.info("Sorting by histogram dissimilarity...") filename_list, image_list = self._get_images() scores = np.zeros(len(filename_list), dtype='float32') distance = cv2.HISTCMP_BHATTACHARYYA logger.info("Calculating histograms...") histograms = [cv2.calcHist([img], [0], None, [256], [0, 256]) for img in image_list] img_list = list(list(items) for items in zip(filename_list, histograms, scores)) logger.info("Comparing histograms...") img_list_len = len(img_list) for i in tqdm(range(0, img_list_len), desc="Comparing", file=sys.stdout): score_total = 0 for j in range(0, img_list_len): if i == j: continue score_total += cv2.compareHist(img_list[i][1], img_list[j][1], distance) img_list[i][2] = score_total logger.info("Sorting...") img_list = sorted(img_list, key=operator.itemgetter(2), reverse=True) return img_list
Example #2
Source File: Sorter.py From DeepFaceLab with GNU General Public License v3.0 | 6 votes |
def process_data(self, data): idx, pitch_yaw_img_list = data for p in range ( len(pitch_yaw_img_list) ): img_list = pitch_yaw_img_list[p] if img_list is not None: for i in range( len(img_list) ): score_total = 0 for j in range( len(img_list) ): if i == j: continue score_total += cv2.compareHist(img_list[i][2], img_list[j][2], cv2.HISTCMP_BHATTACHARYYA) img_list[i][3] = score_total pitch_yaw_img_list[p] = sorted(img_list, key=operator.itemgetter(3), reverse=True) return idx, pitch_yaw_img_list #override
Example #3
Source File: Square.py From DE3-ROB1-CHESS with Creative Commons Attribution 4.0 International | 6 votes |
def piece_added_or_subtracted (self): """ PUBLIC: piece_added_or_subtracted --------------------------------- returns 'added' if something has been added here, 'subtracted' if it seems that a piece has been subtracted """ #=====[ Step 1: get diffs from initial hist ]===== current_diff = cv2.compareHist (self.contents_histogram, self.unoccluded_histogram, 3) last_diff = cv2.compareHist (self.last_contents_histogram, self.unoccluded_histogram, 3) #=====[ Step 2: return whichever is greater ]===== if current_diff > last_diff: return 'entered' else: return 'exited'
Example #4
Source File: sort.py From faceswap with GNU General Public License v3.0 | 6 votes |
def sort_hist(self): """ Sort by image histogram similarity """ logger.info("Sorting by histogram similarity...") filename_list, image_list = self._get_images() distance = cv2.HISTCMP_BHATTACHARYYA logger.info("Calculating histograms...") histograms = [cv2.calcHist([img], [0], None, [256], [0, 256]) for img in image_list] img_list = list(zip(filename_list, histograms)) logger.info("Comparing histograms and sorting...") img_list_len = len(img_list) for i in tqdm(range(0, img_list_len - 1), desc="Comparing", file=sys.stdout): min_score = float("inf") j_min_score = i + 1 for j in range(i + 1, img_list_len): score = cv2.compareHist(img_list[i][1], img_list[j][1], distance) if score < min_score: min_score = score j_min_score = j (img_list[i + 1], img_list[j_min_score]) = (img_list[j_min_score], img_list[i + 1]) return img_list
Example #5
Source File: compare_photos.py From OpenCV-Python-Tutorial with MIT License | 6 votes |
def get_image_difference(image_1, image_2): # 这个函数不行 first_image_hist = cv2.calcHist([image_1], [0], None, [256], [0, 256]) second_image_hist = cv2.calcHist([image_2], [0], None, [256], [0, 256]) img_hist_diff = cv2.compareHist(first_image_hist, second_image_hist, cv2.HISTCMP_BHATTACHARYYA) img_template_probability_match = cv2.matchTemplate(first_image_hist, second_image_hist, cv2.TM_CCOEFF_NORMED)[0][0] img_template_diff = 1 - img_template_probability_match # taking only 10% of histogram diff, since it's less accurate than template method commutative_image_diff = (img_hist_diff / 10) + img_template_diff return commutative_image_diff
Example #6
Source File: color_classification.py From deepgaze with MIT License | 5 votes |
def returnHistogramComparison(self, hist_1, hist_2, method='intersection'): """Return the comparison value of two histograms. Comparing an histogram with itself return 1. @param hist_1 @param hist_2 @param method the comparison method. intersection: (default) the histogram intersection (Swain, Ballard) """ if cv2.__version__.split(".")[0] == '3': if(method=="intersection"): comparison = cv2.compareHist(hist_1, hist_2, cv2.HISTCMP_INTERSECT) elif(method=="correlation"): comparison = cv2.compareHist(hist_1, hist_2, cv2.HISTCMP_CORREL) elif(method=="chisqr"): comparison = cv2.compareHist(hist_1, hist_2, cv2.HISTCMP_CHISQR) elif(method=="bhattacharyya"): comparison = cv2.compareHist(hist_1, hist_2, cv2.HISTCMP_BHATTACHARYYA) else: raise ValueError('[DEEPGAZE] color_classification.py: the method specified ' + str(method) + ' is not supported.') else: if(method=="intersection"): comparison = cv2.compareHist(hist_1, hist_2, cv2.cv.CV_COMP_INTERSECT) elif(method=="correlation"): comparison = cv2.compareHist(hist_1, hist_2, cv2.cv.CV_COMP_CORREL) elif(method=="chisqr"): comparison = cv2.compareHist(hist_1, hist_2, cv2.cv.CV_COMP_CHISQR) elif(method=="bhattacharyya"): comparison = cv2.compareHist(hist_1, hist_2, cv2.cv.CV_COMP_BHATTACHARYYA) else: raise ValueError('[DEEPGAZE] color_classification.py: the method specified ' + str(method) + ' is not supported.') return comparison
Example #7
Source File: Sorter.py From DeepFaceLab with GNU General Public License v3.0 | 5 votes |
def process_data(self, data): i = data[0] score_total = 0 for j in range( 0, self.img_list_len): if i == j: continue score_total += cv2.compareHist(self.img_list[i][1], self.img_list[j][1], cv2.HISTCMP_BHATTACHARYYA) return score_total #override
Example #8
Source File: Sorter.py From DeepFaceLab with GNU General Public License v3.0 | 5 votes |
def process_data(self, data): img_list = [] for x in data: img = cv2_imread(x) img_list.append ([x, cv2.calcHist([img], [0], None, [256], [0, 256]), cv2.calcHist([img], [1], None, [256], [0, 256]), cv2.calcHist([img], [2], None, [256], [0, 256]) ]) img_list_len = len(img_list) for i in range(img_list_len-1): min_score = float("inf") j_min_score = i+1 for j in range(i+1,len(img_list)): score = cv2.compareHist(img_list[i][1], img_list[j][1], cv2.HISTCMP_BHATTACHARYYA) + \ cv2.compareHist(img_list[i][2], img_list[j][2], cv2.HISTCMP_BHATTACHARYYA) + \ cv2.compareHist(img_list[i][3], img_list[j][3], cv2.HISTCMP_BHATTACHARYYA) if score < min_score: min_score = score j_min_score = j img_list[i+1], img_list[j_min_score] = img_list[j_min_score], img_list[i+1] self.progress_bar_inc(1) return img_list #override
Example #9
Source File: Square.py From DE3-ROB1-CHESS with Creative Commons Attribution 4.0 International | 5 votes |
def get_occlusion_change_features (self): """ PUBLIC: get_occlusion_change_features ------------------------------------- returns a numpy array representing this square, optimized for discerning occlusion """ # return np.sum(np.abs(self.image_region_normalized - self.last_image_region_normalized)) return cv2.compareHist (self.contents_histogram, self.last_contents_histogram, 3)
Example #10
Source File: util.py From rabbitVE with GNU General Public License v3.0 | 5 votes |
def compareHist(a, b): a_hist = cv2.calcHist([a], [0], None, [256], [0, 256]) b_hist = cv2.calcHist([b], [0], None, [256], [0, 256]) return cv2.compareHist(a_hist,b_hist,cv2.HISTCMP_BHATTACHARYYA)
Example #11
Source File: util.py From rabbitVE with GNU General Public License v3.0 | 5 votes |
def sort(self): img_path = [x.path for x in os.scandir(self.from_path) if x.path.endswith("jpg") or x.path.endswith("png") or x.path.endswith("jpeg")] img_list = [ [img, cv2.calcHist([cv2.imread(img)], [0], None, [256], [0, 256])] for img in img_path ] img_list_len = len(img_list) for i in range(0, img_list_len - 1): min_score = float("inf") j_min_score = i + 1 for j in range(i + 1, len(img_list)): score = cv2.compareHist(img_list[i][1], img_list[j][1], cv2.HISTCMP_BHATTACHARYYA) if score < min_score: min_score = score j_min_score = j (img_list[i + 1], img_list[j_min_score]) = (img_list[j_min_score], img_list[i + 1]) for i, item in enumerate(img_list): img = cv2.imread(item[0]) path = os.path.join(self.to_path, "{}.png".format(i + 1)) cv2.imwrite(path, img) print("Save in ", path) # # def read_img(path): # return scipy.misc.imread(path)
Example #12
Source File: tool_sort.py From rabbitVE with GNU General Public License v3.0 | 5 votes |
def sort(self): img_path = [x.path for x in os.scandir(self.from_path) if x.path.endswith("jpg") or x.path.endswith("png") or x.path.endswith("jpeg")] img_list = [ [img, cv2.calcHist([cv2.imread(img)], [0], None, [256], [0, 256])] for img in img_path ] img_list_len = len(img_list) for i in range(0, img_list_len - 1): min_score = float("inf") j_min_score = i + 1 for j in range(i + 1, len(img_list)): score = cv2.compareHist(img_list[i][1], img_list[j][1], cv2.HISTCMP_BHATTACHARYYA) if score < min_score: min_score = score j_min_score = j (img_list[i + 1], img_list[j_min_score]) = (img_list[j_min_score], img_list[i + 1]) for i, item in enumerate(img_list): img = cv2.imread(item[0]) path = os.path.join(self.to_path, "{}.png".format(i + 1)) cv2.imwrite(path, img) print("Save in ", path)
Example #13
Source File: hearthstone_auto.py From hearthstone_script- with MIT License | 5 votes |
def detect_and_return_probability(pix, x1, y1, x2, y2): time.sleep(1.3) img = ImageGrab.grab(bbox=(x1, y1, x2, y2)) # x1,y1,x2,y2 img_np = np.array(img) im1 = cv.imread(pix) hist1 = cv.calcHist([im1], [0], None, [256], [0, 256]) hist2 = cv.calcHist([img_np], [0], None, [256], [0, 256]) return cv.compareHist(hist1, hist2, cv.HISTCMP_CORREL) # 敌方嘲讽随从
Example #14
Source File: sort.py From faceswap with GNU General Public License v3.0 | 5 votes |
def get_avg_score_hist(img1, references): """ Return the average histogram score between a face and reference image """ scores = [] for img2 in references: score = cv2.compareHist(img1, img2, cv2.HISTCMP_BHATTACHARYYA) scores.append(score) return sum(scores) / len(scores)
Example #15
Source File: auto.py From airtest with BSD 3-Clause "New" or "Revised" License | 5 votes |
def hist_similarity(image_1, image_2): """color hist based image similarity @param image_1: np.array(the first input image) @param image_2: np.array(the second input image) @return similarity: float(range from [0,1], the bigger the more similar) """ if image_1.ndim == 2 and image_2.ndim == 2: hist_1 = cv2.calcHist([image_1], [0], None, [256], [0.0, 255.0]) hist_2 = cv2.calcHist([image_2], [0], None, [256], [0.0, 255.0]) similarity = cv2.compareHist(hist_1, hist_2, cv2.cv.CV_COMP_CORREL) elif image_1.ndim == 3 and image_2.ndim == 3: """R,G,B split""" b_1, g_1, r_1 = cv2.split(image_1) b_2, g_2, r_2 = cv2.split(image_2) hist_b_1 = cv2.calcHist([b_1], [0], None, [256], [0.0, 255.0]) hist_g_1 = cv2.calcHist([g_1], [0], None, [256], [0.0, 255.0]) hist_r_1 = cv2.calcHist([r_1], [0], None, [256], [0.0, 255.0]) hist_b_2 = cv2.calcHist([b_2], [0], None, [256], [0.0, 255.0]) hist_g_2 = cv2.calcHist([g_2], [0], None, [256], [0.0, 255.0]) hist_r_2 = cv2.calcHist([r_2], [0], None, [256], [0.0, 255.0]) similarity_b = cv2.compareHist(hist_b_1,hist_b_2,cv2.cv.CV_COMP_CORREL) similarity_g = cv2.compareHist(hist_g_1,hist_g_2,cv2.cv.CV_COMP_CORREL) similarity_r = cv2.compareHist(hist_r_1,hist_r_2,cv2.cv.CV_COMP_CORREL) sum_bgr = similarity_b + similarity_g + similarity_r similarity = sum_bgr/3. else: gray_1 = cv2.cvtColor(image_1,cv2.cv.CV_RGB2GRAY) gray_2 = cv2.cvtColor(image_2,cv2.cv.CV_RGB2GRAY) hist_1 = cv2.calcHist([gray_1], [0], None, [256], [0.0, 255.0]) hist_2 = cv2.calcHist([gray_2], [0], None, [256], [0.0, 255.0]) similarity = cv2.compareHist(hist_1, hist_2, cv2.cv.CV_COMP_CORREL) return similarity #SIFT based similarity
Example #16
Source File: searchIndex.py From photomosaic with MIT License | 5 votes |
def histcmp_intersect(self, histA, histB): return cv2.compareHist(histA,histB,cv2.HISTCMP_INTERSECT)
Example #17
Source File: flann_index.py From image_space with Apache License 2.0 | 5 votes |
def run(query, k=10, mode='bruteforce'): if query.startswith('['): vec = json.loads(query) vec = np.array(vec, dtype=np.float32).reshape(1, 512) elif query in image_map: vec = image_map[query].reshape(1, 512) else: return {'error': 'Could not find data for image: ' + query} images = [] if mode == 'bruteforce': hist = vec.reshape(512) dists = [] for (i, file) in enumerate(image_files): dist = cv2.compareHist(hist, image_map[file], cv2.cv.CV_COMP_INTERSECT) dists.append((dist, i)) top = sorted(dists, reverse=True)[:int(k)] for distance, index in top: images.append({ 'id': image_files[index], 'features': image_map[image_files[index]].tolist(), 'distance': distance }) return images
Example #18
Source File: flann_index.py From image_space with Apache License 2.0 | 5 votes |
def run(query, k=10, mode='bruteforce'): if query.startswith('['): vec = json.loads(query) vec = np.array(vec, dtype=np.float32).reshape(1, 512) elif query in image_map: vec = image_map[query].reshape(1, 512) else: return {'error': 'Could not find data for image: ' + query} images = [] if mode == 'bruteforce': hist = vec.reshape(512) dists = [] for (i, file) in enumerate(image_files): dist = cv2.compareHist(hist, image_map[file], cv2.cv.CV_COMP_INTERSECT) dists.append((dist, i)) top = sorted(dists, reverse=True)[:int(k)] for distance, index in top: images.append({ 'id': image_files[index], 'features': image_map[image_files[index]].tolist(), 'distance': distance }) return images
Example #19
Source File: distance_bow_orb.py From douglas-quaid with GNU General Public License v3.0 | 5 votes |
def add_results(self, algo_conf: Algo_conf, pic_package_from: Dict, pic_package_to: Dict, answer: Dict) -> Dict: """ Add results to answer dict, depending on the algorithm name we want to compute Ex : Input {} -> Output {"BOW_ORB":{"name":"BOW_ORB", "distance":0.3,"decision":YES}} :param algo_conf: An algorithm configuration (to specify which algorithm to launch) :param pic_package_from: first picture dict :param pic_package_to: second picture dict :param answer: Current dict of algo_name to algo match (will be updated and returned) :return: a dict of algo_name to algo match """ algo_name = algo_conf.get('algo_name') # Depending on the type of # self.logger.debug(f"Comparison for BOW : {self.dist_conf.BOW_CMP_HIST} of {type(self.dist_conf.BOW_CMP_HIST)} " # and {distance_engine_conf.BOW_CMP_HIST.CORREL.name} of {type(distance_engine_conf.BOW_CMP_HIST.CORREL.name)}") if self.dist_conf.BOW_CMP_HIST == distance_engine_conf.BOW_CMP_HIST.CORREL.name: tmp_dist = 1 - cv2.compareHist(pic_package_from["BOW_ORB_DESCRIPTOR"], pic_package_to["BOW_ORB_DESCRIPTOR"], cv2.HISTCMP_CORREL) elif self.dist_conf.BOW_CMP_HIST == distance_engine_conf.BOW_CMP_HIST.BHATTACHARYYA.name: tmp_dist = cv2.compareHist(pic_package_from["BOW_ORB_DESCRIPTOR"], pic_package_to["BOW_ORB_DESCRIPTOR"], cv2.HISTCMP_BHATTACHARYYA) else: raise Exception('BOW ORB : HISTOGRAM COMPARISON MODE INCORRECT') # Add the distance as an AlgoMatch answer[algo_name] = sd.AlgoMatch(name=algo_name, distance=tmp_dist, decision=self.compute_decision_from_distance(algo_conf, tmp_dist)) return answer # ==================== ------ DECISIONS ------- ====================