Python cv2.addWeighted() Examples

The following are 30 code examples of cv2.addWeighted(). 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: plate_locate.py    From EasyPR-python with Apache License 2.0 8 votes vote down vote up
def sobelOperT(self, img, blursize, morphW, morphH):
        '''
            No different with sobelOper ? 
        '''
        blur = cv2.GaussianBlur(img, (blursize, blursize), 0, 0, cv2.BORDER_DEFAULT)

        if len(blur.shape) == 3:
            gray = cv2.cvtColor(blur, cv2.COLOR_RGB2GRAY)
        else:
            gray = blur

        x = cv2.Sobel(gray, cv2.CV_16S, 1, 0, 3)
        absX = cv2.convertScaleAbs(x)
        grad = cv2.addWeighted(absX, 1, 0, 0, 0)

        _, threshold = cv2.threshold(grad, 0, 255, cv2.THRESH_OTSU + cv2.THRESH_BINARY)

        element = cv2.getStructuringElement(cv2.MORPH_RECT, (morphW, morphH))
        threshold = cv2.morphologyEx(threshold, cv2.MORPH_CLOSE, element)

        return threshold 
Example #2
Source File: seg_parser.py    From openseg.pytorch with MIT License 6 votes vote down vote up
def colorize(self, label_map, image_canvas=None):
        height, width = label_map.shape
        color_dst = np.zeros((height, width, 3), dtype=np.uint8)
        color_list = self.configer.get('details', 'color_list')
        for i in range(self.configer.get('data', 'num_classes')):
            color_dst[label_map == i] = color_list[i % len(color_list)]

        color_img_rgb = np.array(color_dst, dtype=np.uint8)
        color_img_bgr = cv2.cvtColor(color_img_rgb, cv2.COLOR_RGB2BGR)

        if image_canvas is not None:
            image_canvas = cv2.addWeighted(image_canvas, 0.6, color_img_bgr, 0.4, 0)
            return image_canvas

        else:
            return color_img_bgr 
Example #3
Source File: helpers.py    From hazymaze with Apache License 2.0 6 votes vote down vote up
def blend_non_transparent(sprite, background_img):
    gray_overlay = cv2.cvtColor(background_img, cv2.COLOR_BGR2GRAY)
    overlay_mask = cv2.threshold(gray_overlay, 1, 255, cv2.THRESH_BINARY)[1]

    overlay_mask = cv2.erode(overlay_mask, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)))
    overlay_mask = cv2.blur(overlay_mask, (3, 3))

    background_mask = 255 - overlay_mask

    overlay_mask = cv2.cvtColor(overlay_mask, cv2.COLOR_GRAY2BGR)
    background_mask = cv2.cvtColor(background_mask, cv2.COLOR_GRAY2BGR)

    sprite_part = (sprite * (1 / 255.0)) * (background_mask * (1 / 255.0))
    overlay_part = (background_img * (1 / 255.0)) * (overlay_mask * (1 / 255.0))

    return np.uint8(cv2.addWeighted(sprite_part, 255.0, overlay_part, 255.0, 0.0)) 
Example #4
Source File: line_detect_2.py    From crop_row_detection with GNU General Public License v3.0 6 votes vote down vote up
def crop_row_detect(image_in):
    '''Inputs an image and outputs the lines'''

    save_image('0_image_in', image_in)

    ### Grayscale Transform ###
    image_edit = grayscale_transform(image_in)
    save_image('1_image_gray', image_edit)

    ### Skeletonization ###
    skeleton = skeletonize(image_edit)
    save_image('2_image_skeleton', skeleton)

    ### Hough Transform ###
    (crop_lines, crop_lines_hough) = crop_point_hough(skeleton)

    save_image('3_image_hough', cv2.addWeighted(image_in, 1, crop_lines_hough, 1, 0.0))
    save_image('4_image_lines', cv2.addWeighted(image_in, 1, crop_lines, 1, 0.0))

    return crop_lines 
Example #5
Source File: utils.py    From object-detection with MIT License 6 votes vote down vote up
def draw_boxed_text(img, text, topleft, color):
    """Draw a transluent boxed text in white, overlayed on top of a
    colored patch surrounded by a black border. FONT, TEXT_SCALE,
    TEXT_THICKNESS and ALPHA values are constants (fixed) as defined
    on top.

    # Arguments
      img: the input image as a numpy array.
      text: the text to be drawn.
      topleft: XY coordinate of the topleft corner of the boxed text.
      color: color of the patch, i.e. background of the text.

    # Output
      img: note the original image is modified inplace.
    """
    assert img.dtype == np.uint8
    img_h, img_w, _ = img.shape
    if topleft[0] >= img_w or topleft[1] >= img_h:
        return img
    margin = 3
    size = cv2.getTextSize(text, FONT, TEXT_SCALE, TEXT_THICKNESS)
    w = size[0][0] + margin * 2
    h = size[0][1] + margin * 2
    # the patch is used to draw boxed text
    patch = np.zeros((h, w, 3), dtype=np.uint8)
    patch[...] = color
    cv2.putText(patch, text, (margin+1, h-margin-2), FONT, TEXT_SCALE,
                WHITE, thickness=TEXT_THICKNESS, lineType=cv2.LINE_8)
    cv2.rectangle(patch, (0, 0), (w-1, h-1), BLACK, thickness=1)
    w = min(w, img_w - topleft[0])  # clip overlay at image boundary
    h = min(h, img_h - topleft[1])
    # Overlay the boxed text onto region of interest (roi) in img
    roi = img[topleft[1]:topleft[1]+h, topleft[0]:topleft[0]+w, :]
    cv2.addWeighted(patch[0:h, 0:w, :], ALPHA, roi, 1 - ALPHA, 0, roi)
    return img 
Example #6
Source File: line_detect_1.py    From crop_row_detection with GNU General Public License v3.0 6 votes vote down vote up
def crop_row_detect(image_in):
    
    save_image('0_image_in', image_in)
    
    ### Grayscale Transform ###
    image_edit = grayscale_transform(image_in)
    save_image('1_image_gray', image_edit)
        
    ### Binarization ###
    _, image_edit = cv2.threshold(image_edit, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
    save_image('2_image_bin', image_edit)
    
    ### Stripping ###
    crop_points = strip_process(image_edit)
    save_image('8_crop_points', crop_points)
    
    ### Hough Transform ###
    crop_lines = crop_point_hough(crop_points)
    save_image('9_image_hough', cv2.addWeighted(image_in, 1, crop_lines, 1, 0.0))
    
    return crop_lines 
Example #7
Source File: Emojinator_V2.py    From Emojinator with MIT License 6 votes vote down vote up
def blend_transparent(face_img, overlay_t_img):
    # Split out the transparency mask from the colour info
    overlay_img = overlay_t_img[:, :, :3]  # Grab the BRG planes
    overlay_mask = overlay_t_img[:, :, 3:]  # And the alpha plane

    # Again calculate the inverse mask
    background_mask = 255 - overlay_mask

    # Turn the masks into three channel, so we can use them as weights
    overlay_mask = cv2.cvtColor(overlay_mask, cv2.COLOR_GRAY2BGR)
    background_mask = cv2.cvtColor(background_mask, cv2.COLOR_GRAY2BGR)

    # Create a masked out face image, and masked out overlay
    # We convert the images to floating point in range 0.0 - 1.0
    face_part = (face_img * (1 / 255.0)) * (background_mask * (1 / 255.0))
    overlay_part = (overlay_img * (1 / 255.0)) * (overlay_mask * (1 / 255.0))

    # And finally just add them together, and rescale it back to an 8bit integer image
    return np.uint8(cv2.addWeighted(face_part, 255.0, overlay_part, 255.0, 0.0)) 
Example #8
Source File: image_process.py    From Advanced_Lane_Lines with MIT License 6 votes vote down vote up
def draw_lane_fit(undist, warped ,Minv, left_fitx, right_fitx, ploty):
	# Drawing
	# Create an image to draw the lines on
	warp_zero = np.zeros_like(warped).astype(np.uint8)
	color_warp = np.dstack((warp_zero, warp_zero, warp_zero))

	# Recast the x and y points into usable format for cv2.fillPoly()
	pts_left = np.array([np.transpose(np.vstack([left_fitx, ploty]))])
	pts_right = np.array([np.flipud(np.transpose(np.vstack([right_fitx, ploty])))])
	pts = np.hstack((pts_left, pts_right))

	# Draw the lane onto the warped blank image
	cv2.fillPoly(color_warp, np.int_([pts]), (0,255,0))

	# Warp the blank back to original image space using inverse perspective matrix(Minv)
	newwarp = cv2.warpPerspective(color_warp, Minv, (undist.shape[1], undist.shape[0]))
	# Combine the result with the original image
	result = cv2.addWeighted(undist, 1, newwarp, 0.3, 0)

	return result 
Example #9
Source File: visualization.py    From 2D-Motion-Retargeting with MIT License 6 votes vote down vote up
def motion2video(motion, h, w, save_path, colors, transparency=False, motion_tgt=None, fps=25, save_frame=False):
    nr_joints = motion.shape[0]
    videowriter = imageio.get_writer(save_path, fps=fps)
    vlen = motion.shape[-1]
    if save_frame:
        frames_dir = save_path[:-4] + '-frames'
        ensure_dir(frames_dir)
    for i in tqdm(range(vlen)):
        [img, img_cropped] = joints2image(motion[:, :, i], colors, transparency, H=h, W=w, nr_joints=nr_joints)
        if motion_tgt is not None:
            [img_tgt, img_tgt_cropped] = joints2image(motion_tgt[:, :, i], colors, transparency, H=h, W=w, nr_joints=nr_joints)
            img_ori = img.copy()
            img = cv2.addWeighted(img_tgt, 0.3, img_ori, 0.7, 0)
            img_cropped = cv2.addWeighted(img_tgt, 0.3, img_ori, 0.7, 0)
            bb = bounding_box(img_cropped)
            img_cropped = img_cropped[:, bb[2]:bb[3], :]
        if save_frame:
            save_image(img_cropped, os.path.join(frames_dir, "%04d.png" % i))
        videowriter.append_data(img)
    videowriter.close() 
Example #10
Source File: toolbox.py    From stagesepx with MIT License 6 votes vote down vote up
def sharpen_frame(old: np.ndarray) -> np.ndarray:
    """
    refine the edges of an image

    - https://answers.opencv.org/question/121205/how-to-refine-the-edges-of-an-image/
    - https://stackoverflow.com/questions/4993082/how-to-sharpen-an-image-in-opencv

    :param old:
    :return:
    """

    # TODO these args are locked and can not be changed
    blur = turn_blur(old)
    smooth = cv2.addWeighted(blur, 1.5, old, -0.5, 0)
    canny = cv2.Canny(smooth, 50, 150)
    return canny 
Example #11
Source File: demo_main.py    From centerpose with MIT License 6 votes vote down vote up
def add_coco_hp(image, points, color): 
    for j in range(17):
        cv2.circle(image,
                 (points[j, 0], points[j, 1]), 2, (int(color[0]), int(color[1]), int(color[2])), -1)
                 
    stickwidth = 2
    cur_canvas = image.copy()             
    for j, e in enumerate(_kp_connections):
        if points[e].min() > 0:
            X = [points[e[0], 1], points[e[1], 1]]
            Y = [points[e[0], 0], points[e[1], 0]]
            mX = np.mean(X)
            mY = np.mean(Y)
            length = ((X[0] - X[1]) ** 2 + (Y[0] - Y[1]) ** 2) ** 0.5
            angle = math.degrees(math.atan2(X[0] - X[1], Y[0] - Y[1]))
            polygon = cv2.ellipse2Poly((int(mY),int(mX)), (int(length/2), stickwidth), int(angle), 0, 360, 1)
            cv2.fillConvexPoly(cur_canvas, polygon, (int(color[0]), int(color[1]), int(color[2])))
            image = cv2.addWeighted(image, 0.5, cur_canvas, 0.5, 0)

    return image 
Example #12
Source File: debugger.py    From centerpose with MIT License 6 votes vote down vote up
def add_coco_hp(self, points, points_prob, img_id='default'): 
        points = np.array(points, dtype=np.int32).reshape(self.num_joints, 2)
        points_prob = np.array(points_prob, dtype=np.float32).reshape(self.num_joints)

        for j in range(self.num_joints):
            if points_prob[j]>0.:
                cv2.circle(self.imgs[img_id],
                          (points[j, 0], points[j, 1]), 2, (255,255,255), -1)
                         
        stickwidth = 2
        cur_canvas = self.imgs[img_id].copy()             
        for j, e in enumerate(self.edges):
            if points_prob[e[0]] > 0. and points_prob[e[1]] > 0.:
                X = [points[e[0], 1], points[e[1], 1]]
                Y = [points[e[0], 0], points[e[1], 0]]
                mX = np.mean(X)
                mY = np.mean(Y)
                length = ((X[0] - X[1]) ** 2 + (Y[0] - Y[1]) ** 2) ** 0.5
                angle = math.degrees(math.atan2(X[0] - X[1], Y[0] - Y[1]))
                polygon = cv2.ellipse2Poly((int(mY),int(mX)), (int(length/2), stickwidth), int(angle), 0, 360, 1)
                cv2.fillConvexPoly(cur_canvas, polygon, (255, 255, 255))
                self.imgs[img_id] = cv2.addWeighted(self.imgs[img_id], 0.8, cur_canvas, 0.2, 0) 
Example #13
Source File: h5_test.py    From keras-image-segmentation with MIT License 6 votes vote down vote up
def read_h5py_example():
    h5_in = h5py.File(os.path.join(dir_path, 'data.h5'), 'r')
    print (h5_in.keys())
    print (h5_in['train']['image'].dtype)
    print (h5_in['train']['image'][0].shape)

    image_size = h5_in['train']['image'].attrs['size']
    label_size = h5_in['train']['label'].attrs['size']

    x_img = np.reshape(h5_in['train']['image'][0], tuple(image_size))
    y_img = np.reshape(h5_in['train']['label'][0], tuple(label_size))
    name = h5_in['train']['name'][0]
    print (name)
    y_img = (y_img.astype(np.float32)*255/33).astype(np.uint8)
    y_show = cv2.applyColorMap(y_img, cv2.COLORMAP_JET)
    show = cv2.addWeighted(x_img, 0.5, y_show, 0.5, 0)
    cv2.imshow("show", show)
    cv2.waitKey() 
Example #14
Source File: h5_test.py    From keras-image-segmentation with MIT License 6 votes vote down vote up
def image_copy_to_dir(mode, x_paths, y_paths):
    target_path = '/run/media/tkwoo/myWorkspace/workspace/01.dataset/03.Mask_data/cityscape'
    target_path = os.path.join(target_path, mode)

    for idx in trange(len(x_paths)):
        image = cv2.imread(x_paths[idx], 1)
        mask = cv2.imread(y_paths[idx], 0)

        image = cv2.resize(image, None, fx=0.25, fy=0.25, interpolation=cv2.INTER_LINEAR)
        mask = cv2.resize(mask, None, fx=0.25, fy=0.25, interpolation=cv2.INTER_NEAREST)

        cv2.imwrite(os.path.join(target_path, 'image', os.path.basename(x_paths[idx])), image)
        cv2.imwrite(os.path.join(target_path, 'mask', os.path.basename(y_paths[idx])), mask)

        # show = image.copy()
        # mask = (mask.astype(np.float32)*255/33).astype(np.uint8)
        # mask_color = cv2.applyColorMap(mask, cv2.COLORMAP_JET)
        # show = cv2.addWeighted(show, 0.5, mask_color, 0.5, 0.0)
        # cv2.imshow('show', show)
        # key = cv2.waitKey(1)
        # if key == 27:
        #     return 
Example #15
Source File: seg_parser.py    From openseg.pytorch with MIT License 6 votes vote down vote up
def parse_img_seg(self, image_file, label_file):
        if image_file is None or not os.path.exists(image_file):
            Log.error('Image file: {} not existed.'.format(image_file))
            return

        if label_file is None or not os.path.exists(label_file):
            Log.error('Label file: {} not existed.'.format(label_file))
            return

        image_canvas = cv2.imread(image_file)  # B, G, R order.

        mask_canvas = self.colorize(np.array(Image.open(label_file).convert('P')))
        image_canvas = cv2.addWeighted(image_canvas, 0.6, mask_canvas, 0.4, 0)

        cv2.imshow('main', image_canvas)
        cv2.waitKey() 
Example #16
Source File: seg_parser.py    From openseg.pytorch with MIT License 6 votes vote down vote up
def parse_dir_seg(self, image_dir, label_dir):
        if image_dir is None or not os.path.exists(image_dir):
            Log.error('Image Dir: {} not existed.'.format(image_dir))
            return

        if label_dir is None or not os.path.exists(label_dir):
            Log.error('Label Dir: {} not existed.'.format(label_dir))
            return

        for image_file in os.listdir(image_dir):
            shotname, extension = os.path.splitext(image_file)
            Log.info(image_file)
            image_canvas = cv2.imread(os.path.join(image_dir, image_file))  # B, G, R order.
            label_file = os.path.join(label_dir, '{}.png'.format(shotname))
            mask_canvas = self.colorize(np.array(Image.open(label_file).convert('P')))
            image_canvas = cv2.addWeighted(image_canvas, 0.6, mask_canvas, 0.4, 0)

            cv2.imshow('main', image_canvas)
            cv2.waitKey() 
Example #17
Source File: test.py    From Face-skin-hair-segmentaiton-and-skin-color-evaluation with Apache License 2.0 6 votes vote down vote up
def vis_parsing_maps(im, parsing_anno, data_name):
    part_colors = [[255, 255, 255], [0, 255, 0], [255, 0, 0]]

    if data_name == 'figaro1k':
        part_colors = [[255, 255, 255], [255, 0, 0]]

    im = np.array(im)
    vis_im = im.copy().astype(np.uint8)
    vis_parsing_anno_color = np.zeros(
        (parsing_anno.shape[0], parsing_anno.shape[1], 3))

    for pi in range(len(part_colors)):
        index = np.where(parsing_anno == pi)
        vis_parsing_anno_color[index[0], index[1], :] = part_colors[pi]
    vis_parsing_anno_color = vis_parsing_anno_color.astype(np.uint8)

    # Guided filter
    # vis_parsing_anno_color = cv.ximgproc.guidedFilter(
    #     guide=vis_im, src=vis_parsing_anno_color, radius=4, eps=50, dDepth=-1)
    vis_im = cv.addWeighted(vis_im, 0.7, vis_parsing_anno_color, 0.3, 0)

    return vis_im 
Example #18
Source File: utils.py    From edafa with MIT License 6 votes vote down vote up
def change_brightness(img,bits=8):
	"""
	Randomly change img brightness

	:param img: input image
	:param bits: number of bits to represent a single color value

	:returns: transformed image
	"""
	MAX = get_max(bits)

	brightness = np.random.choice([-MAX//2,-MAX//4,0,MAX//4,MAX//2],1)

	if brightness > 0:
		shadow = brightness
		highlight = MAX
	else:
		shadow = 0
		highlight = MAX + brightness
	alpha_b = (highlight - shadow)/MAX
	gamma_b = shadow

	buf = cv2.addWeighted(img, alpha_b, img, 0, gamma_b)

	return buf 
Example #19
Source File: utils.py    From edafa with MIT License 6 votes vote down vote up
def change_contrast(img,bits=8):
	"""
	Randomly change img contrast

	:param img: input image
	:param bits: number of bits to represent a single color value

	:returns: transformed image
	"""
	MAX = get_max(bits)

	contrast = np.random.choice([-MAX//4,-MAX//8,0,MAX//8,MAX//4],1)


	f = (MAX//2)*(contrast + (MAX//2))/((MAX//2)*(MAX//2-contrast) +1)
	alpha_c = f
	gamma_c = (MAX//2)*(1-f)

	buf = cv2.addWeighted(img, alpha_c, img, 0, gamma_c)

	return buf 
Example #20
Source File: visualization_utils_cv2.py    From PythonPilot with Apache License 2.0 6 votes vote down vote up
def draw_mask_on_image_array_cv(image, mask, color=(0, 0, 255), alpha=0.4):
  """Draws mask on an image.
  Args:
    image: uint8 numpy array with shape (img_height, img_height, 3)
    mask: a uint8 numpy array of shape (img_height, img_height) with
      values between either 0 or 1.
    color: color to draw the keypoints with. Default is red.
    alpha: transparency value between 0 and 1. (default: 0.4)
  Raises:
    ValueError: On incorrect data type for image or masks.
  """
  if image.dtype != np.uint8:
    raise ValueError('`image` not of type np.uint8')
  if mask.dtype != np.uint8:
    raise ValueError('`mask` not of type np.uint8')
  if np.any(np.logical_and(mask != 1, mask != 0)):
    raise ValueError('`mask` elements should be in [0, 1]')
  if image.shape[:2] != mask.shape:
    raise ValueError('The image has spatial dimensions %s but the mask has '
                     'dimensions %s' % (image.shape[:2], mask.shape))
  mask = STANDARD_COLORS_ARRAY[mask]
  # cv2.addWeighted(cv_bgr_under, alpha_under, cv_bgr_upper, alpha_upper, gamma, output_image)
  cv2.addWeighted(mask, alpha, image, 1.0, 0, image)
  return 
Example #21
Source File: write_video.py    From fpl with MIT License 6 votes vote down vote up
def draw_prediction(img_dir, b, offset_g, offset_p, predictions, img_offset, no_pred=False, no_gt=False):
        past, ground_truth, pose, vid, frame, pid, flipped = b[:7]
        vid, frame, pid, flipped, py, pe, pp, err, traj_type = predictions[vid][str(frame)][str(pid)]
        predicted = np.array(py)[...,:2]
        im = cv2.imread(os.path.join(img_dir, "rgb_{:05d}.jpg".format(int(frame) + img_offset)))
        im = cv2.addWeighted(im, args.ratio, im, 0.0, 0)
        cv2.circle(im, (int(past[0][0]), int(past[0][1])), args.size_circle, color_ps, -1)
        im = draw_line(im, past, color_ps, 1.0, args.thick)
        im = draw_x(im, past[-1], color_ps, 1.0, args.size_x)

        if not args.no_gt:
            if offset_g > 0:
                im = draw_dotted_line(im, ground_truth[:offset_g+1], color_gt, 1.0, args.thick)
            if offset_g > -1:
                cv2.circle(im, (int(ground_truth[0][0]), int(ground_truth[0][1])), args.size_circle, color_gt, -1)
                im = draw_x(im, ground_truth[offset_g], color_gt, 1.0, args.size_x)

        if not no_pred:
            if offset_p > 0:
                im = draw_dotted_line(im, predicted[:offset_p+1], color_pr, 1.0, args.thick, 0.7)
            if offset_p > -1:
                im = draw_x(im, predicted[offset_p], color_pr, 1.0, args.size_x)
        return im 
Example #22
Source File: tracker.py    From KCF-DSST-py with MIT License 6 votes vote down vote up
def train_scale(self, image, ini=False):
        xsf = self.get_scale_sample(image)

        # Adjust ysf to the same size as xsf in the first time
        if ini:
            totalSize = xsf.shape[0]
            self.ysf = cv2.repeat(self.ysf, totalSize, 1)

        # Get new GF in the paper (delta A)
        new_sf_num = cv2.mulSpectrums(self.ysf, xsf, 0, conjB=True)

        new_sf_den = cv2.mulSpectrums(xsf, xsf, 0, conjB=True)
        new_sf_den = cv2.reduce(real(new_sf_den), 0, cv2.REDUCE_SUM)

        if ini:
            self.sf_den = new_sf_den
            self.sf_num = new_sf_num
        else:
            # Get new A and new B
            self.sf_den = cv2.addWeighted(self.sf_den, (1 - self.scale_lr), new_sf_den, self.scale_lr, 0)
            self.sf_num = cv2.addWeighted(self.sf_num, (1 - self.scale_lr), new_sf_num, self.scale_lr, 0)

        self.update_roi()

    # 检测当前图像尺度 
Example #23
Source File: layer_utils.py    From python_video_stab with MIT License 6 votes vote down vote up
def layer_blend(foreground, background, foreground_alpha=.6):
    """blend a foreground image over background (wrapper for cv2.addWeighted)

    :param foreground: image to be laid over top of background image
    :param background: image to over laid with foreground image
    :param foreground_alpha: alpha to apply to foreground; (1 - foreground_alpha) applied to background
    :return: return combined image where foreground is laid over background with alpha

    >>> from vidstab import VidStab, layer_overlay, layer_blend
    >>>
    >>> stabilizer = VidStab()
    >>>
    >>> stabilizer.stabilize(input_path='my_shaky_video.avi',
    >>>                      output_path='stabilized_output.avi',
    >>>                      border_size=100,
    >>>                      layer_func=layer_blend)
    """
    cv2.addWeighted(foreground, foreground_alpha,
                    background, 1 - foreground_alpha, 0, background)

    return background 
Example #24
Source File: net_utils.py    From Distilling-Object-Detectors with MIT License 6 votes vote down vote up
def draw_box(img, box, label='person', conf=None, color=(0, 255, 0)):
#in cv2, it is B G R not RBG
    # assert type(box) == list, 'box must be xmin, xmax, ymin, ymax'
    # xmin, xmax, ymin, ymax = box
    xmin, ymin, xmax, ymax = box
    xmin, xmax, ymin, ymax = int(xmin), int(xmax), int(ymin), int(ymax)
    img_box = np.copy(img)
    cv2.rectangle(img_box, (xmin, ymin), (xmax, ymax), color, 2)
    cv2.rectangle(img_box, (xmin - 1, ymin), (xmax + 1, ymin - 20), color, cv2.FILLED)
    font = cv2.FONT_HERSHEY_SIMPLEX
    if conf:
        cv2.putText(img_box, label, (xmin + 5, ymin - 5), font, 0.5,
                    (0, 0, 0), 2, 100)
        cv2.putText(img_box, '%.2f' % conf, (xmin + 5, ymin +20), font, 0.5,
                    (0, 0, 255), 2, 100)
    else:
        cv2.putText(img_box, label, (xmin + 5, ymin - 5), font, 1.0,
                    (0, 0, 0), 2, 100)
    alpha = 0.8
    cv2.addWeighted(img_box, alpha, img, 1. - alpha, 0, img) 
Example #25
Source File: blend.py    From imgaug with MIT License 6 votes vote down vote up
def _blend_alpha_uint8_single_alpha_(image_fg, image_bg, alpha, inplace):
    # here we are not guarantueed that inputs have ndim=3, can be ndim=2
    result = cv2.addWeighted(
        _normalize_cv2_input_arr_(image_fg),
        alpha,
        _normalize_cv2_input_arr_(image_bg),
        beta=(1 - alpha),
        gamma=0.0,
        dst=image_fg if inplace else None
    )
    if result.ndim == 2 and image_fg.ndim == 3:
        return result[:, :, np.newaxis]
    return result


# Added in 0.5.0. 
Example #26
Source File: mask.py    From tf-cpn with MIT License 6 votes vote down vote up
def showMask(img_obj):
    img = cv2.imread(img_obj['fpath'])
    img_ori = img.copy()
    gtmasks = img_obj['gtmasks']
    n = len(gtmasks)
    print(img.shape)
    for i, mobj in enumerate(gtmasks):
        if not (type(mobj['mask']) is list):
            print("Pass a RLE mask")
            continue
        else:
            pts = np.round(np.asarray(mobj['mask'][0]))
            pts = pts.reshape(pts.shape[0] // 2, 2)
            pts = np.int32(pts)
            color = np.uint8(np.random.rand(3) * 255).tolist()
            cv2.fillPoly(img, [pts], color)
    cv2.addWeighted(img, 0.5, img_ori, 0.5, 0, img)
    cv2.imshow("Mask", img)
    cv2.waitKey(0) 
Example #27
Source File: visualization.py    From SSENet-pytorch with MIT License 6 votes vote down vote up
def color_pro(pro, img=None, mode='hwc'):
	H, W = pro.shape
	pro_255 = (pro*255).astype(np.uint8)
	pro_255 = np.expand_dims(pro_255,axis=2)
	color = cv2.applyColorMap(pro_255,cv2.COLORMAP_JET)
	color = cv2.cvtColor(color, cv2.COLOR_BGR2RGB)
	if img is not None:
		rate = 0.5
		if mode == 'hwc':
			assert img.shape[0] == H and img.shape[1] == W
			color = cv2.addWeighted(img,rate,color,1-rate,0)
		elif mode == 'chw':
			assert img.shape[1] == H and img.shape[2] == W
			img = np.transpose(img,(1,2,0))
			color = cv2.addWeighted(img,rate,color,1-rate,0)
			color = np.transpose(color,(2,0,1))
	else:
		if mode == 'chw':
			color = np.transpose(color,(2,0,1))	
	return color 
Example #28
Source File: reduce_image_by_seam_carving.py    From OpenCV-3-x-with-Python-By-Example with MIT License 6 votes vote down vote up
def compute_energy_matrix(img): 
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 
 
    # Compute X derivative of the image 
    sobel_x = cv2.Sobel(gray,cv2.CV_64F, 1, 0, ksize=3) 
 
    # Compute Y derivative of the image 
    sobel_y = cv2.Sobel(gray,cv2.CV_64F, 0, 1, ksize=3) 
 
    abs_sobel_x = cv2.convertScaleAbs(sobel_x) 
    abs_sobel_y = cv2.convertScaleAbs(sobel_y) 
 
    # Return weighted summation of the two images i.e. 0.5*X + 0.5*Y 
    return cv2.addWeighted(abs_sobel_x, 0.5, abs_sobel_y, 0.5, 0) 
 
# Find vertical seam in the input image 
Example #29
Source File: detector_utils.py    From HandGesturesDroneController with Apache License 2.0 6 votes vote down vote up
def draw_right_arrow(img,shift_arrow):
    wheel_color = (200,200,200)
    shift_from_center = 55
    overlay = img.copy()
    # (2) draw shapes:
    # (3) blend with the original:
    opacity = 0.7
    
    cv2.line(overlay,(int((img.shape[1]/2)-shift_from_center+shift_arrow*5),int(img.shape[0]/2)),(int(((img.shape[1]/2))+shift_from_center+shift_arrow*5),int(img.shape[0]/2)),wheel_color , 15)
    pts = np.array([[int(((img.shape[1]/2))+shift_from_center+shift_arrow*5)+25,int(img.shape[0]/2)]
    ,[int(((img.shape[1]/2))+shift_from_center+shift_arrow*5),int(img.shape[0]/2)-25],
    [int(((img.shape[1]/2))+shift_from_center+shift_arrow*5),int(img.shape[0]/2)+25]],
    np.int32)
    pts = pts.reshape((-1,1,2))
    # cv2.fillPoly(img,[pts],wheel_color,-1)
    cv2.fillPoly(overlay, [pts], wheel_color, 8)
    cv2.addWeighted(overlay, opacity, img, 1 - opacity, 0, img)

    return img 
Example #30
Source File: detector_utils.py    From HandGesturesDroneController with Apache License 2.0 6 votes vote down vote up
def draw_left_arrow(img,shift_arrow):
    wheel_color = (200,200,200)
    shift_from_center = 55
    overlay = img.copy()
    # (2) draw shapes:
    # (3) blend with the original:
    opacity = 0.7
    
    cv2.line(overlay,(int((img.shape[1]/2)-shift_from_center-shift_arrow*5),int(img.shape[0]/2)),(int(((img.shape[1]/2))+shift_from_center-shift_arrow*5),int(img.shape[0]/2)),wheel_color , 15)
    pts = np.array([[int(((img.shape[1]/2))-shift_from_center-shift_arrow*5)-25,int(img.shape[0]/2)]
    ,[int(((img.shape[1]/2))-shift_from_center-shift_arrow*5),int(img.shape[0]/2)-25],
    [int(((img.shape[1]/2))-shift_from_center-shift_arrow*5),int(img.shape[0]/2)+25]],
    np.int32)
    pts = pts.reshape((-1,1,2))
    # cv2.fillPoly(img,[pts],wheel_color,-1)
    cv2.fillPoly(overlay, [pts], wheel_color, 8)
    cv2.addWeighted(overlay, opacity, img, 1 - opacity, 0, img)

    return img