Python cv2.normalize() Examples

The following are 30 code examples of cv2.normalize(). 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: video2tfrecord.py    From video2tfrecord with MIT License 8 votes vote down vote up
def compute_dense_optical_flow(prev_image, current_image):
  old_shape = current_image.shape
  prev_image_gray = cv2.cvtColor(prev_image, cv2.COLOR_BGR2GRAY)
  current_image_gray = cv2.cvtColor(current_image, cv2.COLOR_BGR2GRAY)
  assert current_image.shape == old_shape
  hsv = np.zeros_like(prev_image)
  hsv[..., 1] = 255
  flow = None
  flow = cv2.calcOpticalFlowFarneback(prev=prev_image_gray,
                                      next=current_image_gray, flow=flow,
                                      pyr_scale=0.8, levels=15, winsize=5,
                                      iterations=10, poly_n=5, poly_sigma=0,
                                      flags=10)

  mag, ang = cv2.cartToPolar(flow[..., 0], flow[..., 1])
  hsv[..., 0] = ang * 180 / np.pi / 2
  hsv[..., 2] = cv2.normalize(mag, None, 0, 255, cv2.NORM_MINMAX)
  return cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR) 
Example #2
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 #3
Source File: smoke_video_dataset_cp.py    From deep-smoke-machine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def load_frames(file_path, resize_to=224.0):
    # Saved numpy files should be read in with format (time, height, width, channel)
    frames = np.load(file_path)
    t, h, w, c = frames.shape

    # Resize and scale images for the network structure
    #TODO: maybe use opencv to normalize the image
    #frames = cv.normalize(frames, None, alpha=0, beta=1, norm_type=cv.NORM_MINMAX, dtype=cv.CV_32F)
    frames_out = []
    need_resize = False
    if w < resize_to or h < resize_to:
        d = resize_to - min(w, h)
        sc = 1 + d / min(w, h)
        need_resize = True
    for i in range(t):
        img = frames[i, :, :, :]
        if need_resize:
            img = cv.resize(img, dsize=(0, 0), fx=sc, fy=sc)
        img = (img / 255.) * 2 - 1
        frames_out.append(img)
    return np.asarray(frames_out, dtype=np.float32) 
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: FOVMultiWellsSplitter.py    From tierpsy-tracker with MIT License 6 votes vote down vote up
def get_blur_im(self):
        """downscale and blur the image"""
        # preprocess image
        dwnscl_factor = 4; # Hydra images' shape is divisible by 4
        blr_sigma = 17; # blur the image a bit, seems to work better
        new_shape = (self.img.shape[1]//dwnscl_factor, # as x,y, not row,columns
                     self.img.shape[0]//dwnscl_factor)

        try:
            dwn_gray_im = cv2.resize(self.img, new_shape)
        except:
            pdb.set_trace()
        # apply blurring
        blur_im = cv2.GaussianBlur(dwn_gray_im, (blr_sigma,blr_sigma),0)
        # normalise between 0 and 255
        blur_im = cv2.normalize(blur_im, None, alpha=0, beta=255,
                                norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8U)
        return blur_im 
Example #6
Source File: GetMaskParams.py    From tierpsy-tracker with MIT License 6 votes vote down vote up
def updateROIs(self):
        #useful for resizing events
        if self.Ifull.size == 0:
            self.twoViews.cleanCanvas()
        else:
            cur = self.ui.tabWidget.currentIndex()
            if cur == self.tab_keys['mask']:
                I1, I2 = self.Ifull, self.Imask
            elif cur == self.tab_keys['bgnd']:
                I1 = self.Ifull
                I2 = np.zeros_like(self.IsubtrB)
                cv2.normalize(self.IsubtrB,I2,0,255,cv2.NORM_MINMAX)
            else:
                I1, I2 = self.Ifull, self.Ifull

            qimage_roi1 = self._numpy2qimage(I1)
            qimage_roi2 = self._numpy2qimage(I2)
            self.twoViews.setPixmap(qimage_roi1, qimage_roi2) 
Example #7
Source File: combine.py    From unet-gan-matting with MIT License 6 votes vote down vote up
def generate_target(object_file, target_name):
    border = 20
    size = [960, 720]

    foreground = cv2.imread(object_file, cv2.IMREAD_UNCHANGED)
    if foreground is None:
        return False
    cv2.normalize(foreground, foreground, 0, 255, cv2.NORM_MINMAX)
    foreground = foreground.astype(numpy.uint8)

    ratio = numpy.amin(numpy.divide(
            numpy.subtract(size, [2*border, 2*border]), foreground.shape[0:2]))
    forground_size = numpy.floor(numpy.multiply(foreground.shape[0:2], ratio)).astype(int)
    foreground = cv2.resize(foreground, (forground_size[1], forground_size[0]))
    foreground = image_fill(foreground,size,[0,0,0,0])

    cv2.imwrite(target_name, foreground) 
Example #8
Source File: nlc.py    From videoseg with MIT License 6 votes vote down vote up
def normalize_nn(transM, sigma=1):
    """
    Normalize transition matrix using gaussian weighing
    Input:
        transM: (k,k)
        sigma: var=sigma^2 of gaussian weight between elements
    Output: transM: (k,k)
    """
    # Make weights Gaussian and normalize
    k = transM.shape[0]
    transM[np.nonzero(transM)] = np.exp(
        -np.square(transM[np.nonzero(transM)]) / sigma**2)
    transM[np.arange(k), np.arange(k)] = 1.
    normalization = np.dot(transM, np.ones(k))
    # This is inefficient, bottom line is better ..
    # transM = np.dot(np.diag(1. / normalization), transM)
    transM = (1. / normalization).reshape((-1, 1)) * transM
    return transM 
Example #9
Source File: nlc.py    From videoseg with MIT License 6 votes vote down vote up
def consensus_vote(votes, transM, frameEnd, iters):
    """
    Perform iterative consensus voting
    """
    sTime = time.time()
    for t in range(iters):
        votes = np.dot(transM, votes)
        # normalize per frame
        for i in range(frameEnd.shape[0]):
            currStartF = 1 + frameEnd[i - 1] if i > 0 else 0
            currEndF = frameEnd[i]
            frameVotes = np.max(votes[currStartF:1 + currEndF])
            votes[currStartF:1 + currEndF] /= frameVotes + (frameVotes <= 0)
    eTime = time.time()
    print('Consensus voting finished: %.2f s' % (eTime - sTime))
    return votes 
Example #10
Source File: template_matching.py    From dual-fisheye-video-stitching with MIT License 6 votes vote down vote up
def main():
    src = cv2.imread('src.jpg', cv2.IMREAD_GRAYSCALE)
    tpl = cv2.imread('tpl.jpg', cv2.IMREAD_GRAYSCALE)
    result = cv2.matchTemplate(src, tpl, cv2.TM_CCOEFF_NORMED)
    result = cv2.normalize(result, dst=None, alpha=0, beta=1,
                           norm_type=cv2.NORM_MINMAX, dtype=-1)
    minVal, maxVal, minLoc, maxLoc = cv2.minMaxLoc(result)
    matchLoc = maxLoc
    draw1 = cv2.rectangle(
        src, matchLoc, (matchLoc[0] + tpl.shape[1], matchLoc[1] + tpl.shape[0]), 0, 2, 8, 0)
    draw2 = cv2.rectangle(
        result, matchLoc, (matchLoc[0] + tpl.shape[1], matchLoc[1] + tpl.shape[0]), 0, 2, 8, 0)
    cv2.imshow('draw1', draw1)
    cv2.imshow('draw2', draw2)
    cv2.waitKey(0)
    print src.shape
    print tpl.shape
    print result.shape
    print matchLoc 
Example #11
Source File: imgproc.py    From graph_distillation with Apache License 2.0 6 votes vote down vote up
def proc_oflow(images):
  h, w = images.shape[-3:-1]

  processed_images = []
  for image in images:
    hsv = np.zeros((h, w, 3), dtype=np.uint8)
    hsv[:, :, 0] = 255
    hsv[:, :, 1] = 255

    mag, ang = cv2.cartToPolar(image[..., 0], image[..., 1])
    hsv[..., 0] = ang*180/np.pi/2
    hsv[..., 2] = cv2.normalize(mag, None, 0, 255, cv2.NORM_MINMAX)

    processed_image = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)
    processed_images.append(processed_image)

  return np.stack(processed_images) 
Example #12
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 #13
Source File: live_demo.py    From mr_saliency with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, parent, capture, fps=24):
        wx.Panel.__init__(self, parent)
                
        self.capture = capture2
        ret, frame = self.capture.read()


        sal = mr_sal.saliency(frame)
        sal = cv2.resize(sal,(320,240)).astype(sp.uint8)
        sal = cv2.normalize(sal, None, 0, 255, cv2.NORM_MINMAX)
        outsal = cv2.applyColorMap(sal,cv2.COLORMAP_HSV)
        self.bmp = wx.BitmapFromBuffer(320,240, outsal.astype(sp.uint8))

        self.timer = wx.Timer(self)
        self.timer.Start(1000./fps)

        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_TIMER, self.NextFrame) 
Example #14
Source File: operations.py    From dffml with MIT License 6 votes vote down vote up
def normalize(
    src: List[int],
    alpha: int = None,
    beta: int = None,
    norm_type: int = None,
    dtype: int = None,
    mask: List[int] = None,
) -> List[int]:
    """
    Normalizes arrays
    """
    src = src.astype("float")
    dst = np.zeros(src.shape)  # Output image array

    parameters = {k: v for k, v in locals().items() if v is not None}

    cv2.normalize(**parameters)
    return dst 
Example #15
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 #16
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 #17
Source File: handpose_evaluation.py    From semi-auto-anno with GNU General Public License v3.0 5 votes vote down vote up
def saveVideoFrames(self, filename, images):
        """
        Create a video with synthesized images
        :param filename: name of file to save
        :param images: video data
        :return: None
        """

        txt = 'Saving {}'.format(filename)
        pbar = pb.ProgressBar(maxval=images.shape[0], widgets=[txt, pb.Percentage(), pb.Bar()])
        pbar.start()

        height = width = 128

        # Define the codec and create VideoWriter object
        fourcc = cv2.cv.CV_FOURCC(*'DIVX')
        video = cv2.VideoWriter('{}/synth_{}.avi'.format(self.subfolder, filename), fourcc, self.fps, (height, width))
        if not video:
            raise EnvironmentError("Error in creating video writer")

        for i in range(images.shape[0]):
            img = images[i]
            img = cv2.normalize(img, alpha=0, beta=255, norm_type=cv2.cv.CV_MINMAX, dtype=cv2.cv.CV_8UC1)
            img = cv2.cvtColor(img, cv2.cv.CV_GRAY2BGR)
            img = cv2.resize(img, (height, width))
            # write frame
            video.write(img)
            pbar.update(i)

        video.release()
        del video
        cv2.destroyAllWindows()

        pbar.finish() 
Example #18
Source File: class_CNN.py    From ALPR_System with Apache License 2.0 5 votes vote down vote up
def read_tensor_from_image(self, image, imageSizeOuput):
    """
    inputs an image and converts to a tensor
    """
    image = cv2.resize(image, dsize=(imageSizeOuput, imageSizeOuput), interpolation = cv2.INTER_CUBIC)
    np_image_data = np.asarray(image)
    np_image_data = cv2.normalize(np_image_data.astype('float'), None, -0.5, .5, cv2.NORM_MINMAX)
    np_final = np.expand_dims(np_image_data,axis=0)
    return np_final 
Example #19
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 #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: semiautoanno.py    From semi-auto-anno with GNU General Public License v3.0 5 votes vote down vote up
def getImageDescriptors_HOG_cdist(self, all_emb, ref_emb, ref_mask):
        # unnormalized cosine distance for HOG
        dist = numpy.dot(all_emb, ref_emb.T)
        # normalize by length of query descriptor projected on reference
        norm = numpy.sqrt(numpy.dot(numpy.square(all_emb), ref_mask.T))
        dist /= norm
        dist[numpy.isinf(dist)] = 0.
        dist[numpy.isnan(dist)] = 0.

        # dist[numpy.triu_indices(dist.shape[0], 1)] = numpy.maximum(dist[numpy.triu_indices(dist.shape[0], 1)],
        #                                                            dist.T[numpy.triu_indices(dist.shape[0], 1)])
        # dist[numpy.tril_indices(dist.shape[0], -1)] = 0.
        # dist += dist.T

        return dist 
Example #22
Source File: img_tools.py    From crossgap_il_rl with GNU General Public License v2.0 5 votes vote down vote up
def float_img_to_display(_img):
        img = _img
        max_value = 1000
        rows, cols = img.shape
        for i in range(rows):
            for j in range(cols):
                if (img[i, j] > max_value):
                    img[i, j] = max_value
        dist1 = cv2.convertScaleAbs(img)
        dist2 = cv2.normalize(dist1, None, 255, 0, cv2.NORM_MINMAX, cv2.CV_8UC1)
        return dist1
        # return dist2 
Example #23
Source File: cvutils.py    From 1ZLAB_PyEspCar with GNU General Public License v3.0 5 votes vote down vote up
def calculate_roi_hist(roi):
    hsv = cv2.cvtColor(roi,cv2.COLOR_BGR2HSV)
    
    # calculating object histogram
    roihist = cv2.calcHist([hsv],[0, 1], None, [180, 256], [0, 180, 0, 256] )
    # normalize histogram and apply backprojection
    cv2.normalize(roihist,roihist,0,255,cv2.NORM_MINMAX)

    return roihist 
Example #24
Source File: combine.py    From unet-gan-matting with MIT License 5 votes vote down vote up
def generate_trimap(object_file, trimap_name):
    border = 20
    size = [960, 720]

    foreground = cv2.imread(object_file, cv2.IMREAD_UNCHANGED)
    if foreground is None:
        return False
    alpha = cv2.split(foreground)[3]

    ratio = numpy.amin(numpy.divide(
            numpy.subtract(size, [2*border, 2*border]), alpha.shape[0:2]))
    forground_size = numpy.floor(numpy.multiply(alpha.shape[0:2], ratio)).astype(int)
    alpha = cv2.resize(alpha, (forground_size[1], forground_size[0]))
    alpha = image_fill(alpha,size,[0,0,0,0])

    alpha = alpha.astype(float)
    cv2.normalize(alpha, alpha, 0.0, 1.0, cv2.NORM_MINMAX)

    _, inner_map = cv2.threshold(alpha, 0.999, 255, cv2.THRESH_BINARY)
    _, outer_map = cv2.threshold(alpha, 0.001, 255, cv2.THRESH_BINARY)

    inner_map = cv2.erode(inner_map, numpy.ones((5,5),numpy.uint8), iterations = 3)
    outer_map = cv2.dilate(outer_map, numpy.ones((5,5),numpy.uint8), iterations = 3)

    cv2.imwrite(trimap_name, inner_map + (outer_map - inner_map) /2)

    foreground = cv2.imread(object_file, cv2.IMREAD_UNCHANGED) 
Example #25
Source File: combine.py    From unet-gan-matting with MIT License 5 votes vote down vote up
def combine_object_background(object_file, background_file, output_name):
    border = 20
    size = [960, 720]

    foreground = cv2.imread(object_file, cv2.IMREAD_UNCHANGED)
    if foreground is None:
        return False

    ratio = numpy.amin(numpy.divide(
            numpy.subtract(size, [2*border, 2*border]), foreground.shape[0:2]))
    forground_size = numpy.floor(numpy.multiply(foreground.shape[0:2], ratio)).astype(int)
    foreground = cv2.resize(foreground, (forground_size[1], forground_size[0]))
    foreground = image_fill(foreground,size,[0,0,0,0])

    foreground = foreground.astype(float)
    cv2.normalize(foreground, foreground, 0.0, 1.0, cv2.NORM_MINMAX)
    alpha = cv2.split(foreground)[3]

    #foreground = cv2.imread(object_file, cv2.IMREAD_COLOR)
    background = cv2.imread(background_file)
    if background is None:
        return False

    ratio = numpy.amax(numpy.divide(foreground.shape[0:2], background.shape[0:2]))
    background_size = numpy.ceil(numpy.multiply(background.shape[0:2], ratio)).astype(int)
    #print(numpy.multiply(background.shape[0:2], ratio).astype(int))
    background = cv2.resize(background, (background_size[1], background_size[0]))
    background = background[0:foreground.shape[0], 0:foreground.shape[1]]
    background = background.astype(float)

    for i in range(0, 3):
        foreground[:,:,i] = numpy.multiply(alpha, foreground[:,:,i]*255)
        background[:,:,i] = numpy.multiply(1.0 - alpha, background[:,:,i])
    outImage = numpy.add(foreground[:,:,0:3], background)

    cv2.imwrite(output_name, outImage)

    return True 
Example #26
Source File: eval.py    From unet-gan-matting with MIT License 5 votes vote down vote up
def generate_trimap(object_file):
    size = [960/2, 720/2]

    foreground = cv2.imread(object_file, cv2.IMREAD_UNCHANGED)
    if foreground is None:
        return False
    print(foreground.shape)
    alpha = cv2.split(foreground)[3]

    ratio = np.amin(np.divide(size, alpha.shape[0:2]))
    forground_size = np.floor(np.multiply(alpha.shape[0:2], ratio)).astype(int)
    alpha = cv2.resize(alpha, (forground_size[1], forground_size[0]))
    alpha = image_fill(alpha,size,[0,0,0,0])

    alpha = alpha.astype(float)
    cv2.normalize(alpha, alpha, 0.0, 1.0, cv2.NORM_MINMAX)

    _, inner_map = cv2.threshold(alpha, 0.9, 255, cv2.THRESH_BINARY)
    _, outer_map = cv2.threshold(alpha, 0.1, 255, cv2.THRESH_BINARY)

    inner_map = cv2.erode(inner_map, np.ones((5,5),np.uint8), iterations = 3)
    outer_map = cv2.dilate(outer_map, np.ones((5,5),np.uint8), iterations = 3)

    return inner_map + (outer_map - inner_map) /2

# Parse Arguments 
Example #27
Source File: image-search-engine.py    From py-image-search-engine with MIT License 5 votes vote down vote up
def describe(self, image):
        """
        Color description of a given image

        compute a 3D histogram in the RGB color space,
        then normalize the histogram so that images
        with the same content, but either scaled larger
        or smaller will have (roughly) the same histogram

        :param image:
            Image to be described.
        :return: flattened 3-D histogram
            Flattened descriptor [feature vector].
        """
        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        hist = cv2.calcHist(images=[image], channels=[0, 1, 2], mask=None,
                            histSize=self.bins, ranges=[0, 256] * 3)
        hist = cv2.normalize(hist, dst=hist.shape)
        return hist.flatten()


################################################################################################
# +———————————————————————————————————————————————————————————————————————————————————————————+
# | Step 2: Indexing
# +———————————————————————————————————————————————————————————————————————————————————————————+
################################################################################################
# key - image file name, value - computed feature vector/descriptor 
Example #28
Source File: descriptor.py    From py-image-search-engine with MIT License 5 votes vote down vote up
def describe(self, filename):
        image = cv2.imread(filename)
        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        hist = cv2.calcHist(images=[image], channels=[0, 1, 2], mask=None,
                            histSize=self.bins, ranges=[0, 256] * 3)
        hist = cv2.normalize(hist, dst=hist.shape)
        return hist.flatten() 
Example #29
Source File: trainer.py    From lidar-bonnetal with MIT License 5 votes vote down vote up
def make_log_img(depth, mask, pred, gt, color_fn):
    # input should be [depth, pred, gt]
    # make range image (normalized to 0,1 for saving)
    depth = (cv2.normalize(depth, None, alpha=0, beta=1,
                           norm_type=cv2.NORM_MINMAX,
                           dtype=cv2.CV_32F) * 255.0).astype(np.uint8)
    out_img = cv2.applyColorMap(
        depth, Trainer.get_mpl_colormap('viridis')) * mask[..., None]
    # make label prediction
    pred_color = color_fn((pred * mask).astype(np.int32))
    out_img = np.concatenate([out_img, pred_color], axis=0)
    # make label gt
    gt_color = color_fn(gt)
    out_img = np.concatenate([out_img, gt_color], axis=0)
    return (out_img).astype(np.uint8) 
Example #30
Source File: utils.py    From tvnet_pytorch with MIT License 5 votes vote down vote up
def save_flow_to_img(flow, h, w, c, name='_result.png'):
    hsv = np.zeros((h, w, c), dtype=np.uint8)
    hsv[:, :, 0] = 255
    hsv[:, :, 2] = 255
    mag, ang = cv2.cartToPolar(flow[..., 0], flow[..., 1])
    hsv[..., 0] = ang * 180 / np.pi / 2
    hsv[..., 1] = cv2.normalize(mag, None, 0, 255, cv2.NORM_MINMAX)

    rgb = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)
    res_img_path = os.path.join('result', name)
    cv2.imwrite(res_img_path, rgb)