Python cv2.bilateralFilter() Examples

The following are 30 code examples of cv2.bilateralFilter(). 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: data_augmentation.py    From Automated-Cardiac-Segmentation-and-Disease-Diagnosis with MIT License 6 votes vote down vote up
def slicewise_bilateral_filter(data_3d, d=3, sigmaColor=8, sigmaSpace=8):
    img_batch_shape = data_3d.shape[:2] +(0,)
    img_batch = np.empty(img_batch_shape, dtype='float32')
    print (img_batch.shape)
    print (data_3d.dtype)
    try:
        slices = data_3d.shape[2] 
    except Exception:
        slices = 1
        denoised_img = bilateralFilter(data_3d[:,:].astype('float32'),d, sigmaColor, sigmaSpace)
        return denoised_img
    for i in range(slices):
        denoised_img = np.expand_dims(bilateralFilter(data_3d[:,:,i].astype('float32'),
                                        d, sigmaColor, sigmaSpace), axis=2)
        img_batch = np.concatenate((img_batch, denoised_img), axis=2)
    return img_batch 
Example #2
Source File: metric.py    From Face-Sketch-Wild with MIT License 6 votes vote down vote up
def avg_score(test_dir, gt_dir, metric_name='ssim', smooth=False, sigma=75, verbose=False):
    """
    Read images from two folders and calculate the average score.
    """
    metric_name = metric_name.lower()
    all_score = []
    if metric_name == 'fsim':
        matlab = matlab_wrapper.MatlabSession()
    for name in sorted(sorted(os.listdir(gt_dir))):
        test_img = Image.open(os.path.join(test_dir, name)).convert('L')
        gt_img = Image.open(os.path.join(gt_dir, name)).convert('L')
        if smooth:
            test_img = cv.bilateralFilter(np.array(test_img),7,sigma,sigma)

        if metric_name == 'ssim':
            tmp_score = SSIM(gt_img, test_img)
        elif metric_name == 'fsim':
            tmp_score = FSIM(matlab, gt_img, test_img)
        if verbose:
            print('Image: {}, Metric: {}, Smooth: {}, Score: {}'.format(name, metric_name, smooth, tmp_score))
        all_score.append(tmp_score)
    return np.mean(np.array(all_score)) 
Example #3
Source File: preprocessing.py    From minian with GNU General Public License v3.0 6 votes vote down vote up
def denoise(varr, method, **kwargs):
    if method == 'gaussian':
        func = cv2.GaussianBlur
    elif method == 'anisotropic':
        func = anisotropic_diffusion
    elif method == 'median':
        func = cv2.medianBlur
    elif method == 'bilateral':
        func = cv2.bilateralFilter
    else:
        raise NotImplementedError(
            "denoise method {} not understood".format(method))
    res = xr.apply_ufunc(
        func,
        varr,
        input_core_dims=[['height', 'width']],
        output_core_dims=[['height', 'width']],
        vectorize=True,
        dask='parallelized',
        output_dtypes=[varr.dtype],
        kwargs=kwargs)
    return res.rename(varr.name + "_denoised") 
Example #4
Source File: Cartoonlization.py    From rabbitVE with GNU General Public License v3.0 6 votes vote down vote up
def cartoonise(self, img_rgb, num_down, num_bilateral, medianBlur, D, sigmaColor, sigmaSpace):
        # 用高斯金字塔降低取样
        img_color = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2BGR)
        for _ in range(num_down):
            img_color = cv2.pyrDown(img_color)
        # 重复使用小的双边滤波代替一个大的滤波
        for _ in range(num_bilateral):
            img_color = cv2.bilateralFilter(img_color, d=D, sigmaColor=sigmaColor, sigmaSpace=sigmaSpace)
        # 升采样图片到原始大小
        for _ in range(num_down):
            img_color = cv2.pyrUp(img_color)
        if not self.Save_Edge:
            img_cartoon = img_color
        else:
            img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2GRAY)
            img_blur = cv2.medianBlur(img_gray, medianBlur)
            img_edge = cv2.adaptiveThreshold(img_blur, 255,
                                             cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
                                             cv2.THRESH_BINARY,
                                             blockSize=self.Adaptive_Threshold_Block_Size,
                                             C=self.C)
            img_edge = cv2.cvtColor(img_edge, cv2.COLOR_GRAY2RGB)
            img_edge = cv2.resize(img_edge, img_color.shape[:2][::-1])
            img_cartoon = cv2.bitwise_and(img_color, img_edge)
        return cv2.cvtColor(img_cartoon, cv2.COLOR_RGB2BGR) 
Example #5
Source File: blur.py    From ViolenceDetection with Apache License 2.0 6 votes vote down vote up
def _augment_images(self, images, random_state, parents, hooks):
        result = images
        nb_images = len(images)
        seed = random_state.randint(0, 10**6)
        samples_d = self.d.draw_samples((nb_images,), random_state=ia.new_random_state(seed))
        samples_sigma_color = self.sigma_color.draw_samples((nb_images,), random_state=ia.new_random_state(seed+1))
        samples_sigma_space = self.sigma_space.draw_samples((nb_images,), random_state=ia.new_random_state(seed+2))
        for i in sm.xrange(nb_images):
            ia.do_assert(images[i].shape[2] == 3, "BilateralBlur can currently only be applied to images with 3 channels.")
            di = samples_d[i]
            sigma_color_i = samples_sigma_color[i]
            sigma_space_i = samples_sigma_space[i]

            if di != 1:
                result[i] = cv2.bilateralFilter(images[i], di, sigma_color_i, sigma_space_i)
        return result 
Example #6
Source File: mobileface_makeup.py    From MobileFace with MIT License 6 votes vote down vote up
def face_smooth(self, im_bgr, smooth_rate=0.7, bi_ksize=15, sigma=100, ga_ksize=3):
        """Face smoothing.
        Parameters
        ----------
        im_bgr: mat 
            The Mat data format of reading from the original image using opencv.
        smooth_rate: float, default is 0.7.
            The face smoothing rate.
        bi_ksize: int, default is 15.
            The kernel size of bilateral filter.
        sigma: int, default is 100.
            The value of sigmaColor and sigmaSpace for bilateral filter.
        ga_ksize: int, default is 3.
            The kernel size of gaussian blur filter.
        Returns
        -------
        type: mat
            The result of face smoothing.
        """
        im_bi = cv2.bilateralFilter(im_bgr, bi_ksize, sigma, sigma)
        im_ga = cv2.GaussianBlur(im_bi, (ga_ksize, ga_ksize), 0, 0)
        im_smooth = np.minimum(smooth_rate * im_ga + (1 - smooth_rate) * im_bgr, 255).astype('uint8')
        return im_smooth 
Example #7
Source File: cartoonizing.py    From Mastering-OpenCV-4-with-Python with MIT License 6 votes vote down vote up
def cartonize_image(img, gray_mode=False):
    """Cartoonizes the image applying cv2.bilateralFilter()"""

    # Get the sketch:
    thresholded = sketch_image(img)

    # Apply bilateral filter with "big numbers" to get the cartoonized effect:
    filtered = cv2.bilateralFilter(img, 10, 250, 250)

    # Perform 'bitwise and' with the thresholded img as mask in order to set these values to the output
    cartoonized = cv2.bitwise_and(filtered, filtered, mask=thresholded)

    if gray_mode:
        return cv2.cvtColor(cartoonized, cv2.COLOR_BGR2GRAY)

    return cartoonized


# Create the dimensions of the figure and set title: 
Example #8
Source File: test_frameHandler.py    From HalloPy with MIT License 6 votes vote down vote up
def test_input_frame(self):
        """Test if input frame preprocessed correctly.  """

        # setup
        test_path = utils.get_full_path('docs/material_for_testing/face_and_hand.jpg')
        test_image = cv2.imread(test_path)
        # Because image loaded from local, and not received from web-cam, a flip is needed,
        # inside frame_handler, a frame is supposed to be received from web-cam, hence it is flipped after receiving it.
        test_image = cv2.flip(test_image, 1)  # type: np.ndarray

        expected = test_image.copy()
        expected = cv2.bilateralFilter(expected, 5, 50, 100)  # smoothing filter
        expected = cv2.flip(expected, 1)

        frame_handler = FrameHandler()
        frame_handler.logger.setLevel(logging.DEBUG)

        # run
        # range [-1, 1] with a value of one being a “perfect match”.
        frame_handler.input_frame = test_image
        ssim = ImageTestTool.compare_imaged(frame_handler.input_frame, expected)
        # print("SSIM: {}".format(ssim))
        assert ssim >= 0.95 
Example #9
Source File: 05_cartoonizing.py    From OpenCV-3-x-with-Python-By-Example with MIT License 6 votes vote down vote up
def cartoonize_image(img, ksize=5, sketch_mode=False):
    num_repetitions, sigma_color, sigma_space, ds_factor = 10, 5, 7, 4 
    # Convert image to grayscale 
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 
 
    # Apply median filter to the grayscale image 
    img_gray = cv2.medianBlur(img_gray, 7) 
 
    # Detect edges in the image and threshold it 
    edges = cv2.Laplacian(img_gray, cv2.CV_8U, ksize=ksize) 
    ret, mask = cv2.threshold(edges, 100, 255, cv2.THRESH_BINARY_INV) 
 
    # 'mask' is the sketch of the image 
    if sketch_mode: 
        return cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR) 
 
    # Resize the image to a smaller size for faster computation 
    img_small = cv2.resize(img, None, fx=1.0/ds_factor, fy=1.0/ds_factor, interpolation=cv2.INTER_AREA)
 
    # Apply bilateral filter the image multiple times 
    for i in range(num_repetitions): 
        img_small = cv2.bilateralFilter(img_small, ksize, sigma_color, sigma_space) 
 
    img_output = cv2.resize(img_small, None, fx=ds_factor, fy=ds_factor, interpolation=cv2.INTER_LINEAR) 
 
    dst = np.zeros(img_gray.shape) 
 
    # Add the thick boundary lines to the image using 'AND' operator 
    dst = cv2.bitwise_and(img_output, img_output, mask=mask) 
    return dst 
Example #10
Source File: DartsRecognition.py    From opencv-steel-darts with GNU General Public License v3.0 5 votes vote down vote up
def getThreshold(cam, t):
    success, t_plus = cam2gray(cam)
    dimg = cv2.absdiff(t, t_plus)

    blur = cv2.GaussianBlur(dimg, (5, 5), 0)
    blur = cv2.bilateralFilter(blur, 9, 75, 75)
    _, thresh = cv2.threshold(blur, 60, 255, 0)

    return thresh 
Example #11
Source File: filter.py    From Walk-Assistant with GNU General Public License v3.0 5 votes vote down vote up
def blur(img):
        return cv2.bilateralFilter(img, 9, 75, 75) 
Example #12
Source File: main.py    From BeautyCamera with MIT License 5 votes vote down vote up
def dermabrasion(self, value1=3, value2=2):
        value1 = self.ui.horizontalSlider_14.value()
        value2 = 11 - self.ui.horizontalSlider_11.value()
        if value1 == 0 and value2 == 0:
            return 0
        if value2 == 0:
            value2 = 2
        if value1 == 0:
            value1 = 3
        img = self.current_img
        dx = value1 * 5
        fc = value1 * 12.5
        p = 50
        temp1 = cv2.bilateralFilter(img, dx, fc, fc)
        temp2 = (temp1 - img + 128)
        temp3 = cv2.GaussianBlur(temp2, (2 * value2 - 1, 2 * value2 - 1), 0, 0)
        temp4 = img + 2 * temp3 - 255
        dst = np.uint8(img * ((100 - p) / 100) + temp4 * (p / 100))


        imgskin_c = np.uint8(-(self.imgskin - 1))

        dst = np.uint8(dst * self.imgskin + img * imgskin_c)
        self.current_img = dst

# 美白算法(皮肤识别) 
Example #13
Source File: video.py    From cv with MIT License 5 votes vote down vote up
def cartoonize_image(img, ds_factor=4, sketch_mode=False):
    #convert to gray scale
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    #apply median filter
    img_gray = cv2.medianBlur(img_gray, 7)

    #detect edges and threshold the imag
    edges = cv2.Laplacian(img_gray, cv2.CV_8U, ksize=5)
    ret, mask = cv2.threshold(edges, 100, 255, cv2.THRESH_BINARY_INV)
    
    #mask is the sketch of the image
    if sketch_mode:
        return cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR)
    
    img_small = cv2.resize(img, None, fx=1.0/ds_factor, fy=1.0/ds_factor, interpolation = cv2.INTER_AREA)
    num_repetitions = 10
    sigma_color = 5
    sigma_space = 7
    size = 5
    
    #apply bilateral filter multiple times
    for i in range(num_repetitions):
        img_small = cv2.bilateralFilter(img_small, size, sigma_color, sigma_space)
    
    img_output = cv2.resize(img_small, None, fx=ds_factor, fy=ds_factor, interpolation=cv2.INTER_LINEAR)
    dst = np.zeros(img_gray.shape)
    
    dst = cv2.bitwise_and(img_output, img_output, mask=mask)
    return dst 
Example #14
Source File: ocr_controller.py    From JusticeAI with MIT License 5 votes vote down vote up
def _filter_blur(img):
    img = cv2.bilateralFilter(img, 5, 250, 250)  # reduces noise but preserves edges
    return cv2.GaussianBlur(img, (5, 5), 0)  # blurs entire image 
Example #15
Source File: main.py    From OpenLabeling with Apache License 2.0 5 votes vote down vote up
def draw_edges(tmp_img):
    blur = cv2.bilateralFilter(tmp_img, 3, 75, 75)
    edges = cv2.Canny(blur, 150, 250, 3)
    edges = cv2.cvtColor(edges, cv2.COLOR_GRAY2RGB)
    # Overlap image and edges together
    tmp_img = np.bitwise_or(tmp_img, edges)
    #tmp_img = cv2.addWeighted(tmp_img, 1 - edges_val, edges, edges_val, 0)
    return tmp_img 
Example #16
Source File: inference_utils.py    From rpg_e2vid with GNU General Public License v3.0 5 votes vote down vote up
def __call__(self, img):

        if self.bilateral_filter_sigma:
            with Timer('Bilateral filter (sigma={:.2f})'.format(self.bilateral_filter_sigma)):
                filtered_img = np.zeros_like(img)
                filtered_img = cv2.bilateralFilter(
                    img, 5, 25.0 * self.bilateral_filter_sigma, 25.0 * self.bilateral_filter_sigma)
                img = filtered_img

        return img 
Example #17
Source File: toolbox_opencv.py    From remi with Apache License 2.0 5 votes vote down vote up
def on_new_image_listener(self, emitter):
        try:
            self.image_source = emitter
            border = self.border_type[self.border] if type(self.border) == str else self.border
            self.set_image_data(cv2.bilateralFilter(emitter.img, self.diameter, self.sigma_color, self.sigma_space, borderType=border))
        except Exception:
            print(traceback.format_exc()) 
Example #18
Source File: utils.py    From video_frame_remover with MIT License 5 votes vote down vote up
def get_frame_box_coords(input_frame, sz=300, min_area_ratio=0.2, max_area_ratio=0.9, pad=5):
    ratio = input_frame.shape[0] / float(sz)
    input_frame_resized = resize_img(input_frame, height=sz)
    input_frame_resized = input_frame_resized.astype(np.uint8)
    total_area = input_frame_resized.shape[0] * input_frame_resized.shape[1]
    color = [255, 255, 255]
    input_frame_padded = cv2.copyMakeBorder(input_frame_resized, pad, pad, pad, pad, cv2.BORDER_CONSTANT, value=color)
    gray = cv2.cvtColor(input_frame_padded, cv2.COLOR_BGR2GRAY)
    gray = cv2.bilateralFilter(gray, 10, 10, 10)
    edged = auto_canny(gray, sigma=0.9)
    _, contours, _ = cv2.findContours(edged, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    if len(contours) == 0:
        return None
    area_lst = []
    rect_coord_lst = []
    for contour in contours:
        (x, y, w, h) = cv2.boundingRect(contour)
        area = w * h
        if min_area_ratio * total_area < area < max_area_ratio * total_area:
            area_lst.append(w * h)
            x0 = max(0, x - pad)
            y0 = max(0, y - pad)
            rect_coord_lst.append(np.array([x0, y0, w, h]))

    if len(area_lst) == 0:
        return None
    max_idx = np.array(area_lst).argmax()
    rect = rect_coord_lst[max_idx]
    x0, y0, width, height = (rect * ratio).astype(int)
    return x0, y0, width, height 
Example #19
Source File: ColorAugmenters.py    From impy with Apache License 2.0 5 votes vote down vote up
def bilateralBlur(self, frame = None, d = None, sigmaColor = None, sigmaSpace = None):
		"""
		Convolves an image with a bilateral filter.
		Args:
			d: Diameter of each pixel neighborhood.
			sigmaColor: Filter color space.
			sigmaSpace: Filter the coordinate space.
		Returns:
			An image blurred by a bilateral filter.
		"""
		# Assertions.
		if (d == None):
			d = 5
		if (type(d) != int):
			raise ValueError("d has to be of type int.")
		if (d > 9):
			raise ValueError("d is allowed to be maximum 9.")
		if (sigmaColor == None):
			sigmaColor = 75
		if (type(sigmaColor) != int):
			raise ValueError("sigmaColor has to be of type int.")
		if (sigmaColor > 250):
			raise ValueError("Sigma color is allowed to be maximum 250.")
		if (sigmaSpace == None):
			sigmaSpace = 75
		if (type(sigmaSpace) != int):
			raise ValueError("sigmaSpace has to be of type int.")
		if (sigmaSpace > 200):
			raise ValueError("Sigma space is allowed to be maximum 200.")		
		# Logic.
		blurredFrame = cv2.bilateralFilter(frame, d, sigmaColor, sigmaSpace)
		if (not (blurredFrame.dtype == np.uint8)):
			print("WARNING: Image is not dtype uint8. Forcing type.")
			blurredFrame = blurredFrame.astype(np.uint8)
		# Return blurred frame.
		return blurredFrame 
Example #20
Source File: pySaliencyMap.py    From aim with MIT License 5 votes vote down vote up
def SMGetSM(self, src):
        # Definitions
        size = src.shape
        width = size[1]
        height = size[0]

        # check
        #        if(width != self.width or height != self.height):
        #            sys.exit("size mismatch")
        
        # Extracting individual color channels
        R, G, B, I = self.SMExtractRGBI(src)

        # Extracting feature maps
        IFM = self.IFMGetFM(I)
        CFM_RG, CFM_BY = self.CFMGetFM(R, G, B)
        OFM = self.OFMGetFM(I)
        MFM_X, MFM_Y = self.MFMGetFM(I)

        # Extracting conspicuity maps
        ICM = self.ICMGetCM(IFM)
        CCM = self.CCMGetCM(CFM_RG, CFM_BY)
        OCM = self.OCMGetCM(OFM)
        MCM = self.MCMGetCM(MFM_X, MFM_Y)

        # Adding all the conspicuity maps to form a saliency map
        wi = pySaliencyMapDefs.weight_intensity
        wc = pySaliencyMapDefs.weight_color
        wo = pySaliencyMapDefs.weight_orientation
        wm = pySaliencyMapDefs.weight_motion
        SMMat = wi * ICM + wc * CCM + wo * OCM + wm * MCM

        # Normalize
        normalizedSM = self.SMRangeNormalize(SMMat)
        normalizedSM2 = normalizedSM.astype(np.float32)
        smoothedSM = cv2.bilateralFilter(normalizedSM2, 7, 3, 1.55)
        self.SM = cv2.resize(smoothedSM, (width, height), interpolation=cv2.INTER_NEAREST)

        return self.SM 
Example #21
Source File: img_processing.py    From robin with MIT License 5 votes vote down vote up
def preprocess_img(img: np.array) -> np.array:
    """Apply bilateral filter to image."""
    #img = cv2.bilateralFilter(img, 5, 50, 50) TODO: change parameters.
    return img 
Example #22
Source File: img.py    From HUAWEIOCR-2019 with MIT License 5 votes vote down vote up
def bilateral_blur(img, d = 9, sigmaColor = 75, sigmaSpace = 75):
    dst = cv2.bilateralFilter(img, d, sigmaColor, sigmaSpace)
    return dst 
Example #23
Source File: img.py    From HUAWEIOCR-2019 with MIT License 5 votes vote down vote up
def bilateral_blur(img, d = 9, sigmaColor = 75, sigmaSpace = 75):
    dst = cv2.bilateralFilter(img, d, sigmaColor, sigmaSpace)
    return dst 
Example #24
Source File: img.py    From HUAWEIOCR-2019 with MIT License 5 votes vote down vote up
def bilateral_blur(img, d = 9, sigmaColor = 75, sigmaSpace = 75):
    dst = cv2.bilateralFilter(img, d, sigmaColor, sigmaSpace)
    return dst 
Example #25
Source File: MeterReader.py    From Pointer-meter-identification-and-reading with MIT License 5 votes vote down vote up
def bilateral_filter(self,img):
        bilateral = cv2.bilateralFilter(img, 9, 50, 50)
        cv2.imshow('Bilateral filter', bilateral)
        return bilateral

    # 高斯滤波去噪 
Example #26
Source File: solver.py    From airport with Apache License 2.0 5 votes vote down vote up
def PrepareImage(image):
  """Converts color image to black and white"""
  # work on gray scale
  bw = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)

  # remove noise, preserve edges
  bw = cv2.bilateralFilter(bw, 9, 75, 75)

  # binary threshold
  bw = cv2.adaptiveThreshold(bw, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
                             cv2.THRESH_BINARY, 11, 2)
  return bw 
Example #27
Source File: preprocess_for_test.py    From 2019-CCF-BDCI-OCR-MCZJ-OCR-IdentificationIDElement with MIT License 5 votes vote down vote up
def preprocess_one_img(img):
    resize_img = _resize_image(img, 32)  # 修改图片的高度
    # 对图片进行滤波处理
    resize_img = cv2.normalize(resize_img, dst=None, alpha=230, beta=20, norm_type=cv2.NORM_MINMAX)
    resize_img = cv2.bilateralFilter(src=resize_img, d=3, sigmaColor=200, sigmaSpace=10)
    resize_img = cv2.filter2D(resize_img, -1, kernel=np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]], np.float32))
    return resize_img 
Example #28
Source File: RegionOfInterest.py    From DoNotSnap with GNU General Public License v3.0 5 votes vote down vote up
def roiMask(image, boundaries):
    scale = max([1.0, np.average(np.array(image.shape)[0:2] / 400.0)])
    shape = (int(round(image.shape[1] / scale)), int(round(image.shape[0] / scale)))

    small_color = cv2.resize(image, shape, interpolation=cv2.INTER_LINEAR)

    # reduce details and remove noise for better edge detection
    small_color = cv2.bilateralFilter(small_color, 8, 64, 64)
    small_color = cv2.pyrMeanShiftFiltering(small_color, 8, 64, maxLevel=1)
    small = cv2.cvtColor(small_color, cv2.COLOR_BGR2HSV)

    hue = small[::, ::, 0]
    intensity = cv2.cvtColor(small_color, cv2.COLOR_BGR2GRAY)

    edges = extractEdges(hue, intensity)
    roi = roiFromEdges(edges)
    weight_map = weightMap(hue, intensity, edges, roi)

    _, final_mask = cv2.threshold(roi, 5, 255, cv2.THRESH_BINARY)
    small = cv2.bitwise_and(small, small, mask=final_mask)

    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (4, 4))

    for (lower, upper) in boundaries:
        lower = np.array([lower, 80, 50], dtype="uint8")
        upper = np.array([upper, 255, 255], dtype="uint8")

        # find the colors within the specified boundaries and apply
        # the mask
        mask = cv2.inRange(small, lower, upper)
        mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel, iterations=3)
        mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel, iterations=1)
        final_mask = cv2.bitwise_and(final_mask, mask)

    # blur the mask for better contour extraction
    final_mask = cv2.GaussianBlur(final_mask, (5, 5), 0)
    return (final_mask, weight_map, scale) 
Example #29
Source File: postprocess.py    From rec-attend-public with MIT License 5 votes vote down vote up
def upsample_single(a, size):
  """Upsample single image, with bilateral filtering.
  Args:
    a: [H', W', 3]
    size: [W, H]
  Returns:
    b: [H, W, 3]
  """
  interpolation = cv2.INTER_LINEAR
  b = cv2.resize(a, size, interpolation=interpolation)
  b = cv2.bilateralFilter(b, 5, 10, 10)
  return b 
Example #30
Source File: fg_model_eval.py    From rec-attend-public with MIT License 5 votes vote down vote up
def upsample_single(self, a, size):
    """Upsample single image, with bilateral filtering.
    Args:
      a: [H', W', 3]
      size: [W, H]
    Returns:
      b: [H, W, 3]
    """
    interpolation = cv2.INTER_LINEAR
    b = cv2.resize(a, size, interpolation=interpolation)
    b = cv2.bilateralFilter(b, 5, 10, 10)
    return b