Python cv2 模块,BORDER_DEFAULT 实例源码

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

项目:guided-filter    作者:lisabug    | 项目源码 | 文件源码
def test_box_filter_reflect_101(self):
        I = np.array(range(1, 50)).reshape(7, 7).astype(np.float32)
        r = 2
        ret1 = cv.smooth.box_filter(I, r, normalize=True)
        ret2 = cv2.blur(I, (5,5), borderType=cv2.BORDER_DEFAULT)
        self.assertTrue(np.array_equal(ret1, ret2))
项目:DmsMsgRcg    作者:bshao001    | 项目源码 | 文件源码
def resize_to_desired(input_img):
    h = input_img.shape[0]
    if h < 20:  # pad the image to 20 or 21 pixels height if it is too short
        border = math.ceil((20 - h) / 2)
        new_img = cv2.copyMakeBorder(input_img, top=border, bottom=border, left=0, right=0,
                                     borderType=cv2.BORDER_DEFAULT)
    else:
        new_img = input_img

    return cv2.resize(new_img, (CLS_IMG_WIDTH, CLS_IMG_HEIGHT))
项目:recognizeFitExercise    作者:tyiannak    | 项目源码 | 文件源码
def getRGBS(img, PLOT = False):

    image = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)

    # grab the image channels, initialize the tuple of colors,
    # the figure and the flattened feature vector   
    features = []
    featuresSobel = []
    Grayscale = cv2.cvtColor(img, cv2.cv.CV_BGR2GRAY)
    histG = cv2.calcHist([Grayscale], [0], None, [16], [0, 256])
    histG = histG / histG.sum()
    features.extend(histG[:,0].tolist())


    grad_x = np.abs(cv2.Sobel(Grayscale, cv2.CV_16S, 1, 0, ksize = 3, scale = 1, delta = 0, borderType = cv2.BORDER_DEFAULT))
    grad_y = np.abs(cv2.Sobel(Grayscale, cv2.CV_16S, 0, 1, ksize = 3, scale = 1, delta = 0, borderType = cv2.BORDER_DEFAULT))
    abs_grad_x = cv2.convertScaleAbs(grad_x)
    abs_grad_y = cv2.convertScaleAbs(grad_y)
    dst = cv2.addWeighted(abs_grad_x,0.5,abs_grad_y,0.5,0)
    histSobel = cv2.calcHist([dst], [0], None, [16], [0, 256])
    histSobel = histSobel / histSobel.sum()
    features.extend(histSobel[:,0].tolist())

    Fnames = []
    Fnames.extend(["Color-Gray"+str(i) for i in range(8)])
    Fnames.extend(["Color-GraySobel"+str(i) for i in range(8)])

    return features, Fnames
项目: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)
项目:Automatic-Plate-Number-Recognition-APNR    作者:kagan94    | 项目源码 | 文件源码
def find_contours(img):
    '''
    :param img: (numpy array)
    :return: all possible rectangles (contours)
    '''
    img_blurred = cv2.GaussianBlur(img, (5, 5), 1)  # remove noise
    img_gray = cv2.cvtColor(img_blurred, cv2.COLOR_BGR2GRAY)  # greyscale image
    # cv2.imshow('', img_gray)
    # cv2.waitKey(0)

    # Apply Sobel filter to find the vertical edges
    # Find vertical lines. Car plates have high density of vertical lines
    img_sobel_x = cv2.Sobel(img_gray, cv2.CV_8UC1, dx=1, dy=0, ksize=3, scale=1, delta=0, borderType=cv2.BORDER_DEFAULT)
    # cv2.imshow('img_sobel', img_sobel_x)

    # Apply optimal threshold by using Oslu algorithm
    retval, img_threshold = cv2.threshold(img_sobel_x, 0, 255, cv2.THRESH_OTSU + cv2.THRESH_BINARY)
    # cv2.imshow('s', img_threshold)
    # cv2.waitKey(0)

    # TODO: Try to apply AdaptiveThresh
    # Size of a pixel neighborhood that is used to calculate a threshold value for the pixel: 3, 5, 7, and so on.
    # gaus_threshold = cv2.adaptiveThreshold(img_gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 115, 1)
    # cv2.imshow('or', img)
    # cv2.imshow('gaus', gaus_threshold)
    # cv2.waitKey(0)

    # Define a stuctural element as rectangular of size 17x3 (we'll use it during the morphological cleaning)
    element = cv2.getStructuringElement(shape=cv2.MORPH_RECT, ksize=(17, 3))

    # And use this structural element in a close morphological operation
    morph_img_threshold = deepcopy(img_threshold)
    cv2.morphologyEx(src=img_threshold, op=cv2.MORPH_CLOSE, kernel=element, dst=morph_img_threshold)
    # cv2.dilate(img_threshold, kernel=np.ones((1,1), np.uint8), dst=img_threshold, iterations=1)
    # cv2.imshow('Normal Threshold', img_threshold)
    # cv2.imshow('Morphological Threshold based on rect. mask', morph_img_threshold)
    # cv2.waitKey(0)

    # Find contours that contain possible plates (in hierarchical relationship)
    contours, hierarchy = cv2.findContours(morph_img_threshold,
                                           mode=cv2.RETR_EXTERNAL,  # retrieve the external contours
                                           method=cv2.CHAIN_APPROX_NONE)  # all pixels of each contour

    plot_intermediate_steps = False
    if plot_intermediate_steps:
        plot(plt, 321, img, "Original image")
        plot(plt, 322, img_blurred, "Blurred image")
        plot(plt, 323, img_gray, "Grayscale image", cmap='gray')
        plot(plt, 324, img_sobel_x, "Sobel")
        plot(plt, 325, img_threshold, "Threshold image")
        # plot(plt, 326, morph_img_threshold, "After Morphological filter")
        plt.tight_layout()
        plt.show()

    return contours
项目:vision-code    作者:FIRST-Team-1699    | 项目源码 | 文件源码
def run(self):
    bytes='' 
    while not self.thread_cancelled:
      try:
        bytes+=self.stream.raw.read(1024) 
        a = bytes.find('\xff\xd8')
        b = bytes.find('\xff\xd9')
        if a!=-1 and b!=-1:
          jpg = bytes[a:b+2]
          bytes= bytes[b+2:]
          img = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8),cv2.IMREAD_COLOR)

          # Convert BGR to HSV
          hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
          # define range of blue color in HSV
          #lower_blue = np.array([self.L_RED, self.L_GREEN, self.L_BLUE], np.uint8)
          #upper_blue = np.array([self.U_RED, self.U_GREEN, self.L_BLUE], np.uint8)

          # Threshold the HSV image to get only blue colors
          mask = cv2.inRange(hsv, np.array([53,187,37]), np.array([97,244,153]))

          # Bitwise-AND mask and original image
          res = cv2.bitwise_and(img,img, mask= mask)
####        blurred = cv2.GaussianBlur(mask, (5, 5), 0)
          blurred = cv2.boxFilter(mask, 0, (7, 7), mask, (-1, -1), False, cv2.BORDER_DEFAULT)
          thresh = cv2.threshold(blurred, 60, 255, cv2.THRESH_BINARY)[1]
          cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
          cnts = cnts[0] if imutils.is_cv2() else cnts[1]
          cv2.filterSpeckles(mask, 0, 100, 25)
##          cv2.filterSpeckles(mask, 0, 50, 25)
##          cv2.filterSpeckles(mask, 0, 100, 100)
          for c in cnts:
              M = cv2.moments(c)
              if int(M["m00"]) != 0:
                  cX = int(M["m10"] / M["m00"])
                  cY = int(M["m01"] / M["m00"])
              else:
                  (cX, cY) = (0, 0)
              print(cX, cY)
              cv2.drawContours(res, [c], -1, (0, 255, 0), 2)
              cv2.circle(res, (cX, cY), 7, (255, 255, 255), 1)

             # table.putNumber("center X", cX)
          cv2.imshow('img',img)
          cv2.imshow('mask',mask)
          cv2.imshow('Final',res)
          cv2.imshow('cam',img)
          #sd.putNumber('Center X', cX) ##send the x value of the center
          #sd.putNumber('Center Y', cY) ##send the y value of the center
##          print(sd.getNumber('Center Y'), sd.getNumber('Center X'))
          if cv2.waitKey(1) ==27:
            exit(0)
      except ThreadError:
        self.thread_cancelled = True
项目:vision-code    作者:FIRST-Team-1699    | 项目源码 | 文件源码
def run(self):
    bytes='' 
    while not self.thread_cancelled:  ####see lines 18, 80, 88 ....
      try:        
        bytes+=self.stream.raw.read(1024) ##limit max bytes read in 1 itteration? need to read more on this
        a = bytes.find('\xff\xd8')##find start of stream of data  
        b = bytes.find('\xff\xd9')##find our end of data stream
        if a!=-1 and b!=-1:  ##so as long as we have a stream of data....do the following
          jpg = bytes[a:b+2]  ##converts to image or a specific variable...
          bytes= bytes[b+2:]  
          img = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8),cv2.IMREAD_COLOR)  ##decode the data

          # Convert BGR to HSV
          hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)  ##converting color format for easier proccessing/ math
          # define range of blue color in HSV
          #lower_blue = np.array([self.L_RED, self.L_GREEN, self.L_BLUE], np.uint8)
          #upper_blue = np.array([self.U_RED, self.U_GREEN, self.L_BLUE], np.uint8)

          # Threshold the HSV image to get only blue colors
          mask = cv2.inRange(hsv, np.array([53,187,37]), np.array([97,244,153]))  ##get colors in the range of these HSV values

          # Bitwise-AND mask and original image
          res = cv2.bitwise_and(img,img, mask= mask)

          blurred = cv2.boxFilter(mask, 0, (7, 7), mask, (-1, -1), False, cv2.BORDER_DEFAULT) ##the next few line create outlines and 
          thresh = cv2.threshold(blurred, 60, 255, cv2.THRESH_BINARY)[1]                      ##remove any noise
          cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)  #find countors
          cnts = cnts[0] if imutils.is_cv2() else cnts[1]   
          cv2.filterSpeckles(mask, 0, 100, 25)      ##remove speckles aka random dots and white noise
          for c in cnts:
              M = cv2.moments(c)
              if int(M["m00"]) != 0:  ##Checks for division by zero
                  cX = int(M["m10"] / M["m00"])
                  cY = int(M["m01"] / M["m00"])
              else:
                  (cX, cY) = (0, 0)
              cv2.drawContours(res, [c], -1, (0, 255, 0), 2)  ##draw box/highlighting 
              cv2.circle(res, (cX, cY), 7, (255, 255, 255), 1)  ##draw box/highlighting 

              ##Try-Catch for appending cX to table
              try:
                self.table.putNumber('centerX', cX)  ##Adds cX to the networktables
              except KeyError:
                print("centerX failed.")

          cv2.imshow('img',img)   ##display original image
          cv2.imshow('mask',mask)  ##display masked image
          cv2.imshow('Final',res)  ##show final image


          cv2.imshow('cam',img)  ##see line 71/comments
          if cv2.waitKey(1) ==27:  ##now we close if esc key is pressed
            exit(0)
      except ThreadError:
        self.thread_cancelled = True