本文整理匯總了Python中cv2.compareHist方法的典型用法代碼示例。如果您正苦於以下問題:Python cv2.compareHist方法的具體用法?Python cv2.compareHist怎麽用?Python cv2.compareHist使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類cv2
的用法示例。
在下文中一共展示了cv2.compareHist方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: sort_hist
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import compareHist [as 別名]
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
示例2: sort_hist_dissim
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import compareHist [as 別名]
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
示例3: piece_added_or_subtracted
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import compareHist [as 別名]
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'
示例4: process_data
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import compareHist [as 別名]
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
示例5: get_image_difference
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import compareHist [as 別名]
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
示例6: add_results
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import compareHist [as 別名]
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 ------- ====================
示例7: run
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import compareHist [as 別名]
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
示例8: histcmp_intersect
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import compareHist [as 別名]
def histcmp_intersect(self, histA, histB):
return cv2.compareHist(histA,histB,cv2.HISTCMP_INTERSECT)
示例9: hist_similarity
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import compareHist [as 別名]
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
示例10: get_avg_score_hist
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import compareHist [as 別名]
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)
示例11: returnHistogramComparison
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import compareHist [as 別名]
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
示例12: detect_and_return_probability
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import compareHist [as 別名]
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)
# 敵方嘲諷隨從
示例13: sort
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import compareHist [as 別名]
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)
示例14: sort
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import compareHist [as 別名]
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)
示例15: compareHist
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import compareHist [as 別名]
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)