Python cv2.calcHist() Examples

The following are 30 code examples of cv2.calcHist(). 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: tracking.py    From OpenCV-Computer-Vision-Projects-with-Python with MIT License 8 votes vote down vote up
def _update_mean_shift_bookkeeping(self, frame, box_grouped):
        """Preprocess all valid bounding boxes for mean-shift tracking

            This method preprocesses all relevant bounding boxes (those that
            have been detected by both mean-shift tracking and saliency) for
            the next mean-shift step.

            :param frame: current RGB input frame
            :param box_grouped: list of bounding boxes
        """
        hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

        self.object_roi = []
        self.object_box = []
        for box in box_grouped:
            (x, y, w, h) = box
            hsv_roi = hsv[y:y + h, x:x + w]
            mask = cv2.inRange(hsv_roi, np.array((0., 60., 32.)),
                               np.array((180., 255., 255.)))
            roi_hist = cv2.calcHist([hsv_roi], [0], mask, [180], [0, 180])
            cv2.normalize(roi_hist, roi_hist, 0, 255, cv2.NORM_MINMAX)

            self.object_roi.append(roi_hist)
            self.object_box.append(box) 
Example #2
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 #3
Source File: color_classification.py    From deepgaze with MIT License 6 votes vote down vote up
def addModelHistogram(self, model_frame, name=''):
        """Add the histogram to internal container. If the name of the object
           is already present then replace that histogram with a new one.

        @param model_frame the frame to add to the model, its histogram
            is obtained and saved in internal list.
        @param name a string representing the name of the model.
            If nothing is specified then the name will be the index of the element.
        """
        if(self.hist_type=='HSV'): model_frame = cv2.cvtColor(model_frame, cv2.COLOR_BGR2HSV)
        elif(self.hist_type=='GRAY'): model_frame = cv2.cvtColor(model_frame, cv2.COLOR_BGR2GRAY)
        elif(self.hist_type=='RGB'): model_frame = cv2.cvtColor(model_frame, cv2.COLOR_BGR2RGB)
        hist = cv2.calcHist([model_frame], self.channels, None, self.hist_size, self.hist_range)
        hist = cv2.normalize(hist, hist).flatten()
        if name == '': name = str(len(self.model_list))
        if name not in self.name_list:
            self.model_list.append(hist)
            self.name_list.append(name)
        else:
            for i in range(len(self.name_list)):
                if self.name_list[i] == name:
                    self.model_list[i] = hist
                    break 
Example #4
Source File: object_detection_using_color.py    From Hands-On-Machine-Learning-with-OpenCV-4 with MIT License 6 votes vote down vote up
def capture_histogram(path_of_sample):

    # read the image
    color = cv2.imread(path_of_sample)

    # convert to HSV
    color_hsv = cv2.cvtColor(color, cv2.COLOR_BGR2HSV)

    # compute the histogram
    object_hist = cv2.calcHist([color_hsv],      # image
                               [0, 1],           # channels
                               None,             # no mask
                               [180, 256],       # size of histogram
                               [0, 180, 0, 256]  # channel values
                               )

    # min max normalization
    cv2.normalize(object_hist, object_hist, 0, 255, cv2.NORM_MINMAX)

    return object_hist 
Example #5
Source File: dat.py    From pyCFTrackers with MIT License 6 votes vote down vote up
def get_foreground_background_probs(frame,obj_rect,num_bins,bin_mapping=None):
    frame=frame.astype(np.uint8)

    surr_hist = cv2.calcHist([frame],[0, 1, 2], None, [num_bins,num_bins,num_bins],
                             [0, 256, 0, 256, 0, 256])
    x,y,w,h=obj_rect
    if x+w>frame.shape[1]-1:
        w=(frame.shape[1]-1)-x
    if y+h>frame.shape[0]-1:
        h=(frame.shape[0]-1)-y
    x=int(max(x,0))
    y=int(max(y,0))
    obj_win=frame[y:y+h+1,x:x+w+1]

    obj_hist = cv2.calcHist([obj_win], [0, 1, 2], None, [num_bins, num_bins, num_bins], [0, 256, 0, 256, 0, 256])
    prob_lut = (obj_hist + 1) / (surr_hist + 2)
    prob_map = None
    if bin_mapping is not None:
        frame_bin = cv2.LUT(frame, bin_mapping).astype(np.int64)
        prob_map = prob_lut[frame_bin[:, :, 0], frame_bin[:, :, 1], frame_bin[:, :, 2]]

    return prob_lut,prob_map 
Example #6
Source File: color_classification.py    From deepgaze with MIT License 6 votes vote down vote up
def returnHistogramComparisonArray(self, image, method='intersection'):
        """Return the comparison array between all the model and the input image.

        The highest value represents the best match.
        @param image the image to compare
        @param method the comparison method.
            intersection: (default) the histogram intersection (Swain, Ballard)
        @return a numpy array containg the comparison value between each pair image-model
        """
        if(self.hist_type=='HSV'): image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
        elif(self.hist_type=='GRAY'): image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        elif(self.hist_type=='RGB'): image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        comparison_array = np.zeros(len(self.model_list))
        image_hist = cv2.calcHist([image], self.channels, None, self.hist_size, self.hist_range)
        image_hist = cv2.normalize(image_hist, image_hist).flatten()
        counter = 0
        for model_hist in self.model_list:
            comparison_array[counter] = self.returnHistogramComparison(image_hist, model_hist, method=method)
            counter += 1
        return comparison_array 
Example #7
Source File: camshift_object_tracker.py    From automl-video-ondevice with Apache License 2.0 6 votes vote down vote up
def calculate_roi_hist(self, frame):
    """Calculates region of interest histogram.

    Args:
      frame: The np.array image frame to calculate ROI histogram for.
    """
    (x, y, w, h) = self.box
    roi = frame[y:y + h, x:x + w]

    hsv_roi = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV)
    mask = cv2.inRange(hsv_roi, np.array((0., 60., 32.)),
                       np.array((180., 255., 255.)))
    roi_hist = cv2.calcHist([hsv_roi], [0, 1], mask, [180, 255],
                            [0, 180, 0, 255])
    cv2.normalize(roi_hist, roi_hist, 0, 255, cv2.NORM_MINMAX)
    self.roi_hist = roi_hist

  # Run this every frame 
Example #8
Source File: Sorter.py    From DeepFaceLab with GNU General Public License v3.0 6 votes vote down vote up
def sort_by_hist_dissim(input_path):
    io.log_info ("Sorting by histogram dissimilarity...")

    img_list = []
    trash_img_list = []
    for filepath in io.progress_bar_generator( pathex.get_image_paths(input_path), "Loading"):
        filepath = Path(filepath)

        dflimg = DFLIMG.load (filepath)

        image = cv2_imread(str(filepath))

        if dflimg is not None and dflimg.has_data():
            face_mask = LandmarksProcessor.get_image_hull_mask (image.shape, dflimg.get_landmarks())
            image = (image*face_mask).astype(np.uint8)

        img_list.append ([str(filepath), cv2.calcHist([cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)], [0], None, [256], [0, 256]), 0 ])

    img_list = HistDissimSubprocessor(img_list).run()

    io.log_info ("Sorting...")
    img_list = sorted(img_list, key=operator.itemgetter(2), reverse=True)

    return img_list, trash_img_list 
Example #9
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 #10
Source File: functional.py    From albumentations with MIT License 6 votes vote down vote up
def _equalize_pil(img, mask=None):
    histogram = cv2.calcHist([img], [0], mask, [256], (0, 256)).ravel()
    h = [_f for _f in histogram if _f]

    if len(h) <= 1:
        return img.copy()

    step = np.sum(h[:-1]) // 255
    if not step:
        return img.copy()

    lut = np.empty(256, dtype=np.uint8)
    n = step // 2
    for i in range(256):
        lut[i] = min(n // step, 255)
        n += histogram[i]

    return cv2.LUT(img, np.array(lut)) 
Example #11
Source File: hist.py    From PyCV-time with MIT License 5 votes vote down vote up
def hist_curve(im):
    h = np.zeros((300,256,3))
    if len(im.shape) == 2:
        color = [(255,255,255)]
    elif im.shape[2] == 3:
        color = [ (255,0,0),(0,255,0),(0,0,255) ]
    for ch, col in enumerate(color):
        hist_item = cv2.calcHist([im],[ch],None,[256],[0,256])
        cv2.normalize(hist_item,hist_item,0,255,cv2.NORM_MINMAX)
        hist=np.int32(np.around(hist_item))
        pts = np.int32(np.column_stack((bins,hist)))
        cv2.polylines(h,[pts],False,col)
    y=np.flipud(h)
    return y 
Example #12
Source File: rgbhistogram.py    From pyimagesearch with GNU General Public License v3.0 5 votes vote down vote up
def describe(self, image):
        hist = cv2.calcHist([image], [0,1,2], None,
                self.bins, [0,256,0,256,0,256])
        hist = cv2.normalize(hist)

        return hist.flatten() 
Example #13
Source File: Sorter.py    From DeepFaceLab with GNU General Public License v3.0 5 votes vote down vote up
def process_data(self, data):
            filepath = Path(data[0])

            try:
                dflimg = DFLIMG.load (filepath)

                if dflimg is None or not dflimg.has_data():
                    self.log_err (f"{filepath.name} is not a dfl image file")
                    return [ 1, [str(filepath)] ]

                bgr = cv2_imread(str(filepath))
                if bgr is None:
                    raise Exception ("Unable to load %s" % (filepath.name) )

                gray = cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY)
                if self.faster:
                    source_rect = dflimg.get_source_rect()
                    sharpness = mathlib.polygon_area(np.array(source_rect[[0,2,2,0]]).astype(np.float32), np.array(source_rect[[1,1,3,3]]).astype(np.float32))
                else:
                    face_mask = LandmarksProcessor.get_image_hull_mask (gray.shape, dflimg.get_landmarks())     
                    sharpness = estimate_sharpness( (gray[...,None]*face_mask).astype(np.uint8) )

                pitch, yaw, roll = LandmarksProcessor.estimate_pitch_yaw_roll ( dflimg.get_landmarks(), size=dflimg.get_shape()[1] )

                hist = cv2.calcHist([gray], [0], None, [256], [0, 256])
            except Exception as e:
                self.log_err (e)
                return [ 1, [str(filepath)] ]

            return [ 0, [str(filepath), sharpness, hist, yaw, pitch ] ]

        #override 
Example #14
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 #15
Source File: color_histogram.py    From Mastering-OpenCV-4-with-Python with MIT License 5 votes vote down vote up
def hist_color_img(img):
    """Calculates the histogram for a three-channel image"""

    histr = []
    histr.append(cv2.calcHist([img], [0], None, [256], [0, 256]))
    histr.append(cv2.calcHist([img], [1], None, [256], [0, 256]))
    histr.append(cv2.calcHist([img], [2], None, [256], [0, 256]))
    return histr


# Create the dimensions of the figure and set title: 
Example #16
Source File: rgbhistogram.py    From pyimagesearch with GNU General Public License v3.0 5 votes vote down vote up
def describe(self, image):
		# compute a 3D histogram in the RGB colorspace,
		# then normalize the histogram so that images
		# with the same content, but either scaled larger
		# or smaller will have (roughly) the same histogram
		hist = cv2.calcHist([image], [0, 1, 2],
			None, self.bins, [0, 256, 0, 256, 0, 256])
		hist = cv2.normalize(hist)

		# return out 3D histogram as a flattened array
		return hist.flatten() 
Example #17
Source File: hist.py    From PyCV-time with MIT License 5 votes vote down vote up
def hist_lines(im):
    h = np.zeros((300,256,3))
    if len(im.shape)!=2:
        print "hist_lines applicable only for grayscale images"
        #print "so converting image to grayscale for representation"
        im = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
    hist_item = cv2.calcHist([im],[0],None,[256],[0,256])
    cv2.normalize(hist_item,hist_item,0,255,cv2.NORM_MINMAX)
    hist=np.int32(np.around(hist_item))
    for x,y in enumerate(hist):
        cv2.line(h,(x,0),(x,y),(255,255,255))
    y = np.flipud(h)
    return y 
Example #18
Source File: hearthstone_auto.py    From hearthstone_script- with MIT License 5 votes vote down vote up
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 #19
Source File: color_histogram_equalization.py    From Mastering-OpenCV-4-with-Python with MIT License 5 votes vote down vote up
def hist_color_img(img):
    """Calculates the histogram for a three-channel image"""

    histr = []
    histr.append(cv2.calcHist([img], [0], None, [256], [0, 256]))
    histr.append(cv2.calcHist([img], [1], None, [256], [0, 256]))
    histr.append(cv2.calcHist([img], [2], None, [256], [0, 256]))
    return histr 
Example #20
Source File: FaceBlurring.py    From ImageProcessingProjects with MIT License 5 votes vote down vote up
def camshift_track(prev, box, termination):
    hsv = cv2.cvtColor(prev,cv2.COLOR_BGR2HSV)
    x,y,w,h = box
    roi = prev[y:y+h, x:x+w]
    hist = cv2.calcHist([roi], [0], None, [16], [0, 180])
    cv2.normalize(hist, hist, 0, 255, cv2.NORM_MINMAX)
    backProj = cv2.calcBackProject([hsv], [0], hist, [0, 180], 1)
    (r, box) = cv2.CamShift(backProj, tuple(box), termination)
    return box 
Example #21
Source File: dat.py    From pyCFTrackers with MIT License 5 votes vote down vote up
def get_adaptive_threshold(prob_map, obj_rect, config=DATConfig()):
    x,y,w,h=obj_rect
    w+=1
    w=int(min(prob_map.shape[1]-x,w))
    h+=1
    h=int(min(prob_map.shape[0]-y,h))
    obj_prob_map=prob_map[y:y+h,x:x+w]
    bins=21
    H_obj=cv2.calcHist([obj_prob_map],[0],None,[bins],[-0.025,1.025],accumulate=False)
    H_obj=H_obj/np.sum(H_obj)
    cum_H_obj=copy.deepcopy(H_obj)
    for i in range(1,cum_H_obj.shape[0]):
        cum_H_obj[i,0]+=cum_H_obj[i-1,0]
    H_dist=cv2.calcHist([prob_map],[0],None,[bins],[-0.025,1.025],accumulate=False)
    H_dist=H_dist-H_obj
    H_dist=H_dist/np.sum(H_dist)
    cum_H_dist=copy.deepcopy(H_dist)
    for i in range(1,cum_H_dist.shape[0]):
        cum_H_dist[i,0]+=cum_H_dist[i-1,0]
    k=np.zeros_like(cum_H_obj)
    for i in range(k.shape[0]-1):
        k[i,0]=cum_H_obj[i+1,0]-cum_H_obj[i,0]
    # not sure

    x=np.abs(cum_H_obj-(1-cum_H_dist))+(cum_H_obj<(1-cum_H_dist))+(1-k)
    i=np.argmin(x)
    #print(i)
    threshold=max(0.4,min(0.7,config.adapt_thresh_prob_bins[i]))
    return threshold 
Example #22
Source File: mccth_staple.py    From pyCFTrackers with MIT License 5 votes vote down vote up
def compute_histogram(self, patch, mask, n_bins):
        h, w, d = patch.shape
        assert h == mask.shape[0] and w == mask.shape[1]
        mask = mask.astype(np.uint8)
        histogram = cv2.calcHist([patch], [0, 1, 2], mask, [n_bins, n_bins, n_bins],
                                 [0, 256, 0, 256, 0, 256]) / np.count_nonzero(mask)
        return histogram 
Example #23
Source File: ldes.py    From pyCFTrackers with MIT License 5 votes vote down vote up
def get_color_space_hist(self,patch,n_bins):
        histogram=cv2.calcHist([patch.astype(np.uint8)],[0,1,2],None,[n_bins,n_bins,n_bins],[0,256,0,256,0,256])
        return histogram 
Example #24
Source File: staple.py    From pyCFTrackers with MIT License 5 votes vote down vote up
def compute_histogram(self, patch, mask, n_bins):
        h, w, d = patch.shape
        assert h == mask.shape[0] and w == mask.shape[1]
        mask = mask.astype(np.uint8)
        histogram = cv2.calcHist([patch], [0, 1, 2], mask, [n_bins, n_bins, n_bins],
                                 [0, 256, 0, 256, 0, 256]) / np.count_nonzero(mask)
        return histogram 
Example #25
Source File: test_monkey.py    From ATX with Apache License 2.0 5 votes vote down vote up
def test_features():
    from atx.drivers.android_minicap import AndroidDeviceMinicap
    cv2.namedWindow("preview")
    d = AndroidDeviceMinicap()

    # r, h, c, w = 200, 100, 200, 100
    # track_window = (c, r, w, h)
    # oldimg = cv2.imread('base1.png')
    # roi = oldimg[r:r+h, c:c+w]
    # hsv_roi = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV)
    # mask = cv2.inRange(hsv_roi, 0, 255)
    # roi_hist = cv2.calcHist([hsv_roi], [0], mask, [180], [0,180])
    # cv2.normalize(roi_hist, roi_hist, 0, 255, cv2.NORM_MINMAX)
    # term_cirt = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT,  10, 1)


    while True:
        try:
            w, h = d._screen.shape[:2]
            img = cv2.resize(d._screen, (h/2, w/2))
            cv2.imshow('preview', img)

            hist = cv2.calcHist([img], [0], None, [256], [0,256])
            plt.plot(plt.hist(hist.ravel(), 256))
            plt.show()
            # if img.shape == oldimg.shape:
            #     # hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
            #     # ret, track_window = cv2.meanShift(hsv, track_window, term_cirt)
            #     # x, y, w, h = track_window
            #     cv2.rectangle(img, (x, y), (x+w, y+h), 255, 2)
            #     cv2.imshow('preview', img)
            # # cv2.imshow('preview', img)
            cv2.waitKey(1)
        except KeyboardInterrupt:
            break

    cv2.destroyWindow('preview') 
Example #26
Source File: global.py    From image-classification-python with MIT License 5 votes vote down vote up
def fd_histogram(image, mask=None):
    # convert the image to HSV color-space
    image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
    # compute the color histogram
    hist  = cv2.calcHist([image], [0, 1, 2], None, [bins, bins, bins], [0, 256, 0, 256, 0, 256])
    # normalize the histogram
    cv2.normalize(hist, hist)
    # return the histogram
    return hist.flatten()

# get the training labels 
Example #27
Source File: sort.py    From faceswap with GNU General Public License v3.0 5 votes vote down vote up
def reload_images(self, group_method, img_list):
        """
        Reloads the image list by replacing the comparative values with those
        that the chosen grouping method expects.
        :param group_method: str name of the grouping method that will be used.
        :param img_list: image list that has been sorted by one of the sort
        methods.
        :return: img_list but with the comparative values that the chosen
        grouping method expects.
        """
        logger.info("Preparing to group...")
        if group_method == 'group_blur':
            filename_list, image_list = self._get_images()
            blurs = [self.estimate_blur(img) for img in image_list]
            temp_list = list(zip(filename_list, blurs))
        elif group_method == 'group_face_cnn':
            filename_list, image_list, landmarks = self._get_landmarks()
            temp_list = list(zip(filename_list, landmarks))
        elif group_method == 'group_face_yaw':
            filename_list, image_list, landmarks = self._get_landmarks()
            yaws = [self.calc_landmarks_face_yaw(mark) for mark in landmarks]
            temp_list = list(zip(filename_list, yaws))
        elif group_method == 'group_hist':
            filename_list, image_list = self._get_images()
            histograms = [cv2.calcHist([img], [0], None, [256], [0, 256]) for img in image_list]
            temp_list = list(zip(filename_list, histograms))
        else:
            raise ValueError("{} group_method not found.".format(group_method))

        return self.splice_lists(img_list, temp_list) 
Example #28
Source File: FingerDetection.py    From Finger-Detection-and-Tracking with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def hand_histogram(frame):
    global hand_rect_one_x, hand_rect_one_y

    hsv_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    roi = np.zeros([90, 10, 3], dtype=hsv_frame.dtype)

    for i in range(total_rectangle):
        roi[i * 10: i * 10 + 10, 0: 10] = hsv_frame[hand_rect_one_x[i]:hand_rect_one_x[i] + 10,
                                          hand_rect_one_y[i]:hand_rect_one_y[i] + 10]

    hand_hist = cv2.calcHist([roi], [0, 1], None, [180, 256], [0, 180, 0, 256])
    return cv2.normalize(hand_hist, hand_hist, 0, 255, cv2.NORM_MINMAX) 
Example #29
Source File: ImageHistogram.py    From Finger-Detection-and-Tracking with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def main():
    image = cv2.imread("../data/4.1.03.tiff", 1)
    image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

    red_hist = cv2.calcHist([image_rgb], [0], None, [256], [0, 255])
    green_hist = cv2.calcHist([image_rgb], [1], None, [256], [0, 255])
    blue_hist = cv2.calcHist([image_rgb], [2], None, [256], [0, 255])

    # Histogram using Matplotlib
    plt.subplot(3, 1, 1)
    plt.hist(image.ravel(), 256, [0, 255])
    plt.xlim([0, 255])
    plt.title("Image Histogram using Matplotlib")

    # Histogram using Numpy
    plt.subplot(3, 1, 2)
    histogram, _ = np.histogram(image.ravel(), 256, [0, 255])
    plt.plot(histogram, color='r')
    plt.xlim([0, 255])
    plt.title("Image Histogram using Numpy")

    # Histogram using Numpy
    plt.subplot(3, 1, 3)
    plt.plot(red_hist, color='r')
    plt.xlim([0, 255])
    plt.title("Image Histogram using OpenCV")

    plt.show() 
Example #30
Source File: HistogramEqualization.py    From Finger-Detection-and-Tracking with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def main():
    image = cv2.imread("../data/4.1.03.tiff", 1)
    image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

    red, green, blue = cv2.split(image_rgb)

    eq_red_image = cv2.equalizeHist(red)
    eq_green_image = cv2.equalizeHist(green)
    eq_blue_image = cv2.equalizeHist(blue)

    red_hist = cv2.calcHist([red], [0], None, [256], [0, 255])
    green_hist = cv2.calcHist([green], [0], None, [256], [0, 255])
    blue_hist = cv2.calcHist([blue], [0], None, [256], [0, 255])

    eq_red_hist = cv2.calcHist([eq_red_image], [0], None, [256], [0, 255])
    eq_green_hist = cv2.calcHist([eq_green_image], [0], None, [256], [0, 255])
    eq_blue_hist = cv2.calcHist([eq_blue_image], [0], None, [256], [0, 255])

    channels_images = [red_hist, green_hist, blue_hist]
    equalized_images = [eq_red_hist, eq_green_hist, eq_blue_hist]

    # Channels Histogram
    for i in range(3):
        plt.subplot(4, 1, i + 1)
        plt.plot(channels_images[i], color='g')
        plt.xlim([0, 255])

    plt.show()

    # Channels Equalized Histogram
    for i in range(3):
        plt.subplot(3, 1, i + 1)
        plt.plot(equalized_images[i], color='b')
        plt.xlim([0, 255])

    plt.show()