Python cv2 模块,BORDER_CONSTANT 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用cv2.BORDER_CONSTANT

项目:FaceDetected    作者:ttchin    | 项目源码 | 文件源码
def resize_with_pad(image, height=IMAGE_SIZE, width=IMAGE_SIZE):

    def get_padding_size(image):
        h, w, _ = image.shape
        longest_edge = max(h, w)
        top, bottom, left, right = (0, 0, 0, 0)
        if h < longest_edge:
            dh = longest_edge - h
            top = dh // 2
            bottom = dh - top
        elif w < longest_edge:
            dw = longest_edge - w
            left = dw // 2
            right = dw - left
        else:
            pass
        return top, bottom, left, right

    top, bottom, left, right = get_padding_size(image)
    BLACK = [0, 0, 0]
    constant = cv2.copyMakeBorder(image, top , bottom, left, right, cv2.BORDER_CONSTANT, value=BLACK)

    resized_image = cv2.resize(constant, (height, width))

    return resized_image
项目:SomeoneSensor    作者:samfk6    | 项目源码 | 文件源码
def resize_with_pad(image, height=IMAGE_SIZE, width=IMAGE_SIZE):

    # def get_padding_size(image):
    #     h, w, _ = image.shape
    #     longest_edge = max(h, w)
    #     top, bottom, left, right = (0, 0, 0, 0)
    #     if h < longest_edge:
    #         dh = longest_edge - h
    #         top = dh // 2
    #         bottom = dh - top
    #     elif w < longest_edge:
    #         dw = longest_edge - w
    #         left = dw // 2
    #         right = dw - left
    #     else:
    #         pass
    #     return top, bottom, left, right

    # top, bottom, left, right = get_padding_size(image)
    # BLACK = [0, 0, 0]
    # constant = cv2.copyMakeBorder(image, top , bottom, left, right, cv2.BORDER_CONSTANT, value=BLACK)

    # resized_image = cv2.resize(constant, (height, width))
    resized_image = cv2.resize(image,(IMAGE_SIZE, IMAGE_SIZE))
    return resized_image
项目:srcsim2017    作者:ZarjRobotics    | 项目源码 | 文件源码
def find_contours(mask, smooth_factor=0.005):
        """ Find the contours in a given mask """
        border = 5
        # Canny detection breaks down with the edge of the image
        my_mask = cv2.copyMakeBorder(mask, border, border, border, border,
                                     cv2.BORDER_CONSTANT, value=(0, 0, 0))

        my_mask = cv2.cvtColor(my_mask, cv2.COLOR_BGR2GRAY)

        if is_cv2():
            contours, _ = cv2.findContours(my_mask, cv2.RETR_EXTERNAL,
                                           cv2.CHAIN_APPROX_SIMPLE)
        else:
            _, contours, _ = cv2.findContours(my_mask, cv2.RETR_EXTERNAL,
                                              cv2.CHAIN_APPROX_SIMPLE)

        # shift the contours back down
        for contour in contours:
            for pnt in contour:
                if pnt[0][1] > border:
                    pnt[0][1] = pnt[0][1] - border
                else:
                    pnt[0][1] = 0
                if pnt[0][0] > border:
                    pnt[0][0] = pnt[0][0] - border
                else:
                    pnt[0][0] = 0

        closed_contours = []
        for contour in contours:
            epsilon = smooth_factor*cv2.arcLength(contour, True)
            approx = cv2.approxPolyDP(contour, epsilon, True)
            area = cv2.contourArea(approx)
            # if they are too small they are not edges
            if area < 200:
                continue
            closed_contours.append(approx)

        return closed_contours
项目:Pytorch-Deeplab    作者:speedinghzl    | 项目源码 | 文件源码
def __getitem__(self, index):
        datafiles = self.files[index]

        image = cv2.imread(datafiles["img"], cv2.IMREAD_COLOR)
        size = image.shape
        name = osp.splitext(osp.basename(datafiles["img"]))[0]

        image = np.asarray(image, np.float32)
        image -= self.mean

        img_h, img_w, _ = image.shape

        pad_h = max(self.crop_h - img_h, 0)
        pad_w = max(self.crop_w - img_w, 0)
        if pad_h > 0 or pad_w > 0:
            image = cv2.copyMakeBorder(image, 0, pad_h, 0, 
                pad_w, cv2.BORDER_CONSTANT, 
                value=(0.0, 0.0, 0.0))

        image = image.transpose((2, 0, 1))

        return image, name, size
项目:Face_Recognition    作者:AkiraXD0712    | 项目源码 | 文件源码
def resize_with_pad(image, height=IMAGE_SIZE, width=IMAGE_SIZE):

    def get_padding_size(image):
        h, w, _ = image.shape
        longest_edge = max(h, w)
        top, bottom, left, right = (0, 0, 0, 0)
        if h < longest_edge:
            dh = longest_edge - h
            top = dh // 2
            bottom = dh - top
        elif w < longest_edge:
            dw = longest_edge - w
            left = dw // 2
            right = dw - left
        else:
            pass
        return top, bottom, left, right

    top, bottom, left, right = get_padding_size(image)
    black = [0, 0, 0]
    constant = cv2.copyMakeBorder(image, top , bottom, left, right, cv2.BORDER_CONSTANT, value=black)
    resized_image = cv2.resize(constant, (height, width))

    return resized_image
项目:2017-robot    作者:frc1418    | 项目源码 | 文件源码
def preallocate(self, img):
        if self.size is None or self.size[0] != img.shape[0] or self.size[1] != img.shape[1]:
            h, w = img.shape[:2]
            self.size = (h, w)

            self.img = np.empty((h, w, 3), dtype=np.uint8)

            self.hsv = np.empty((h, w, 3), dtype=np.uint8)
            self.bin = np.empty((h, w, 1), dtype=np.uint8)
            self.bin2 = np.empty((h, w, 1), dtype=np.uint8)

            self.out = np.empty((h, w, 3), dtype=np.uint8)

            # for overlays
            self.zeros = np.zeros((h, w, 1), dtype=np.bool)
            self.black = np.zeros((h, w, 3), dtype=np.uint8)

            self.morphKernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2,2), anchor=(0,0))

        cv2.copyMakeBorder(img, 0, 0, 0, 0, cv2.BORDER_CONSTANT, value=self.RED, dst=self.out)
项目:GulpIO    作者:TwentyBN    | 项目源码 | 文件源码
def __call__(self, img):
        """
        Args:
            img (numpy.array): Image to be cropped.
        Returns:
            numpy.array: Cropped image.
        """
        sample_w = random.choice(self.sample_sizes)
        sample_h = random.choice(self.sample_sizes)
        h, w = img.shape[:2]
        x1 = random.randint(0, w - sample_w)
        y1 = random.randint(0, h - sample_h)
        if self.padding > 0:
            img = cv2.copyMakeBorder(img, self.padding, self.padding,
                                     self.padding, self.padding,
                                     cv2.BORDER_CONSTANT, value=0)
        # sample crop locations if not given
        # it is necessary to keep cropping same in a video
        img_crop = img[y1:y1+sample_h, x1:x1+sample_w]
        return img_crop
项目:GulpIO    作者:TwentyBN    | 项目源码 | 文件源码
def __call__(self, imgs):
        """
        Args:
            img (numpy.array): Image to be cropped.
        Returns:
            numpy.array: Cropped image.
        """
        sample_w = random.choice(self.sample_sizes)
        sample_h = random.choice(self.sample_sizes)
        h, w = imgs[0].shape[:2]
        x1 = random.randint(0, w - sample_w)
        y1 = random.randint(0, h - sample_h)
        for idx, img in enumerate(imgs):
            if self.padding > 0:
                img = cv2.copyMakeBorder(img, self.padding, self.padding,
                                         self.padding, self.padding,
                                         cv2.BORDER_CONSTANT, value=0)
            # sample crop locations if not given
            # it is necessary to keep cropping same in a video
            img_crop = img[y1:y1+sample_h, x1:x1+sample_w]
            imgs[idx] = img_crop
        return imgs
项目:robotpy-cscore    作者:robotpy    | 项目源码 | 文件源码
def setImage(self, img):
        '''
            Call this function when you wish to write the image to disk. Not
            every image is written to disk. Makes a copy of the image.

            :param img: A numpy array representing an OpenCV image
        '''

        if not self.active:
            return

        if self.size is None or self.size[0] != img.shape[0] or self.size[1] != img.shape[1]:
            h, w = img.shape[:2]
            self.size = (h, w)

            self.out1 = np.empty((h, w, 3), dtype=np.uint8)
            self.out2 = np.empty((h, w, 3), dtype=np.uint8)

        with self.lock:
            cv2.copyMakeBorder(img, 0, 0, 0, 0, cv2.BORDER_CONSTANT, value=(0,0,255), dst=self.out1)
            self.has_image = True
            self.lock.notify()
项目:CRC2017    作者:Ironpulse    | 项目源码 | 文件源码
def setImage(self, img):
        '''
            Call this function when you wish to write the image to disk. Not
            every image is written to disk. Makes a copy of the image.

            :param img: A numpy array representing an OpenCV image
        '''

        if not self.active:
            return

        if self.size is None or self.size[0] != img.shape[0] or self.size[1] != img.shape[1]:
            h, w = img.shape[:2]
            self.size = (h, w)

            self.out1 = np.empty((h, w, 3), dtype=np.uint8)
            self.out2 = np.empty((h, w, 3), dtype=np.uint8)

        with self.lock:
            cv2.copyMakeBorder(img, 0, 0, 0, 0, cv2.BORDER_CONSTANT, value=(0,0,255), dst=self.out1)
            self.has_image = True
            self.lock.notify()
项目:ATLeS    作者:liffiton    | 项目源码 | 文件源码
def _do_filter(self, frame):
        ''' Process a single frame. '''
        # blur to reduce noise
        frame = cv2.GaussianBlur(frame, (5, 5), 0, borderType=cv2.BORDER_CONSTANT)

        # threshold to find contiguous regions of "bright" pixels
        # ignore all "dark" (<1/8 max) pixels
        max = numpy.max(frame)
        min = numpy.min(frame)
        # if the frame is completely dark, then just return it
        if max == min:
            return frame
        threshold = min + (max - min) / 8
        _, frame = cv2.threshold(frame, threshold, 255, cv2.THRESH_BINARY)

        # filter out single pixels and other noise
        frame = cv2.erode(frame, self._element_shrink)

        # restore and join nearby regions (in case one fish has a skinny middle...)
        frame = cv2.dilate(frame, self._element_grow)

        return frame
项目:flight-stone    作者:asmateus    | 项目源码 | 文件源码
def subwindow(img, window, borderType=cv2.BORDER_CONSTANT):
    cutWindow = [x for x in window]
    limit(cutWindow, [0, 0, img.shape[1], img.shape[0]])  # modify cutWindow
    assert(cutWindow[2] > 0 and cutWindow[3] > 0)
    border = getBorder(window, cutWindow)
    res = img[cutWindow[1]:cutWindow[1] + cutWindow[3], cutWindow[0]:cutWindow[0] + cutWindow[2]]

    if(border != [0, 0, 0, 0]):
        res = cv2.copyMakeBorder(res, border[1], border[3], border[0], border[2], borderType)
    return res


# KCF tracker
项目:Simple-deCAPTCHA    作者:BLKStone    | 项目源码 | 文件源码
def showResultMat(self, imgRotated, rect_size, center, index):

        m_width = 136
        m_height = 36

        imgCorp = cv2.getRectSubPix(imgRotated,rect_size,center)
        imgCorp = cv2.copyMakeBorder(imgCorp ,30,30,30,30,cv2.BORDER_CONSTANT,value=(0,0,0))
        #constant = cv2.copyMakeBorder(closing ,30,30,30,30,cv2.BORDER_CONSTANT,value=255)

        imgCorp = self.inverseColor(imgCorp)
        print 'resize',imgCorp.shape

        if self.m_debug:
            picname = 'debug/rotate_fragment_'+str(index)+'.png'
            cv2.imwrite(picname,imgCorp)

        # imgResized = cv2.resize(imgCorp,(m_width,m_height))

        # if self.m_debug:
        #     picname = 'debug/rotate_fragment_resize_'+str(index)+'.png'
        #     cv2.imwrite(picname,imgResized)

        return imgCorp

    # ?????? 0 ? 255, 255 ? 0
项目:mxnet_tk1    作者:starimpact    | 项目源码 | 文件源码
def copyMakeBorder(src, top, bot, left, right, border_type=cv2.BORDER_CONSTANT, value=0):
    """Pad image border
    Wrapper for cv2.copyMakeBorder that uses mx.nd.NDArray

    Parameters
    ----------
    src : NDArray
        Image in (width, height, channels).
        Others are the same with cv2.copyMakeBorder

    Returns
    -------
    img : NDArray
        padded image
    """
    hdl = NDArrayHandle()
    check_call(_LIB.MXCVcopyMakeBorder(src.handle, ctypes.c_int(top), ctypes.c_int(bot),
                                       ctypes.c_int(left), ctypes.c_int(right),
                                       ctypes.c_int(border_type), ctypes.c_double(value),
                                       ctypes.byref(hdl)))
    return mx.nd.NDArray(hdl)
项目:ppap_detect    作者:ashitani    | 项目源码 | 文件源码
def pad_image(img_src,scale):
    size = tuple(np.array([img_src.shape[1], img_src.shape[0]]))
    org_h=size[1]
    org_w=size[0]

    src_r = np.sqrt((size[0]/2.0)**2+(size[1]/2.0)**2)
    dest_h = int(2*src_r * scale)
    dest_w = int(2*src_r * scale)

    dh= (dest_h-org_h)/2
    dw= (dest_w-org_w)/2

    img=img_src
    if dh>0:
        img=cv2.copyMakeBorder(img,dh,dh,0,0,cv2.BORDER_CONSTANT,value=(0,0,0,0))
    if dw>0:
        img=cv2.copyMakeBorder(img,0,0,dw,dw,cv2.BORDER_CONSTANT,value=(0,0,0,0))
    return img, [dest_h,dest_w]
项目:ppap_detect    作者:ashitani    | 项目源码 | 文件源码
def pad_image(img_src,scale):
    size = tuple(np.array([img_src.shape[1], img_src.shape[0]]))
    org_h=size[1]
    org_w=size[0]

    src_r = np.sqrt((size[0]/2.0)**2+(size[1]/2.0)**2)
    dest_h = int(2*src_r * scale)
    dest_w = int(2*src_r * scale)

    dh= (dest_h-org_h)/2
    dw= (dest_w-org_w)/2

    img=img_src
    if dh>0:
        img=cv2.copyMakeBorder(img,dh,dh,0,0,cv2.BORDER_CONSTANT,value=(0,0,0,0))
    if dw>0:
        img=cv2.copyMakeBorder(img,0,0,dw,dw,cv2.BORDER_CONSTANT,value=(0,0,0,0))
    return img, [dest_h,dest_w]
项目:kaggle_ndsb2017    作者:juliandewit    | 项目源码 | 文件源码
def random_translate_img(img, xy_range, border_mode="constant"):
    if random.random() > xy_range.chance:
        return img
    import cv2
    if not isinstance(img, list):
        img = [img]

    org_height, org_width = img[0].shape[:2]
    translate_x = random.randint(xy_range.x_min, xy_range.x_max)
    translate_y = random.randint(xy_range.y_min, xy_range.y_max)
    trans_matrix = numpy.float32([[1, 0, translate_x], [0, 1, translate_y]])

    border_const = cv2.BORDER_CONSTANT
    if border_mode == "reflect":
        border_const = cv2.BORDER_REFLECT

    res = []
    for img_inst in img:
        img_inst = cv2.warpAffine(img_inst, trans_matrix, (org_width, org_height), borderMode=border_const)
        res.append(img_inst)
    if len(res) == 1:
        res = res[0]
    xy_range.last_x = translate_x
    xy_range.last_y = translate_y
    return res
项目:kaggle_ndsb2017    作者:juliandewit    | 项目源码 | 文件源码
def random_rotate_img(img, chance, min_angle, max_angle):
    import cv2
    if random.random() > chance:
        return img
    if not isinstance(img, list):
        img = [img]

    angle = random.randint(min_angle, max_angle)
    center = (img[0].shape[0] / 2, img[0].shape[1] / 2)
    rot_matrix = cv2.getRotationMatrix2D(center, angle, scale=1.0)

    res = []
    for img_inst in img:
        img_inst = cv2.warpAffine(img_inst, rot_matrix, dsize=img_inst.shape[:2], borderMode=cv2.BORDER_CONSTANT)
        res.append(img_inst)
    if len(res) == 0:
        res = res[0]
    return res
项目:BossSensor    作者:Hironsan    | 项目源码 | 文件源码
def resize_with_pad(image, height=IMAGE_SIZE, width=IMAGE_SIZE):

    def get_padding_size(image):
        h, w, _ = image.shape
        longest_edge = max(h, w)
        top, bottom, left, right = (0, 0, 0, 0)
        if h < longest_edge:
            dh = longest_edge - h
            top = dh // 2
            bottom = dh - top
        elif w < longest_edge:
            dw = longest_edge - w
            left = dw // 2
            right = dw - left
        else:
            pass
        return top, bottom, left, right

    top, bottom, left, right = get_padding_size(image)
    BLACK = [0, 0, 0]
    constant = cv2.copyMakeBorder(image, top , bottom, left, right, cv2.BORDER_CONSTANT, value=BLACK)

    resized_image = cv2.resize(constant, (height, width))

    return resized_image
项目:kaggle_amazon_from_space    作者:N01Z3    | 项目源码 | 文件源码
def randomShiftScaleRotate(img, shift_limit=0.0625, scale_limit=0.1, rotate_limit=45, u=0.5):
    if random.random() < u:
        height, width, channel = img.shape

        angle = random.uniform(-rotate_limit, rotate_limit)  # degree
        scale = random.uniform(1 - scale_limit, 1 + scale_limit)
        dx = round(random.uniform(-shift_limit, shift_limit)) * width
        dy = round(random.uniform(-shift_limit, shift_limit)) * height

        cc = math.cos(angle / 180 * math.pi) * (scale)
        ss = math.sin(angle / 180 * math.pi) * (scale)
        rotate_matrix = np.array([[cc, -ss], [ss, cc]])

        box0 = np.array([[0, 0], [width, 0], [width, height], [0, height], ])
        box1 = box0 - np.array([width / 2, height / 2])
        box1 = np.dot(box1, rotate_matrix.T) + np.array([width / 2 + dx, height / 2 + dy])

        box0 = box0.astype(np.float32)
        box1 = box1.astype(np.float32)
        mat = cv2.getPerspectiveTransform(box0, box1)
        img = cv2.warpPerspective(img, mat, (width, height), flags=cv2.INTER_LINEAR,
                                  borderMode=cv2.BORDER_REFLECT_101)  # cv2.BORDER_CONSTANT, borderValue = (0, 0, 0))  #cv2.BORDER_REFLECT_101

    return img
项目:Kaggle-Cat-vs-Dog-Tensorflow-CNN    作者:jshin49    | 项目源码 | 文件源码
def process_image(img, img_size, pixel_depth):
    '''
        Maintain aspect ratio of image while resizing
    '''
    img = cv2.imread(img, cv2.IMREAD_COLOR)
    if (img.shape[0] >= img.shape[1]):  # height is greater than width
        resizeto = (img_size, int(
            round(img_size * (float(img.shape[1]) / img.shape[0]))))
    else:
        resizeto = (
            int(round(img_size * (float(img.shape[0]) / img.shape[1]))), img_size)

    img = cv2.resize(img, (resizeto[1], resizeto[
        0]), interpolation=cv2.INTER_CUBIC)
    img = cv2.copyMakeBorder(
        img, 0, img_size - img.shape[0], 0, img_size - img.shape[1], cv2.BORDER_CONSTANT, 0)

    img = normalize_image(img, pixel_depth)

    return img[:, :, ::-1]  # turn into rgb format
项目:guided-filter    作者:lisabug    | 项目源码 | 文件源码
def test_box_filter_zero(self):
        I = np.array(range(1, 50)).reshape(7, 7).astype(np.float32)
        r = 2
        ret1 = cv.smooth.box_filter(I, r, normalize=True, border_type='zero')
        ret2 = cv2.blur(I, (5,5), borderType=cv2.BORDER_CONSTANT)
        self.assertTrue(np.array_equal(ret1, ret2))
项目:pybot    作者:spillai    | 项目源码 | 文件源码
def _pad_image(self, im): 
        return cv2.copyMakeBorder(im,19,20,24,25,cv2.BORDER_CONSTANT,value=[0,0,0] if im.ndim == 3 else 0)
项目:pybot    作者:spillai    | 项目源码 | 文件源码
def im_pad(im, pad=3, value=0): 
    return cv2.copyMakeBorder(im, pad, pad, pad, pad, cv2.BORDER_CONSTANT, value)
项目:spikefuel    作者:duguyue100    | 项目源码 | 文件源码
def create_border(frame, height, width, color):
    """Add constant border for the frame.

    The original frame will be displayed at the center of the monitor

    Parameters
    ----------
    frame : OpenCV Mat
        the original frame of image or video
    height : int
        height of the monitor
    width : int
        width of the monitor
    color : list
        the color of the border

    Returns
    -------
    new_frame : OpenCV Mat
        border added OpenCV Mat
    """
    vert = height/2-frame.shape[0]/2
    hor = width/2-frame.shape[1]/2

    new_frame = cv2.copyMakeBorder(src=frame, top=vert, bottom=vert, left=hor,
                                   right=hor, borderType=cv2.BORDER_CONSTANT,
                                   value=color)

    return new_frame
项目:spikefuel    作者:duguyue100    | 项目源码 | 文件源码
def rescale_image(frame, swin_h, swin_w, color=[255, 0, 0]):
    """Rescale image to size of working window.

    Parameters
    ---------
    frame : numpy.ndarray
        given image or frame
    swin_h : int
        width of the working window
    swin_w : int
        height of the working window
    color : list
        The background color of appended border
    """
    # new_frame = frame.copy()
    # try to save memory
    new_frame = frame
    frame_h = frame.shape[0]
    frame_w = frame.shape[1]
    # if the ratio is different, then append border
    if (float(swin_h)/float(swin_w)) != (float(frame_h)/float(frame_w)):
        # do something
        if (float(frame_h)/float(frame_w)) > (float(swin_h)/float(swin_w)):
            w_append = int((frame_h*swin_w-swin_h*frame_w)/swin_h)
            new_frame = cv2.copyMakeBorder(src=new_frame, top=0, bottom=0,
                                           left=w_append/2, right=w_append/2,
                                           borderType=cv2.BORDER_CONSTANT,
                                           value=color)

        elif (float(frame_h)/float(frame_w)) < (float(swin_h)/float(swin_w)):
            h_append = int((swin_h*frame_w-frame_h*swin_w)/swin_w)
            new_frame = cv2.copyMakeBorder(src=new_frame, top=h_append/2,
                                           bottom=h_append/2, left=0, right=0,
                                           borderType=cv2.BORDER_CONSTANT,
                                           value=color)

    new_frame = cv2.resize(new_frame, (swin_w, swin_h),
                           interpolation=cv2.INTER_AREA)

    return new_frame
项目:diracnets    作者:szagoruyko    | 项目源码 | 文件源码
def __init__(self, padding, borderType=cv2.BORDER_CONSTANT, borderValue=0):
        assert isinstance(padding, numbers.Number)
        self.padding = padding
        self.borderType = borderType
        self.borderValue = borderValue
项目:DogvsCat    作者:aysebilgegunduz    | 项目源码 | 文件源码
def read_image(file_path):
    img = cv2.imread(file_path, cv2.IMREAD_COLOR)  # cv2.IMREAD_GRAYSCALE
    if (img.shape[0] >= img.shape[1]):  # height is greater than width
        resizeto = (IMAGE_SIZE, int(round(IMAGE_SIZE * (float(img.shape[1]) / img.shape[0]))));
    else:
        resizeto = (int(round(IMAGE_SIZE * (float(img.shape[0]) / img.shape[1]))), IMAGE_SIZE);

    img2 = cv2.resize(img, (resizeto[1], resizeto[0]), interpolation=cv2.INTER_CUBIC)
    img3 = cv2.copyMakeBorder(img2, 0, IMAGE_SIZE - img2.shape[0], 0, IMAGE_SIZE - img2.shape[1], cv2.BORDER_CONSTANT,
                              0)

    return img3[:, :, ::-1]  # turn into rgb format
项目:cvcalib    作者:Algomorph    | 项目源码 | 文件源码
def prep_img_save(img, b=5):
    return cv2.normalize(cv2.copyMakeBorder(img, b, b, b, b, cv2.BORDER_CONSTANT, value=0), 0, 255,
                  cv2.NORM_MINMAX).astype(np.uint8)
项目:cvcalib    作者:Algomorph    | 项目源码 | 文件源码
def find_chessboard_corners(greyscale_image, neighborhood_size=10, candidate_threshold=.5):
    candidates = find_candidates(greyscale_image, neighborhood_size, candidate_threshold)
    bordered_image = cv2.copyMakeBorder(greyscale_image, neighborhood_size, neighborhood_size, neighborhood_size,
                                        neighborhood_size, cv2.BORDER_CONSTANT, value=0)
    detected_corners = []
    windows = []
    grad_mags = []
    templates = []
    ix_candidate = 0
    for candidate in candidates:
        print(ix_candidate)
        coord = candidate
        window = greyscale_image[coord[0] - neighborhood_size:coord[0] + neighborhood_size + 1,
                 coord[1] - neighborhood_size:coord[1] + neighborhood_size + 1]
        hist, grad_mag = __filter_candidate(bordered_image, candidate, neighborhood_size)
        win_b = cv2.copyMakeBorder(window, 5, 5, 5, 5, cv2.BORDER_CONSTANT, value=0)
        windows.append(win_b)
        grad_mags.append(prep_img_save(grad_mag))
        angles = __find_dominant_directions(hist)
        if angles is not None:
            template = __build_corner_template(neighborhood_size * 2 + 1, angles)
            templates.append(prep_img_save(template))
        else:
            templates.append(np.zeros_like(win_b))
        ix_candidate += 1
        # if __filter_candidate(bordered_image, candidate, neighborhood_size):
        #      detected_corners.append(candidate)

    ch_test = np.vstack((np.hstack(windows), np.hstack(grad_mags), np.hstack(templates)))
    cv2.imwrite("~/Desktop/TMP/ch_test01.png", ch_test)

    detected_corners = np.array(detected_corners)
    # return detected_corners

    return candidates
项目:doc2text    作者:jlsutherland    | 项目源码 | 文件源码
def rotate(image, theta):
    (h, w) = image.shape[:2]
    center = (w / 2, h / 2)
    M = cv2.getRotationMatrix2D(center, theta, 1)
    rotated = cv2.warpAffine(image, M, (int(w), int(h)), cv2.INTER_LINEAR,
                             borderMode=cv2.BORDER_CONSTANT, borderValue=(255, 255, 255))
    return rotated
项目:tf-openpose    作者:ildoonet    | 项目源码 | 文件源码
def pose_rotation(meta):
    deg = random.uniform(-40.0, 40.0)
    img = meta.img

    center = (img.shape[1] * 0.5, img.shape[0] * 0.5)
    rot_m = cv2.getRotationMatrix2D((center[0] - 0.5, center[1] - 0.5), deg, 1)
    ret = cv2.warpAffine(img, rot_m, img.shape[1::-1], flags=cv2.INTER_AREA, borderMode=cv2.BORDER_CONSTANT)
    if img.ndim == 3 and ret.ndim == 2:
        ret = ret[:, :, np.newaxis]
    neww, newh = RotationAndCropValid.largest_rotated_rect(ret.shape[1], ret.shape[0], deg)
    neww = min(neww, ret.shape[1])
    newh = min(newh, ret.shape[0])
    newx = int(center[0] - neww * 0.5)
    newy = int(center[1] - newh * 0.5)
    # print(ret.shape, deg, newx, newy, neww, newh)
    img = ret[newy:newy + newh, newx:newx + neww]

    # adjust meta data
    adjust_joint_list = []
    for joint in meta.joint_list:
        adjust_joint = []
        for point in joint:
            if point[0] < -100 or point[1] < -100:
                adjust_joint.append((-1000, -1000))
                continue
            # if point[0] <= 0 or point[1] <= 0:
            #     adjust_joint.append((-1, -1))
            #     continue
            x, y = _rotate_coord((meta.width, meta.height), (newx, newy), point, deg)
            adjust_joint.append((x, y))
        adjust_joint_list.append(adjust_joint)

    meta.joint_list = adjust_joint_list
    meta.width, meta.height = neww, newh
    meta.img = img

    return meta
项目:imgProcessor    作者:radjkarl    | 项目源码 | 文件源码
def correct(self, image, keepSize=False, borderValue=0):
        '''
        remove lens distortion from given image
        '''
        image = imread(image)
        (h, w) = image.shape[:2]
        mapx, mapy = self.getUndistortRectifyMap(w, h)
        self.img = cv2.remap(image, mapx, mapy, cv2.INTER_LINEAR,
                             borderMode=cv2.BORDER_CONSTANT,
                             borderValue=borderValue
                             )
        if not keepSize:
            xx, yy, ww, hh = self.roi
            self.img = self.img[yy: yy + hh, xx: xx + ww]
        return self.img
项目:Pytorch-Deeplab    作者:speedinghzl    | 项目源码 | 文件源码
def __getitem__(self, index):
        datafiles = self.files[index]
        image = cv2.imread(datafiles["img"], cv2.IMREAD_COLOR)
        label = cv2.imread(datafiles["label"], cv2.IMREAD_GRAYSCALE)
        size = image.shape
        name = datafiles["name"]
        if self.scale:
            image, label = self.generate_scale_label(image, label)
        image = np.asarray(image, np.float32)
        image -= self.mean
        img_h, img_w = label.shape
        pad_h = max(self.crop_h - img_h, 0)
        pad_w = max(self.crop_w - img_w, 0)
        if pad_h > 0 or pad_w > 0:
            img_pad = cv2.copyMakeBorder(image, 0, pad_h, 0, 
                pad_w, cv2.BORDER_CONSTANT, 
                value=(0.0, 0.0, 0.0))
            label_pad = cv2.copyMakeBorder(label, 0, pad_h, 0, 
                pad_w, cv2.BORDER_CONSTANT,
                value=(self.ignore_label,))
        else:
            img_pad, label_pad = image, label

        img_h, img_w = label_pad.shape
        h_off = random.randint(0, img_h - self.crop_h)
        w_off = random.randint(0, img_w - self.crop_w)
        # roi = cv2.Rect(w_off, h_off, self.crop_w, self.crop_h);
        image = np.asarray(img_pad[h_off : h_off+self.crop_h, w_off : w_off+self.crop_w], np.float32)
        label = np.asarray(label_pad[h_off : h_off+self.crop_h, w_off : w_off+self.crop_w], np.float32)
        #image = image[:, :, ::-1]  # change to BGR
        image = image.transpose((2, 0, 1))
        if self.is_mirror:
            flip = np.random.choice(2) * 2 - 1
            image = image[:, :, ::flip]
            label = label[:, ::flip]

        return image.copy(), label.copy(), np.array(size), name
项目:Pytorch-Deeplab    作者:speedinghzl    | 项目源码 | 文件源码
def __getitem__(self, index):
        datafiles = self.files[index]
        image = cv2.imread(datafiles["img"], cv2.IMREAD_COLOR)
        size = image.shape
        name = osp.splitext(osp.basename(datafiles["img"]))[0]
        image = np.asarray(image, np.float32)
        image -= self.mean

        img_h, img_w, _ = image.shape
        pad_h = max(self.crop_h - img_h, 0)
        pad_w = max(self.crop_w - img_w, 0)
        if pad_h > 0 or pad_w > 0:
            image = cv2.copyMakeBorder(image, 0, pad_h, 0, 
                pad_w, cv2.BORDER_CONSTANT, 
                value=(0.0, 0.0, 0.0))
        image = image.transpose((2, 0, 1))
        return image, name, size
项目:Pytorch-Deeplab    作者:speedinghzl    | 项目源码 | 文件源码
def __getitem__(self, index):
        datafiles = self.files[index]

        image = cv2.imread(datafiles["img"], cv2.IMREAD_COLOR)
        label = cv2.imread(datafiles["label"], cv2.IMREAD_GRAYSCALE)
        size = image.shape
        name = datafiles["name"]

        if self.scale:
            image, label = self.generate_scale_label(image, label)

        image = np.asarray(image, np.float32)
        image -= self.mean
        img_h, img_w = label.shape
        pad_h = max(self.crop_h - img_h, 0)
        pad_w = max(self.crop_w - img_w, 0)
        if pad_h > 0 or pad_w > 0:
            img_pad = cv2.copyMakeBorder(image, 0, pad_h, 0, 
                pad_w, cv2.BORDER_CONSTANT, 
                value=(0.0, 0.0, 0.0))
            label_pad = cv2.copyMakeBorder(label, 0, pad_h, 0, 
                pad_w, cv2.BORDER_CONSTANT,
                value=(self.ignore_label,))
        else:
            img_pad, label_pad = image, label
        img_h, img_w = label_pad.shape

        h_off = random.randint(0, img_h - self.crop_h)
        w_off = random.randint(0, img_w - self.crop_w)

        # roi = cv2.Rect(w_off, h_off, self.crop_w, self.crop_h);
        image = np.asarray(img_pad[h_off : h_off+self.crop_h, w_off : w_off+self.crop_w], np.float32)
        label = np.asarray(label_pad[h_off : h_off+self.crop_h, w_off : w_off+self.crop_w], np.float32)
        #image = image[:, :, ::-1]  # change to BGR
        image = image.transpose((2, 0, 1))
        if self.is_mirror:
            flip = np.random.choice(2) * 2 - 1
            image = image[:, :, ::flip]
            label = label[:, ::flip]

        return image.copy(), label.copy(), np.array(size), name
项目:2017-robot    作者:frc1418    | 项目源码 | 文件源码
def threshold(self, img):
        cv2.cvtColor(img, cv2.COLOR_BGR2HSV, dst=self.hsv)
        cv2.inRange(self.hsv, self.thresh_low, self.thresh_high, dst=self.bin)

        cv2.morphologyEx(self.bin, cv2.MORPH_CLOSE, self.morphKernel, dst=self.bin2, iterations=1)

        if self.draw_thresh:
            b = (self.bin2 != 0)
            cv2.copyMakeBorder(self.black, 0, 0, 0, 0, cv2.BORDER_CONSTANT, value=self.RED, dst=self.out)
            self.out[np.dstack((b, b, b))] = 255

        return self.bin2
项目:DeepPoseComparison    作者:ynaka81    | 项目源码 | 文件源码
def _pad_image(self, image, joint):
        height, width, _ = image.shape
        shape = np.array((width, height))
        residual = (self.image_size - shape).clip(0, self.image_size)
        left, top = residual/2
        right, bottom = residual - residual/2
        padded_image = cv2.copyMakeBorder(
            image, top, bottom, left, right, cv2.BORDER_CONSTANT, value=0)
        moved_joint = joint + (left, top, 0)
        return padded_image, moved_joint
项目:GulpIO    作者:TwentyBN    | 项目源码 | 文件源码
def __init__(self, size, padding=0, pad_method=cv2.BORDER_CONSTANT):
        if isinstance(size, numbers.Number):
            self.size = (int(size), int(size))
        else:
            self.size = size
        self.padding = padding
        self.pad_method = pad_method
项目:GulpIO    作者:TwentyBN    | 项目源码 | 文件源码
def __init__(self, size, padding=0, pad_method=cv2.BORDER_CONSTANT):
        if isinstance(size, numbers.Number):
            self.size = (int(size), int(size))
        else:
            self.size = size
        self.padding = padding
        self.pad_method = pad_method
项目:unet-tensorflow    作者:timctho    | 项目源码 | 文件源码
def randomShiftScaleRotate(image, mask, mask_w,
                           shift_limit=(-0.0625, 0.0625),
                           scale_limit=(-0.1, 0.1),
                           rotate_limit=(-45, 45), aspect_limit=(0, 0),
                           borderMode=cv2.BORDER_CONSTANT, u=0.5):
    if np.random.random() < u:
        height, width, channel = image.shape

        angle = np.random.uniform(rotate_limit[0], rotate_limit[1])  # degree
        scale = np.random.uniform(1 + scale_limit[0], 1 + scale_limit[1])
        aspect = np.random.uniform(1 + aspect_limit[0], 1 + aspect_limit[1])
        sx = scale * aspect / (aspect ** 0.5)
        sy = scale / (aspect ** 0.5)
        dx = round(np.random.uniform(shift_limit[0], shift_limit[1]) * width)
        dy = round(np.random.uniform(shift_limit[0], shift_limit[1]) * height)

        cc = np.math.cos(angle / 180 * np.math.pi) * sx
        ss = np.math.sin(angle / 180 * np.math.pi) * sy
        rotate_matrix = np.array([[cc, -ss], [ss, cc]])

        box0 = np.array([[0, 0], [width, 0], [width, height], [0, height], ])
        box1 = box0 - np.array([width / 2, height / 2])
        box1 = np.dot(box1, rotate_matrix.T) + np.array([width / 2 + dx, height / 2 + dy])

        box0 = box0.astype(np.float32)
        box1 = box1.astype(np.float32)
        mat = cv2.getPerspectiveTransform(box0, box1)
        image = cv2.warpPerspective(image, mat, (width, height), flags=cv2.INTER_LINEAR, borderMode=borderMode,
                                    borderValue=(
                                        0, 0,
                                        0,))
        mask = cv2.warpPerspective(mask, mat, (width, height), flags=cv2.INTER_LINEAR, borderMode=borderMode,
                                   borderValue=(
                                       0, 0,
                                       0,))
        mask_w = cv2.warpPerspective(mask, mat, (width, height), flags=cv2.INTER_LINEAR, borderMode=borderMode,
                                     borderValue=(
                                         0, 0,
                                         0,))

    return image, mask, mask_w
项目:unet-tensorflow    作者:timctho    | 项目源码 | 文件源码
def randomShiftScaleRotate(image, mask, mask_w,
                           shift_limit=(-0.0625, 0.0625),
                           scale_limit=(-0.1, 0.1),
                           rotate_limit=(-45, 45), aspect_limit=(0, 0),
                           borderMode=cv2.BORDER_CONSTANT, u=0.5):
    if np.random.random() < u:
        height, width, channel = image.shape

        angle = np.random.uniform(rotate_limit[0], rotate_limit[1])  # degree
        scale = np.random.uniform(1 + scale_limit[0], 1 + scale_limit[1])
        aspect = np.random.uniform(1 + aspect_limit[0], 1 + aspect_limit[1])
        sx = scale * aspect / (aspect ** 0.5)
        sy = scale / (aspect ** 0.5)
        dx = round(np.random.uniform(shift_limit[0], shift_limit[1]) * width)
        dy = round(np.random.uniform(shift_limit[0], shift_limit[1]) * height)

        cc = np.math.cos(angle / 180 * np.math.pi) * sx
        ss = np.math.sin(angle / 180 * np.math.pi) * sy
        rotate_matrix = np.array([[cc, -ss], [ss, cc]])

        box0 = np.array([[0, 0], [width, 0], [width, height], [0, height], ])
        box1 = box0 - np.array([width / 2, height / 2])
        box1 = np.dot(box1, rotate_matrix.T) + np.array([width / 2 + dx, height / 2 + dy])

        box0 = box0.astype(np.float32)
        box1 = box1.astype(np.float32)
        mat = cv2.getPerspectiveTransform(box0, box1)
        image = cv2.warpPerspective(image, mat, (width, height), flags=cv2.INTER_LINEAR, borderMode=borderMode,
                                    borderValue=(
                                        0, 0,
                                        0,))
        mask = cv2.warpPerspective(mask, mat, (width, height), flags=cv2.INTER_LINEAR, borderMode=borderMode,
                                   borderValue=(
                                       0, 0,
                                       0,))
        mask_w = cv2.warpPerspective(mask_w, mat, (width, height), flags=cv2.INTER_LINEAR, borderMode=borderMode,
                                     borderValue=(
                                         0, 0,
                                         0,))

    return image, mask, mask_w
项目:DeHaze    作者:XierHacker    | 项目源码 | 文件源码
def getDarkMap(img,pitchSize=9):
    darkMap=np.zeros(shape=(img.shape[0],img.shape[1]),dtype=np.uint8)
    #padding,and darkMap has the same shape with the img
   # print ("shape of darkmap",darkMap.shape[0],darkMap.shape[1])
    padSize=(pitchSize-1)//2
    #print ("type of pitchsize",type(padSize))
    pad=cv2.copyMakeBorder(img,padSize,padSize,padSize,padSize,cv2.BORDER_CONSTANT,value=255)
    for i in range(darkMap.shape[0]):
        for j in range(darkMap.shape[1]):
            darkMap[i,j]=pad[i:i+pitchSize,j:j+pitchSize].min()

    return pad,darkMap
项目:DeHaze    作者:XierHacker    | 项目源码 | 文件源码
def getDarkMap(img,pitchSize=9):
    darkMap=np.zeros(shape=(img.shape[0],img.shape[1]),dtype=np.uint8)
    #padding,and darkMap has the same shape with the img
   # print ("shape of darkmap",darkMap.shape[0],darkMap.shape[1])
    padSize=(pitchSize-1)//2
    #print ("type of pitchsize",type(padSize))
    pad=cv2.copyMakeBorder(img,padSize,padSize,padSize,padSize,cv2.BORDER_CONSTANT,value=255)
    for i in range(darkMap.shape[0]):
        for j in range(darkMap.shape[1]):
            darkMap[i,j]=pad[i:i+pitchSize,j:j+pitchSize].min()

    return pad,darkMap
项目:deep-prior-pp    作者:moberweger    | 项目源码 | 文件源码
def rotateHand(self, dpt, cube, com, rot, joints3D, pad_value=0):
        """
        Rotate hand virtually in the image plane by a given angle
        :param dpt: cropped depth image with different CoM
        :param cube: metric cube of size (sx,sy,sz)
        :param com: original center of mass, in image coordinates (x,y,z)
        :param rot: rotation angle in deg
        :param joints3D: original joint coordinates, in 3D coordinates (x,y,z)
        :param pad_value: value of padding
        :return: adjusted image, new 3D joint coordinates, rotation angle in XXX
        """

        # if rot is 0, nothing to do
        if numpy.allclose(rot, 0.):
            return dpt, joints3D, rot

        rot = numpy.mod(rot, 360)

        M = cv2.getRotationMatrix2D((dpt.shape[1]//2, dpt.shape[0]//2), -rot, 1)
        new_dpt = cv2.warpAffine(dpt, M, (dpt.shape[1], dpt.shape[0]), flags=cv2.INTER_NEAREST,
                                 borderMode=cv2.BORDER_CONSTANT, borderValue=pad_value)

        com3D = self.importer.jointImgTo3D(com)
        joint_2D = self.importer.joints3DToImg(joints3D + com3D)
        data_2D = numpy.zeros_like(joint_2D)
        for k in xrange(data_2D.shape[0]):
            data_2D[k] = rotatePoint2D(joint_2D[k], com[0:2], rot)
        new_joints3D = (self.importer.jointsImgTo3D(data_2D) - com3D)

        return new_dpt, new_joints3D, rot
项目:eclipse2017    作者:google    | 项目源码 | 文件源码
def pad_height(image):
    height, width, _ = image.shape
    border_x = 0
    border_y = int(round(1080-height)/2.)
    image = cv2.copyMakeBorder(image, border_y, border_y,
                               border_x, border_x,
                               cv2.BORDER_CONSTANT, value=[0,0,0,0])
    return image
项目:eclipse2017    作者:google    | 项目源码 | 文件源码
def pad_width(image):
    height, width, _ = image.shape
    border_x = int(round(1920-width)/2.)
    border_y = 0
    image = cv2.copyMakeBorder(image, border_y, border_y,
                               border_x, border_x,
                               cv2.BORDER_CONSTANT, value=[0,0,0,0])
    return image
项目:opencv-helpers    作者:abarrak    | 项目源码 | 文件源码
def frame(image, top=2, bottom=2, left=2, right=2, borderType=cv.BORDER_CONSTANT, color=[255, 0, 0]):
  '''
  add borders around :image:
  :param image: has to be in RBG color scheme. Use `convert_to_rgb` if it's in opencv BGR scheme.
  :param color: array representing an RGB color.
  :param borderType: Other options are:
                                    cv.BORDER_REFLECT,
                                    cv.BORDER_REFLECT_101,
                                    cv.BORDER_DEFAULT,
                                    cv.BORDER_REPLICATE,
                                    cv.BORDER_WRAP
  '''
  return cv.copyMakeBorder(image, top, bottom, left, right, borderType, value=color)
项目:CVtools    作者:Tyler-D    | 项目源码 | 文件源码
def MotionBlur(img, steps):
    '''
    Parameters:
    -----------
    img: Ndarray. CV loaded image
    steps: tuple(step_x, step_y). Motion Velocity

    Return:
    -------
    img: Ndarray. Blurred image
    '''
    BLACK=[0,0,0]
    img_height, img_width, channel= img.shape
    step_x , step_y = steps

    hori = abs(step_x)
    vert = abs(step_y)
    img_mb = cv.copyMakeBorder(img, vert, vert, hori, hori, cv.BORDER_CONSTANT, value=BLACK)

    img_mask = np.zeros((img_height,img_width, channel))
    if step_x!=0 :
        sign_x = step_x / hori
        for x in xrange(0, hori):
            img_mask += img_mb[vert : vert+img_height, hori-x*sign_x : hori+img_width-x*sign_x]

    if step_y!=0 :
        sign_y = step_y / vert
        for y in xrange(0, vert):
            img_mask += img_mb[vert-y*sign_y : vert+img_height-y*sign_y, hori:hori+img_width]

    img_mask /= (hori+vert)
    return img_mask
项目:dlcv_for_beginners    作者:frombeijingwithlove    | 项目源码 | 文件源码
def _draw_bbox(self, img):

        h, w = img.shape[:2]
        canvas = cv2.copyMakeBorder(img, 0, BAR_HEIGHT, 0, 0, cv2.BORDER_CONSTANT, value=COLOR_GRAY)

        label_msg = '{}: {}, {}'.format(self._cur_label, self._pt0, self._pt1) \
            if self._drawing \
            else 'Current label: {}'.format(self._cur_label)
        msg = '{}/{}: {} | {}'.format(self._index + 1, len(self._filelist), self._filelist[self._index], label_msg)

        cv2.putText(canvas, msg, (1, h+12),
                    cv2.FONT_HERSHEY_SIMPLEX,
                    0.5, (0, 0, 0), 1)
        for label, (bpt0, bpt1) in self._bboxes:
            label_color = self.label_colors[label] if label in self.label_colors else COLOR_GRAY
            cv2.rectangle(canvas, bpt0, bpt1, label_color, thickness=2)
            cv2.putText(canvas, label, (bpt0[0]+3, bpt0[1]+15),
                        cv2.FONT_HERSHEY_SIMPLEX,
                        0.5, label_color, 2)
        if self._drawing:
            label_color = self.label_colors[self._cur_label] if self._cur_label in self.label_colors else COLOR_GRAY
            if self._pt1[0] >= self._pt0[0] and self._pt1[1] >= self._pt0[1]:
                cv2.rectangle(canvas, self._pt0, self._pt1, label_color, thickness=2)
            cv2.putText(canvas, self._cur_label, (self._pt0[0] + 3, self._pt0[1] + 15),
                        cv2.FONT_HERSHEY_SIMPLEX,
                        0.5, label_color, 2)
        return canvas