当前位置: 首页>>代码示例>>Python>>正文


Python cv2.approxPolyDP方法代码示例

本文整理汇总了Python中cv2.approxPolyDP方法的典型用法代码示例。如果您正苦于以下问题:Python cv2.approxPolyDP方法的具体用法?Python cv2.approxPolyDP怎么用?Python cv2.approxPolyDP使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在cv2的用法示例。


在下文中一共展示了cv2.approxPolyDP方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: FindHullDefects

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import approxPolyDP [as 别名]
def FindHullDefects(self, segment):
        _,contours,hierarchy = cv2.findContours(segment, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

        # find largest area contour
        max_area = -1
        for i in range(len(contours)):
            area = cv2.contourArea(contours[i])
            if area>max_area:
                cnt = contours[i]
                max_area = area

        cnt = cv2.approxPolyDP(cnt,0.01*cv2.arcLength(cnt,True),True)
        hull = cv2.convexHull(cnt, returnPoints=False)
        defects = cv2.convexityDefects(cnt, hull)

        return [cnt,defects] 
开发者ID:PacktPublishing,项目名称:OpenCV-Computer-Vision-Projects-with-Python,代码行数:18,代码来源:chapter2.py

示例2: find_squares

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import approxPolyDP [as 别名]
def find_squares(img):
    img = cv2.GaussianBlur(img, (5, 5), 0)
    squares = []
    for gray in cv2.split(img):
        for thrs in xrange(0, 255, 26):
            if thrs == 0:
                bin = cv2.Canny(gray, 0, 50, apertureSize=5)
                bin = cv2.dilate(bin, None)
            else:
                retval, bin = cv2.threshold(gray, thrs, 255, cv2.THRESH_BINARY)
            bin, contours, hierarchy = cv2.findContours(bin, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
            for cnt in contours:
                cnt_len = cv2.arcLength(cnt, True)
                cnt = cv2.approxPolyDP(cnt, 0.02*cnt_len, True)
                if len(cnt) == 4 and cv2.contourArea(cnt) > 1000 and cv2.isContourConvex(cnt):
                    cnt = cnt.reshape(-1, 2)
                    max_cos = np.max([angle_cos( cnt[i], cnt[(i+1) % 4], cnt[(i+2) % 4] ) for i in xrange(4)])
                    if max_cos < 0.1:
                        squares.append(cnt)
    return squares 
开发者ID:makelove,项目名称:OpenCV-Python-Tutorial,代码行数:22,代码来源:squares.py

示例3: mask_to_bbox

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import approxPolyDP [as 别名]
def mask_to_bbox(mask, image, num_class, area_threhold=0, out_path=None, out_file_name=None):
  bbox_list = []
  im = copy.copy(image)
  mask = mask.astype(np.uint8)
  for i in range(1, num_class, 1):
    c_bbox_list = []
    c_mask = np.zeros_like(mask)
    c_mask[np.where(mask==i)] = 255
    bimg , countours, hier = cv2.findContours(c_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    for cnt in countours:
      area = cv2.contourArea(cnt)
      if area < area_threhold:
        continue
      epsilon = 0.005 * cv2.arcLength(cnt,True)
      approx = cv2.approxPolyDP(cnt,epsilon,True)
      (x, y, w, h) = cv2.boundingRect(approx)
      c_bbox_list.append([x,  y, x+w, y+h])
      if out_path is not None:
        color = COLOR_LIST[i-1]
        im=cv2.rectangle(im, pt1=(x, y), pt2=(x+w, y+h),color=color, thickness=2)
    bbox_list.append(c_bbox_list)
  if out_path is not None:
    outf = os.path.join(out_path, out_file_name)
    cv2.imwrite(outf, im)
  return bbox_list 
开发者ID:rockyzhengwu,项目名称:document-ocr,代码行数:27,代码来源:load_saved_model.py

示例4: find_boxes

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import approxPolyDP [as 别名]
def find_boxes(tiff_fl, blur=False):
    im = Image.open(tiff_fl).convert('L')
    a = np.asarray(im)
    if blur:
        a = cv.GaussianBlur(a, (5, 5), 0)
    contours, hierarchy = cv.findContours(a.copy(), mode=cv.RETR_TREE, method=cv.CHAIN_APPROX_SIMPLE)
    border_boxes = []
#     n = np.ones_like(a)
    for j,cnt in enumerate(contours):
        cnt_len = cv.arcLength(cnt, True)
        orig_cnt = cnt.copy()
        cnt = cv.approxPolyDP(cnt, 0.02*cnt_len, True)
        if len(cnt) == 4 and ((a.shape[0]-3) * (a.shape[1] -3)) > cv.contourArea(cnt) > 1000 and cv.isContourConvex(cnt):
            cnt = cnt.reshape(-1, 2)
            max_cos = np.max([angle_cos( cnt[i], cnt[(i+1) % 4], cnt[(i+2) % 4] ) for i in xrange(4)])
            if max_cos < 0.1:
                b = cv.boundingRect(orig_cnt)
                x,y,w,h = b
                border_boxes.append(b)
#                 cv.rectangle(n, (x,y), (x+w, y+h), 0)
#                 cv.drawContours(n, [cnt], -1,0, thickness = 5)
#     Image.fromarray(n*255).show()
    return border_boxes 
开发者ID:zmr,项目名称:namsel,代码行数:25,代码来源:detect_tables.py

示例5: __init__

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import approxPolyDP [as 别名]
def __init__(self, rubiks_parent, index, contour, heirarchy, debug):
        self.rubiks_parent = rubiks_parent
        self.index = index
        self.contour = contour
        self.heirarchy = heirarchy
        peri = cv2.arcLength(contour, True)
        self.approx = cv2.approxPolyDP(contour, 0.1 * peri, True)
        self.area = cv2.contourArea(contour)
        self.corners = len(self.approx)
        self.width = None
        self.debug = debug

        # compute the center of the contour
        M = cv2.moments(contour)

        if M["m00"]:
            self.cX = int(M["m10"] / M["m00"])
            self.cY = int(M["m01"] / M["m00"])

            # if self.cX == 188 and self.cY == 93:
            #    log.warning("CustomContour M %s" % pformat(M))
        else:
            self.cX = None
            self.cY = None 
开发者ID:dwalton76,项目名称:rubiks-cube-tracker,代码行数:26,代码来源:__init__.py

示例6: _find_document_corners

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import approxPolyDP [as 别名]
def _find_document_corners(resized_img):
    contours = _compute_all_contours(resized_img)
    resized_height, resized_width = _get_img_dimensions(resized_img)
    full_resized_image_area = resized_height * resized_width

    # Default to the smallest possible document area and save any larger document areas
    largest_document_area = full_resized_image_area * ALIGNMENT_PERCENT_AREA_DOCUMENT_MUST_COVER

    # Default to largest: no modification to the image if no document is found
    largest_document_corners = _get_corner_array(resized_height, resized_width)

    for contour in contours:
        contour_perimeter = cv2.arcLength(contour, True)
        approximate_polygonal_contour = cv2.approxPolyDP(contour, 0.03 * contour_perimeter, True)

        # All pages have 4 corners and are convex
        if (len(approximate_polygonal_contour) == 4 and
                cv2.isContourConvex(approximate_polygonal_contour) and
                cv2.contourArea(approximate_polygonal_contour) > largest_document_area):
            largest_document_area = cv2.contourArea(approximate_polygonal_contour)
            largest_document_corners = approximate_polygonal_contour

    return largest_document_corners 
开发者ID:Cyberjusticelab,项目名称:JusticeAI,代码行数:25,代码来源:ocr_controller.py

示例7: approximate_contours

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import approxPolyDP [as 别名]
def approximate_contours(contours):
    print 'approximate_contours'
    result = []
    for x in contours:
        epsilon = 0.005 * cv2.arcLength(x, True)
        approx = cv2.approxPolyDP(x, epsilon, True)
        result.append(approx)
    return result 
开发者ID:fogleman,项目名称:xy,代码行数:10,代码来源:buildings.py

示例8: get_border_point

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import approxPolyDP [as 别名]
def get_border_point(points, rect, max_height, max_width):
    """Get border points of a fill area

    # Arguments
        points: points of fill .
        rect: bounding rect of fill.
        max_height: image max height.
        max_width: image max width.
    # Returns
        points , convex shape of points
    """
    # Get a local bounding rect.
    border_rect = get_border_bounding_rect(max_height, max_width, rect[:2], rect[2:], 2)

    # Get fill in rect.
    fill = np.zeros((border_rect[3] - border_rect[1], border_rect[2] - border_rect[0]), np.uint8)
    # Move points to the rect.
    fill[(points[0] - border_rect[1], points[1] - border_rect[0])] = 255

    # Get shape.
    _, contours, _ = cv2.findContours(fill, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    approx_shape = cv2.approxPolyDP(contours[0], 0.02 * cv2.arcLength(contours[0], True), True)

    # Get border pixel.
    # Structuring element in cross shape is used instead of box to get 4-connected border.
    cross = cv2.getStructuringElement(cv2.MORPH_CROSS, (3, 3))
    border_pixel_mask = cv2.morphologyEx(fill, cv2.MORPH_DILATE, cross, anchor=(-1, -1), iterations=1) - fill
    border_pixel_points = np.where(border_pixel_mask == 255)

    # Transform points back to fillmap.
    border_pixel_points = (border_pixel_points[0] + border_rect[1], border_pixel_points[1] + border_rect[0])

    return border_pixel_points, approx_shape 
开发者ID:hepesu,项目名称:LineFiller,代码行数:35,代码来源:trappedball_fill.py

示例9: find_display_contour

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import approxPolyDP [as 别名]
def find_display_contour(edge_img_arr):
  display_contour = None
  edge_copy = edge_img_arr.copy()
  contours,hierarchy = cv2.findContours(edge_copy, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
  top_cntrs = sorted(contours, key = cv2.contourArea, reverse = True)[:10]

  for cntr in top_cntrs:
    peri = cv2.arcLength(cntr,True)
    approx = cv2.approxPolyDP(cntr, 0.02 * peri, True)

    if len(approx) == 4:
      display_contour = approx
      break

  return display_contour 
开发者ID:arturaugusto,项目名称:display_ocr,代码行数:17,代码来源:digital_display_ocr.py

示例10: simplify

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import approxPolyDP [as 别名]
def simplify(polygon, eps):
    """Simplifies a polygon to minimize the polygon's vertices.

    Args:
      polygon: the polygon made up of a list of vertices.
      eps: the approximation accuracy as max. percentage of the arc length, in [0, 1]

    """

    assert 0 <= eps <= 1, "approximation accuracy is percentage in [0, 1]"

    epsilon = eps * cv2.arcLength(polygon, closed=True)
    return cv2.approxPolyDP(polygon, epsilon=epsilon, closed=True) 
开发者ID:mapbox,项目名称:robosat,代码行数:15,代码来源:core.py

示例11: detect_edge

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import approxPolyDP [as 别名]
def detect_edge(self, image, enabled_transform = False):
        dst = None
        orig = image.copy()

        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        blurred = cv2.GaussianBlur(gray, (5, 5), 0)
        edged = cv2.Canny(blurred, 0, 20)
        _, contours, _ = cv2.findContours(edged, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)

        contours = sorted(contours, key=cv2.contourArea, reverse=True)

        for cnt in contours:
            epsilon = 0.051 * cv2.arcLength(cnt, True)
            approx = cv2.approxPolyDP(cnt, epsilon, True)

            if len(approx) == 4:
                target = approx
                cv2.drawContours(image, [target], -1, (0, 255, 0), 2)

                if enabled_transform:
                    approx = rect.rectify(target)
                    # pts2 = np.float32([[0,0],[800,0],[800,800],[0,800]])
                    # M = cv2.getPerspectiveTransform(approx,pts2)
                    # dst = cv2.warpPerspective(orig,M,(800,800))
                    dst = self.four_point_transform(orig, approx)
                break

        return image, dst 
开发者ID:yushulx,项目名称:web-document-scanner,代码行数:30,代码来源:document.py

示例12: draw_contour

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import approxPolyDP [as 别名]
def draw_contour(img, mask):
    a, b, c = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
    for cnt in b:
        approx = cv2.approxPolyDP(cnt, 0, True)
        cv2.drawContours(img, [approx], 0, (255, 255, 255), -1)
    return img 
开发者ID:yu45020,项目名称:Text_Segmentation_Image_Inpainting,代码行数:8,代码来源:Dataloader.py

示例13: get_output_image

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import approxPolyDP [as 别名]
def get_output_image(path):
  
    img = cv2.imread(path,2)
    img_org =  cv2.imread(path)

    ret,thresh = cv2.threshold(img,127,255,0)
    im2,contours,hierarchy = cv2.findContours(thresh, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)

    for j,cnt in enumerate(contours):
        epsilon = 0.01*cv2.arcLength(cnt,True)
        approx = cv2.approxPolyDP(cnt,epsilon,True)
        
        hull = cv2.convexHull(cnt)
        k = cv2.isContourConvex(cnt)
        x,y,w,h = cv2.boundingRect(cnt)
        
        if(hierarchy[0][j][3]!=-1 and w>10 and h>10):
            #putting boundary on each digit
            cv2.rectangle(img_org,(x,y),(x+w,y+h),(0,255,0),2)
            
            #cropping each image and process
            roi = img[y:y+h, x:x+w]
            roi = cv2.bitwise_not(roi)
            roi = image_refiner(roi)
            th,fnl = cv2.threshold(roi,127,255,cv2.THRESH_BINARY)

            # getting prediction of cropped image
            pred = predict_digit(roi)
            print(pred)
            
            # placing label on each digit
            (x,y),radius = cv2.minEnclosingCircle(cnt)
            img_org = put_label(img_org,pred,x,y)

    return img_org 
开发者ID:surya-veer,项目名称:RealTime-DigitRecognition,代码行数:37,代码来源:process_image.py

示例14: boundingRects

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import approxPolyDP [as 别名]
def boundingRects(scale, contours):
    for contour in contours:
        epsilon = 0.1 * cv2.arcLength(contour, True)
        approx = cv2.approxPolyDP(contour, epsilon, True)
        x, y, w, h = cv2.boundingRect(approx)

        yield [x * scale, y * scale, w * scale, h * scale] 
开发者ID:AVGInnovationLabs,项目名称:DoNotSnap,代码行数:9,代码来源:RegionOfInterest.py

示例15: main

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import approxPolyDP [as 别名]
def main():
    model = create_model()
    model.load_weights(WEIGHTS_FILE)

    for filename in glob.glob(IMAGES):
        unscaled = cv2.imread(filename)
        image = cv2.resize(unscaled, (IMAGE_SIZE, IMAGE_SIZE))
        feat_scaled = preprocess_input(np.array(image, dtype=np.float32))

        region = np.squeeze(model.predict(feat_scaled[np.newaxis,:]))

        output = np.zeros(region.shape, dtype=np.uint8)
        output[region > 0.5] = 1

        contours, _ = cv2.findContours(output, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
        for cnt in contours:
            approx = cv2.approxPolyDP(cnt, EPSILON * cv2.arcLength(cnt, True), True)
            x, y, w, h = cv2.boundingRect(approx)

            x0 = np.rint(x * unscaled.shape[1] / output.shape[1]).astype(int)
            x1 = np.rint((x + w) * unscaled.shape[1] / output.shape[1]).astype(int)
            y0 = np.rint(y * unscaled.shape[0] / output.shape[0]).astype(int)
            y1 = np.rint((y + h) * unscaled.shape[0] / output.shape[0]).astype(int)
            cv2.rectangle(unscaled, (x0, y0), (x1, y1), (0, 255, 0), 1)

        cv2.imshow("image", unscaled)
        cv2.waitKey(0)
        cv2.destroyAllWindows() 
开发者ID:lars76,项目名称:object-localization,代码行数:30,代码来源:test.py


注:本文中的cv2.approxPolyDP方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。