Exemplo n.º 1
0
 def use_image(self, im):
     self.kind = 'opencv'
     self.hist = cv.CreateHist([self.bins], cv.CV_HIST_ARRAY,
                               [self.value_range], 1)
     cv.CalcHist([im], self.hist)
     self.min_value, self.max_value, _, _ = cv.GetMinMaxHistValue(self.hist)
     return self
Exemplo n.º 2
0
def hs_histogram(src):
    # Convert to HSV
    hsv = cv.CreateImage(cv.GetSize(src), 8, 3)
    cv.CvtColor(src, hsv, cv.CV_BGR2HSV)

    # Extract the H and S plane
    h_plane = cv.CreateMat(src.rows, src.cols, cv.CV_8UC1)
    s_plane = cv.CreateMat(src.rows, src.cols, cv.CV_8UC1)
    cv.Split(hsv, h_plane, s_plane, None, None)
    planes = [h_plane, s_plane]

    h_bins = 30
    s_bins = 32
    hist_size = [h_bins, s_bins]
    # hue varies from 0 to 180
    h_ranges = [0, 180]
    # saturation varies from 0 to 255
    s_ranges = [0, 255]
    ranges = [h_ranges, s_ranges]
    scale = 10
    hist = cv.CreateHist([h_bins, s_bins], cv.CV_HIST_ARRAY, ranges, 1)
    cv.CalcHist([cv.GetImage(i) for i in planes], hist)
    (_, max_value, _, _) = cv.GetMinMaxHistValue(hist)

    hist_img = cv.CreateImage((h_bins * scale, s_bins * scale), 8, 3)

    for h in range(h_bins):
        for s in range(s_bins):
            bin_val = cv.QueryHistValue_2D(hist, h, s)
            intensity = cv.Round(bin_val * 255 / max_value)
            cv.Rectangle(hist_img, (h * scale, s * scale),
                         ((h + 1) * scale - 1, (s + 1) * scale - 1),
                         cv.RGB(intensity, intensity, intensity), cv.CV_FILLED)

    return hist_img
Exemplo n.º 3
0
    def __init__(self):
        rospy.init_node('cam_shift_node')
        
        self.ROI = rospy.Publisher("roi", RegionOfInterest, queue_size=1)

        """ Create the display window """
        self.cv_window_name = "Camshift Tracker"
        cv.NamedWindow(self.cv_window_name, 0)
        
        """ Create the cv_bridge object """
        self.bridge = CvBridge()
        
        """ Subscribe to the raw camera image topic """
        self.image_sub = rospy.Subscriber("/camera/image_raw", Image, self.image_callback)
        
        """ Set up a smaller window to display the CamShift histogram. """
        cv.NamedWindow("Histogram", 0)
        cv.MoveWindow("Histogram", 700, 10)
        cv.SetMouseCallback(self.cv_window_name, self.on_mouse)

        self.drag_start = None      # Set to (x,y) when mouse starts dragtime
        self.track_window = None    # Set to rect when the mouse drag finishes

        self.hist = cv.CreateHist([180], cv.CV_HIST_ARRAY, [(0,180)], 1 )
        self.backproject_mode = False
Exemplo n.º 4
0
    def run(self):
        hist = cv.CreateHist([180], cv.CV_HIST_ARRAY, [(0, 180)], 1)
        HOST, PORT = 'localhost', 5000
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.connect((HOST, PORT))
        while not self.quit:
            frame = cv.QueryFrame(self.capture)
            track_box = None
            self.update_hue(frame)

            # Compute back projection
            backproject = cv.CreateImage(cv.GetSize(frame), 8, 1)
            cv.CalcArrBackProject([self.hue], backproject, hist)
            if self.track_window and is_rect_nonzero(self.track_window):
                camshift = cv.CamShift(backproject, self.track_window,
                                       STOP_CRITERIA)
                (iters, (area, value, rect), track_box) = camshift
                self.track_window = rect

            if self.drag_start and is_rect_nonzero(self.selection):
                self.draw_mouse_drag_area(frame)
                self.recompute_histogram(hist)
            elif self.track_window and is_rect_nonzero(self.track_window):
                cv.EllipseBox(frame, track_box, cv.CV_RGB(0, 255, 255), 3,
                              cv.CV_AA, 0)

            if track_box:
                self.update_message(track_box)
                sock.send(json.dumps(self.message) + "\n")
            self.draw_target(frame, track_box)
            self.update_windows(frame, backproject, hist)
            self.handle_keyboard_input()
            track_box = None
Exemplo n.º 5
0
def get_2d_hist(planes, x_bins, y_bins, x_range_max=255, y_range_max=255):
    x_ranges = [0, x_range_max]
    y_ranges = [0, y_range_max]
    ranges = [x_ranges, y_ranges]
    hist = cv.CreateHist([x_bins, y_bins], cv.CV_HIST_ARRAY, ranges, 1)
    cv.CalcHist(planes, hist)
    return hist
Exemplo n.º 6
0
 def __init__(self, im, title=None, hist_size=256, color=cv.ScalarAll(0)):
     ranges = [[0, hist_size]]
     self.hist_size = hist_size
     self.color = color
     self.im = im
     self.hist_image = cv.CreateImage((320, 200), 8, 3)
     self.hist = cv.CreateHist([hist_size], cv.CV_HIST_ARRAY, ranges, 1)
     self.title = title
Exemplo n.º 7
0
def otsu(image, min_value, max_value):
    hist = cv.CreateHist([256], cv.CV_HIST_ARRAY, [[0, 255]],
                         1)  # Create a histogram variable
    cv.CalcHist([image], hist, 0, None)  # Calculate the histogram
    threshold, variance = calc_threshold(
        hist, min_value, max_value)  # Find the optimal threshold
    print threshold, variance
    return image, threshold, hist
Exemplo n.º 8
0
	def LoadHistogram(self, samples, channels, bins, ranges, factor):
		ch_numpy = [ samples[:, ch:(ch + 1)] for ch in channels ]
		ch_cvmat = map(cv.fromarray, ch_numpy)
		ch_image = map(cv.GetImage,  ch_cvmat)

		histogram = cv.CreateHist(bins, cv.CV_HIST_ARRAY, ranges, True)
		cv.CalcHist(ch_image, histogram, False)
		cv.NormalizeHist(histogram, factor)
		return histogram
Exemplo n.º 9
0
def make_histogram(imagefile):
    col = cv.LoadImageM(imagefile)
    gray = cv.CreateImage(cv.GetSize(col), cv.IPL_DEPTH_8U, 1)
    cv.CvtColor(col, gray, cv.CV_RGB2GRAY)

    hist = cv.CreateHist([NUM_BINS], cv.CV_HIST_ARRAY, [[0, 255]], 1)
    cv.CalcHist([gray], hist)
    cv.NormalizeHist(hist, 1.0)
    return hist
Exemplo n.º 10
0
def otsu_get_threshold(src):
    '''
    Find the optimal threshold value for a grey level image using Otsu's
    method.

    This is baised on Otsu's original paper published in IEEE Xplore: "A
    Threshold Selection Method from Gray-Level Histograms"

    '''

    if src.nChannels != 1:
        raise ValueError("Image must have one channel.")

    # Compute Histogram
    hist = cv.CreateHist([256], cv.CV_HIST_ARRAY, [[0, 255]], 1)
    cv.CalcHist([src], hist)

    # Convert to Probability Histogram
    cv.NormalizeHist(hist, 1)

    overall_moment = 0
    for t in xrange(256):
        overall_moment += t * cv.QueryHistValue_1D(hist, t)

    # Find the threshold t that gives the highest variance
    # Suffixes _b and _f mean background and foreground
    num_pixels = src.width * src.height
    weight_b = 0
    moment_b = 0
    highest_variance = 0
    best_threshold = 0
    for t in xrange(256):

        hist_value = cv.QueryHistValue_1D(hist, t)

        weight_b += hist_value
        weight_f = 1 - weight_b
        if weight_b == 0:
            continue
        if weight_f == 0:
            break

        moment_b += t * hist_value
        moment_f = overall_moment - moment_b

        mean_b = moment_b / weight_b
        mean_f = moment_f / weight_f

        variance_between = weight_b * weight_f * \
            (mean_b - mean_f) ** 2

        if variance_between >= highest_variance:
            highest_variance = variance_between
            best_threshold = t

    return best_threshold
Exemplo n.º 11
0
    def run(self):
        hist = cv.CreateHist([180], cv.CV_HIST_ARRAY, [(0, 180)], 1)
        backproject_mode = False
        while True:
            frame = cv.QueryFrame(self.capture)

            # Convert to HSV and keep the hue
            hsv = cv.CreateImage(cv.GetSize(frame), 8, 3)
            cv.CvtColor(frame, hsv, cv.CV_BGR2HSV)
            self.hue = cv.CreateImage(cv.GetSize(frame), 8, 1)
            print(self.hue)
            cv.Split(hsv, self.hue, None, None, None)

            # Compute back projection
            backproject = cv.CreateImage(cv.GetSize(frame), 8, 1)

            # Run the cam-shift
            cv.CalcArrBackProject([self.hue], backproject, hist)
            if self.track_window and is_rect_nonzero(self.track_window):
                crit = (cv.CV_TERMCRIT_EPS | cv.CV_TERMCRIT_ITER, 10, 1)
                (iters, (area, value, rect),
                 track_box) = cv.CamShift(backproject, self.track_window, crit)
                self.track_window = rect

            # If mouse is pressed, highlight the current selected rectangle
            # and recompute the histogram

            if self.drag_start and is_rect_nonzero(self.selection):
                sub = cv.GetSubRect(frame, self.selection)
                save = cv.CloneMat(sub)
                cv.ConvertScale(frame, frame, 0.5)
                cv.Copy(save, sub)
                x, y, w, h = self.selection
                cv.Rectangle(frame, (x, y), (x + w, y + h), (255, 255, 255))

                sel = cv.GetSubRect(self.hue, self.selection)
                cv.CalcArrHist([sel], hist, 0)
                (_, max_val, _, _) = cv.GetMinMaxHistValue(hist)
                if max_val != 0:
                    cv.ConvertScale(hist.bins, hist.bins, 255. / max_val)
            elif self.track_window and is_rect_nonzero(self.track_window):
                cv.EllipseBox(frame, track_box, cv.CV_RGB(255, 0, 0), 3,
                              cv.CV_AA, 0)

            if not backproject_mode:
                #frame=cv.Flip(frame)
                cv.ShowImage("CamShiftDemo", frame)
            else:
                cv.ShowImage("CamShiftDemo", backproject)
            cv.ShowImage("Histogram", self.hue_histogram_as_image(hist))

            c = cv.WaitKey(7)
            if c == 27:
                break
            elif c == ord("b"):
                backproject_mode = not backproject_mode
Exemplo n.º 12
0
 def calc_hist(self):
     self.hist = cv.CreateHist([self.h_bins, self.s_bins], cv.CV_HIST_ARRAY, self.ranges, 1)
     hsv = cv.CreateImage(cv.GetSize(self.background_noise[0]), 8, 3)
     h_plane = cv.CreateMat(self.background_noise[0].height, self.background_noise[0].width, cv.CV_8UC1)
     s_plane = cv.CreateMat(self.background_noise[0].height, self.background_noise[0].width, cv.CV_8UC1)
     for i in xrange(len(self.background_noise)):
         cv.CvtColor(self.background_noise[i], hsv, cv.CV_BGR2HSV)
         cv.Split(hsv, h_plane, s_plane, None, None)            
         planes = [h_plane, s_plane]#, s_plane, v_plane]
         cv.CalcHist([cv.GetImage(i) for i in planes], self.hist, True, self.mask)            
Exemplo n.º 13
0
def grey_histogram(img, nBins=64):
    """
    Returns a one dimension histogram for the given image
    The image is expected to have one channel, 8 bits depth
    nBins can be defined between 1 and 255 
    """
    hist_size = [nBins]
    h_ranges = [0, 255]
    hist = cv.CreateHist(hist_size, cv.CV_HIST_ARRAY, [[0, 255]], 1)
    cv.CalcHist([img], hist)

    return hist
Exemplo n.º 14
0
    def drawHistogram(self, image):
        w = 0.5
        n = 9
        gauss1d = np.exp(-0.5 * w / n * np.array(range(-(n - 1), n, 2))**2)
        gauss1d /= sum(gauss1d)

        hist_size = 180
        hist = cv.CreateHist([hist_size], cv.CV_HIST_ARRAY, [[0, 256]], 1)
        cv.CvtColor(image, self.HSV, cv.CV_BGR2HSV)
        cv.Split(self.HSV, self.B, self.G, self.R, None)

        channels = self.B, self.G, self.R
        _red = cv.Scalar(255, 0, 0, 0)
        _green = cv.Scalar(0, 255, 0, 0)
        _blue = cv.Scalar(0, 0, 255, 0)
        _white = cv.Scalar(255, 255, 255, 0)
        _trans = cv.Scalar(0, 0, 0, 255)
        values = _blue, _green, _red

        positions = (0, (self.Ihist.height + 10), 2 * self.Ihist.height + 20)

        for ch, colour, Y in zip(channels, values, positions):
            cv.CalcHist([ch], hist, 0, None)
            cv.Set(self.Ihist, _trans)
            bin_w = cv.Round(float(self.Ihist.width) / hist_size)
            # min_value, max_value, pmin, pmax = cv.GetMinMaxHistValue(hist)

            X = self.HSV.width - self.Ihist.width
            rect = (X, Y, self.Ihist.width, self.Ihist.height)

            hist_arr = [cv.GetReal1D(hist.bins, i) for i in range(hist_size)]
            hist_arr = np.convolve(gauss1d, hist_arr, 'same')

            cv.SetImageROI(image, rect)
            hist_arr *= self.Ihist.height / max(hist_arr)
            for i, v in enumerate(hist_arr):
                cv.Rectangle(self.Ihist, (i * bin_w, self.Ihist.height),
                             ((i + 1) * bin_w, self.Ihist.height - round(v)),
                             colour, -1, 8, 0)

            diffs = np.diff(hist_arr, 1)
            for i, v in enumerate(diffs):
                if v > 1 and diffs[i - 1] * diffs[i] <= 0:
                    cv.Rectangle(self.Ihist, (i * bin_w, self.Ihist.height),
                                 ((i + 1) * bin_w,
                                  self.Ihist.height - round(hist_arr[i])),
                                 _white, -1, 8, 0)

            cv.AddWeighted(image, 1 - self.hist_visibility, self.Ihist,
                           self.hist_visibility, 0.0, image)

        cv.ResetImageROI(image)
Exemplo n.º 15
0
def hs_histogram(src, patch):
    # Convert to HSV
    hsv = cv.CreateImage(cv.GetSize(src), 8, 3)
    cv.CvtColor(src, hsv, cv.CV_BGR2HSV)
    hsv_patch= cv.CreateImage(cv.GetSize(patch), 8, 3)

    # Extract the H and S planes
    h_plane = cv.CreateMat(src.rows, src.cols, cv.CV_8UC1)
    h_plane_img = cv.CreateImage(cv.GetSize(src), 8, 1)
    h_plane_patch = cv.CreateMat(patch.rows, patch.cols, cv.CV_8UC1)
    s_plane = cv.CreateMat(src.rows, src.cols, cv.CV_8UC1)
    s_plane_img = cv.CreateImage(cv.GetSize(src), 8, 1)
    s_plane_patch = cv.CreateMat(patch.rows, patch.cols, cv.CV_8UC1)
    v_plane = cv.CreateMat(src.rows, src.cols, cv.CV_8UC1)

    cv.Split(hsv, h_plane, s_plane, v_plane, None)
    cv.Split(hsv, h_plane_img, s_plane_img, None, None)
    cv.Split(hsv_patch, h_plane_patch, s_plane_patch, None, None)
    #cv.Split(src, h_plane, s_plane, v_plane, None)
    planes = [h_plane_patch, s_plane_patch]#, s_plane, v_plane]

    h_bins = 30
    s_bins = 32
    v_bins = 30
    hist_size = [h_bins, s_bins]
    # hue varies from 0 (~0 deg red) to 180 (~360 deg red again */
    h_ranges = [0, 180]
    # saturation varies from 0 (black-gray-white) to
    # 255 (pure spectrum color)
    s_ranges = [0, 255]
    v_ranges = [0, 255]
    ranges = [h_ranges, s_ranges]#, s_ranges, v_ranges]
    scale = 10
    hist = cv.CreateHist([h_bins, s_bins], cv.CV_HIST_ARRAY, ranges, 1)
    cv.CalcHist([cv.GetImage(i) for i in planes], hist)
    (_, max_value, _, _) = cv.GetMinMaxHistValue(hist)

    hist_img = cv.CreateImage((h_bins*scale, s_bins*scale), 8, 3)

    back_proj_img = cv.CreateImage(cv.GetSize(src), 8, 1)
    cv.CalcBackProject([h_plane_img, s_plane_img], back_proj_img, hist)
    
    # for h in range(h_bins):
    #     for s in range(s_bins):
    #         bin_val = cv.QueryHistValue_2D(hist, h, s)
    #         intensity = cv.Round(bin_val * 255 / max_value)
    #         cv.Rectangle(hist_img,
    #                      (h*scale, s*scale),
    #                      ((h+1)*scale - 1, (s+1)*scale - 1),
    #                      cv.RGB(intensity, intensity, intensity), 
    #                      cv.CV_FILLED)
    return back_proj_img, hist
Exemplo n.º 16
0
def rgbBackProjectHist(im, fg_hist, bg_hist=None):
    '''
    Compute the hue saturation histogram of an image. (Based on OpenCV example code).
    
    @param im: the image
    @type im: pv.Image
    @param fg_hist: the histogram
    @type fg_hist: pv.Histogram
    @param bg_hist:
    @type bg_hist: pv.Histogram
    @return: an OpenCV histogram
    @rtype: pv.Image
    '''
    w, h = im.size
    bgr = im.asOpenCV()

    if bg_hist != None:
        # set the histogram size
        hist_size = [fg_hist.nbins1, fg_hist.nbins2, fg_hist.nbins3]

        # pixel value ranges
        b_ranges = [0, 255]
        g_ranges = [0, 255]
        r_ranges = [0, 255]
        ranges = [b_ranges, g_ranges, r_ranges]

        # Calculate the histogram
        prob_hist = cv.CreateHist(hist_size, cv.CV_HIST_ARRAY, ranges, 1)

        fg_hist.rescaleMax(255)
        bg_hist.rescaleMax(255)

        cv.CalcProbDensity(bg_hist.hist, fg_hist.hist, prob_hist, scale=255)

        fg_hist = pv.Histogram(prob_hist, pv.HIST_HS, fg_hist.nbins1,
                               fg_hist.nbins2, None)

    # Extract the H and S planes
    b_plane = cv.CreateImage((w, h), cv.IPL_DEPTH_8U, 1)
    g_plane = cv.CreateImage((w, h), cv.IPL_DEPTH_8U, 1)
    r_plane = cv.CreateImage((w, h), cv.IPL_DEPTH_8U, 1)
    cv.Split(bgr, b_plane, g_plane, r_plane, None)
    planes = [b_plane, g_plane, r_plane]

    output = cv.CreateImage((w, h), cv.IPL_DEPTH_8U, 1)

    # Normalize the histogram
    fg_hist.rescaleMax(255)

    cv.CalcBackProject(planes, output, fg_hist.hist)

    return pv.Image(output)
Exemplo n.º 17
0
def cdf(channel):
    # -- find cum dist func for individual channel
    # -- find cumulative histogram and calculate hist to find
    #    which bin (between 0,255) corresponds to what value
    #    and store in refHist
    hist = cv.CreateHist([256], cv.CV_HIST_ARRAY, [[0, 256]], 1)
    cv.CalcHist([cv.GetImage(channel)], hist)
    refHist = [cv.QueryHistValue_1D(hist, x) for x in range(0, 256)]
    # -- calculate cdf
    cdf = [v / np.sum(refHist[:]) for v in refHist[:]]
    for x in range(1, 256):
        cdf[x] += cdf[x - 1]
    return cdf
Exemplo n.º 18
0
    def find_color_bounds(self, hue):
        """ retrieve hue boundaries for most prevailing colors of the image """
        hSize = self.max_histogram_size

        hist = cv.CreateHist([hSize], cv.CV_HIST_SPARSE, [[0, 180]])
        cv.CalcHist([hue], hist)

        bins = np.array([hist.bins[i] for i in range(hSize)])

        start_pt = list(self.get_hist_edges(bins))
        end_pt = start_pt[1:]
        end_pt.append(self.max_histogram_size)

        return zip(start_pt, end_pt)
Exemplo n.º 19
0
def pitch_detect(intrinsics, dist_coeffs, dst0):
    capture = cv.CaptureFromCAM(0)
    src = cv.QueryFrame(capture)
    cv.SetImageROI(dst0, (0, 0, 640, 480))
    cv.Undistort2(src, dst0, intrinsics, dist_coeffs)
    cv.SetImageROI(dst0, image_ROI)
    dst = GetImage(dst0)
    hsv = cv.CreateImage(size, 8, 3)
    CvtColor(dst, hsv, CV_RGB2HSV)
    cv.Split(hsv, hue, sat, val, None)
    hist = cv.CreateHist([32, 64], CV_HIST_ARRAY, [[0, 180], [0, 256]], 1)
    cv.CalcHist([hue, sat], hist, 0, None)
    values = cv.GetMinMaxHistValue(hist)
    tweak = values[3][0]
    return tweak
Exemplo n.º 20
0
    def __init__(self, size):
        w = 0.5
        n = 9
        self.gauss1d = np.exp(-0.5 * w / n *
                              np.array(range(-(n - 1), n, 2))**2)
        self.gauss1d /= sum(self.gauss1d)
        self.hist = cv.CreateHist([self.hist_size], cv.CV_HIST_ARRAY,
                                  [[0, 256]], 1)

        self.Ihist = cv.CreateImage((128, 64), 8, 3)
        self.R = cv.CreateImage(size, cv.IPL_DEPTH_8U, 1)
        self.G = cv.CreateImage(size, cv.IPL_DEPTH_8U, 1)
        self.B = cv.CreateImage(size, cv.IPL_DEPTH_8U, 1)

        self.tmp = cv.CreateImage(size, cv.IPL_DEPTH_8U, 3)
Exemplo n.º 21
0
    def _compute_1ch_histogram(self, img_list):
        """
        DESIGNED FOR INTERNAL USE ONLY
        CAREFUL, NO VERIFICATIONS PERFORMED
        """
        dims = [self.nb_bins]
        all_ranges = [self.ranges]

        hist_list = []
        for img in img_list:
            hist = cv.CreateHist(dims, cv.CV_HIST_ARRAY, all_ranges, uniform=1)
            cv.CalcHist([img], hist)
            hist_list.append(hist)

        return hist_list
Exemplo n.º 22
0
    def getHist(self, hBins, sBins):
        # Extract the H and S planes
        h_plane = cv.CreateMat(self.src.height, self.src.width, cv.CV_8UC1)
        s_plane = cv.CreateMat(self.src.height, self.src.width, cv.CV_8UC1)
        cv.Split(self.src, h_plane, s_plane, None, None)
        planes = [h_plane, s_plane]

        hist_size = [hBins, sBins]
        # hue varies from 0 (~0 deg red) to 180 (~360 deg red again */
        h_ranges = [0, 180]
        # saturation varies from 0 (black-gray-white) to 255 (pure spectrum color)
        s_ranges = [0, 255]
        ranges = [h_ranges, s_ranges]

        self.hist = cv.CreateHist([hBins, sBins], cv.CV_HIST_ARRAY, ranges, 1)
        cv.CalcHist([cv.GetImage(i) for i in planes], self.hist)

        return self.hist
Exemplo n.º 23
0
def mapper(key, value):
  # Read in the data and decode...
  imgbytes = np.fromstring(value,dtype='uint8') 
  imarr = cv2.imdecode(imgbytes,cv2.CV_LOAD_IMAGE_COLOR) 
  im = cv.fromarray(imarr) 
  # Convert and split data to get hue... 
  hsv = cv.CreateImage(cv.GetSize(im),8,3)
  hue = cv.CreateImage(cv.GetSize(im),8,1)
  cv.CvtColor(im,hsv,cv.CV_BGR2HSV)
  cv.Split(hsv, hue, None, None, None)
  # Calculate colour (hue) histogram...
  hue_bins = 180 
  hue_range = [0,180] # n.b. opencv hue range
  hist = cv.CreateHist([hue_bins], cv.CV_HIST_ARRAY, [hue_range], 1) 
  cv.CalcHist([hue],hist,0,None)
  # Yield count of colour... 
  for h in range(hue_bins):
    yield int(h),cv.QueryHistValue_1D(hist,h) 
Exemplo n.º 24
0
def RGBHist(im,r_bins=8,g_bins=8,b_bins=8,mask=None,normalize=True):
    '''
    Compute the rgb saturation histogram of an image. (Based on OpenCV example code).
    
    @param im: the image
    @type im: pv.Image
    @param r_bins: the number of bins for hue.
    @type r_bins: int
    @param g_bins: the number of bins for hue.
    @type g_bins: int
    @param b_bins: the number of bins for hue.
    @type b_bins: int
    @param mask: an image containing a mask
    @type mask: cv.Image or np.array(dtype=np.bool)
    @return: an OpenCV histogram
    @rtype: pv.Histogram
    '''
    w,h = im.size
    bgr = im.asOpenCV()

    # Extract the H and S planes
    b_plane = cv.CreateImage((w,h), cv.IPL_DEPTH_8U, 1)
    g_plane = cv.CreateImage((w,h), cv.IPL_DEPTH_8U, 1)
    r_plane = cv.CreateImage((w,h), cv.IPL_DEPTH_8U, 1)
    cv.Split(bgr, b_plane, g_plane, r_plane, None)
    planes = [b_plane, g_plane, r_plane]

    # set the histogram size
    hist_size = [b_bins, g_bins, r_bins]
    
    # pixel value ranges
    b_ranges = [0, 255]
    g_ranges = [0, 255]
    r_ranges = [0, 255]
    
    ranges = [b_ranges, g_ranges, r_ranges]

    # Calculate the histogram    
    hist = cv.CreateHist(hist_size, cv.CV_HIST_ARRAY, ranges, 1)
    if mask != None:
        mask = mask.asOpenCVBW()
    cv.CalcHist(planes, hist, mask=mask)
    
    return pv.Histogram(hist,HIST_RGB,b_bins,g_bins,r_bins)
Exemplo n.º 25
0
def HSHist(im,h_bins=32,s_bins=32,mask=None,normalize=True):
    '''
    Compute the hue saturation histogram of an image. (Based on OpenCV example code).
    
    @param im: the image
    @type im: pv.Image
    @param h_bins: the number of bins for hue.
    @type h_bins: int
    @param s_bins: the number of bins for saturation.
    @type s_bins: int
    @param mask: an image containing a mask
    @type mask: cv.Image or np.array(dtype=np.bool)
    @return: an OpenCV histogram
    @rtype: pv.Histogram
    '''
    w,h = im.size
    hsv = im.asHSV()

    # Extract the H and S planes
    h_plane = cv.CreateImage((w,h), cv.IPL_DEPTH_8U, 1)
    s_plane = cv.CreateImage((w,h), cv.IPL_DEPTH_8U, 1)
    cv.Split(hsv, h_plane, s_plane, None, None)
    planes = [h_plane, s_plane]

    # set the histogram size
    hist_size = [h_bins, s_bins]
    
    # hue varies from 0 (~0 deg red) to 180 (~360 deg red again */
    h_ranges = [0, 180]
    
    # saturation varies from 0 (black-gray-white) to
    # 255 (pure spectrum color)
    s_ranges = [0, 255]
    
    ranges = [h_ranges, s_ranges]

    # Calculate the histogram    
    hist = cv.CreateHist(hist_size, cv.CV_HIST_ARRAY, ranges, 1)
    if mask != None:
        mask = mask.asOpenCVBW()
    cv.CalcHist(planes, hist,mask=mask)
    
    return pv.Histogram(hist,HIST_HS,h_bins,s_bins,None)
Exemplo n.º 26
0
def compute_histogram(src, h_bins=30, s_bins=32):
    #create images
    hsv = cv.CreateImage(cv.GetSize(src), 8, 3)
    hplane = cv.CreateImage(cv.GetSize(src), 8, 1)
    splane = cv.CreateImage(cv.GetSize(src), 8, 1)
    vplane = cv.CreateImage(cv.GetSize(src), 8, 1)

    planes = [hplane, splane]
    cv.CvtColor(src, hsv, cv.CV_BGR2HSV)
    cv.Split(hsv, hplane, splane, vplane, None)

    #compute histogram  (why not use v_plane?)
    hist = cv.CreateHist((h_bins, s_bins),
                         cv.CV_HIST_ARRAY,
                         ranges=((0, 180), (0, 255)),
                         uniform=True)
    cv.CalcHist(planes, hist)  #compute histogram
    cv.NormalizeHist(hist, 1.0)  #normalize hist

    return hist
Exemplo n.º 27
0
    def analyse(self, painting):
        data = super(SimpleRHOG, self).analyse(painting)
        segmented = numpy.ones((10, 10), numpy.float32)
        for i in range(1, 10):
            for j in range(1, 10):
                avg = 0
                for x in range(1, int(data.rows / 10)):
                    for y in range(1, int(data.cols / 10)):
                        (val, _, _, _) = cv.Get2D(data, x * i, y * j)
                        avg += val
                avg /= int(data.rows / 10) * int(data.cols / 10)
                segmented[i - 1][j - 1] = avg

        segs = cv.fromarray(segmented)
        grad_img = cv.CreateImage((segs.rows, segs.cols), cv.IPL_DEPTH_32F,
                                  segs.channels)
        cv.Convert(segs, grad_img)
        hist = cv.CreateHist([15], cv.CV_HIST_ARRAY, [[0, 2 * math.pi]])
        cv.CalcHist([grad_img], hist)
        return hist
    def __init__(self, imagem_fonte):

        self.imagem_fonte = imagem_fonte
        self.imagem_destino = cv.CloneMat(imagem_fonte)
        self.imagemHistograma = cv.CreateImage((512, 100), 8, 1)
        self.histograma = cv.CreateHist([512], cv.CV_HIST_ARRAY, [[0, 256]], 1)

        self.brilho = 0
        self.contraste = 0

        cv.NamedWindow("Foto Tons Cinza", 1)
        cv.NamedWindow("Foto Equalizada", 1)
        cv.NamedWindow("Histograma Equalizado", 1)

        cv.CreateTrackbar("Brilho", "Histograma Equalizado", 100, 200,
                          self.atualiza_brilho)
        cv.CreateTrackbar("Contraste", "Histograma Equalizado", 100, 200,
                          self.atualiza_contraste)

        self.atualiza_brilhocontraste()
Exemplo n.º 29
0
def calcHistogram(src, quantization=16):
    # Convert to HSV
    #src = cv.fromarray(_src)
    luv = cv.CreateImage(cv.GetSize(src), 8, 3)
    cv.CvtColor(src, luv, cv.CV_RGB2Luv)

    # Extract the H and S planes
    size = cv.GetSize(src)
    L_plane = cv.CreateMat(size[1], size[0], cv.CV_8UC1)
    U_plane = cv.CreateMat(size[1], size[0], cv.CV_8UC1)
    V_plane = cv.CreateMat(size[1], size[0], cv.CV_8UC1)
    cv.Split(luv, L_plane, U_plane, V_plane, None)
    planes = [L_plane, U_plane, V_plane]
    #print np.asarray(L_plane),np.asarray(U_plane),np.asarray(V_plane)
    #Define number of bins
    L_bins = quantization
    U_bins = quantization
    V_bins = quantization

    #Define histogram size
    hist_size = [L_bins, U_bins, V_bins]

    #
    L_ranges = [0, 255]
    U_ranges = [0, 255]
    V_ranges = [0, 255]

    ranges = [L_ranges, U_ranges, V_ranges]

    #Create histogram
    hist = cv.CreateHist([L_bins, U_bins, V_bins], cv.CV_HIST_ARRAY, ranges, 1)

    #Calc histogram
    cv.CalcHist([cv.GetImage(i) for i in planes], hist)

    #Normalize histogram
    cv.NormalizeHist(hist, 1.0)

    #Return histogram
    return hist
Exemplo n.º 30
0
    def __init__(self, classifiers, regression=False, debug=False):
        self.classifiers = classifiers
        self.curr_classifier_idx = -1
        self.threshold = 150
        self.current_depth = 350
        self.follow_point = 0
        self.keep_running = True

        # the window where we're tracking color
        self.track_window = None
        self.track_box = None

        # if in debug mode, we feed it to a simple request handler
        # and make debug windows etc
        self.debug = debug

        if self.debug:
            self.dbg_depth = Debug("DEPTH", self)
            self.dbg_rgb = Debug("RGB", self, True)

        # histogram for finding FLESH
        self.hist = cv.CreateHist([180], cv.CV_HIST_ARRAY, [(0, 180)], 1)