Python cv2.HISTCMP_BHATTACHARYYA Examples

The following are 12 code examples of cv2.HISTCMP_BHATTACHARYYA(). 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 vote down vote up
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: compare_photos.py    From OpenCV-Python-Tutorial with MIT License 6 votes vote down vote up
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 #3
Source File: sort.py    From faceswap with GNU General Public License v3.0 6 votes vote down vote up
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 #4
Source File: Sorter.py    From DeepFaceLab with GNU General Public License v3.0 6 votes vote down vote up
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 #5
Source File: distance_bow_orb.py    From douglas-quaid with GNU General Public License v3.0 5 votes vote down vote up
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 ------- ==================== 
Example #6
Source File: sort.py    From faceswap with GNU General Public License v3.0 5 votes vote down vote up
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 #7
Source File: color_classification.py    From deepgaze with MIT License 5 votes vote down vote up
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 #8
Source File: tool_sort.py    From rabbitVE with GNU General Public License v3.0 5 votes vote down vote up
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 #9
Source File: util.py    From rabbitVE with GNU General Public License v3.0 5 votes vote down vote up
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 #10
Source File: util.py    From rabbitVE with GNU General Public License v3.0 5 votes vote down vote up
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: Sorter.py    From DeepFaceLab with GNU General Public License v3.0 5 votes vote down vote up
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 #12
Source File: Sorter.py    From DeepFaceLab with GNU General Public License v3.0 5 votes vote down vote up
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