本文整理匯總了Python中cv2.arcLength方法的典型用法代碼示例。如果您正苦於以下問題:Python cv2.arcLength方法的具體用法?Python cv2.arcLength怎麽用?Python cv2.arcLength使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類cv2
的用法示例。
在下文中一共展示了cv2.arcLength方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: FindHullDefects
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import arcLength [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]
示例2: find_squares
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import arcLength [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
示例3: find_boxes
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import arcLength [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
示例4: mask_to_bbox
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import arcLength [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
示例5: _get_annotation
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import arcLength [as 別名]
def _get_annotation(self, label_path: str) -> tuple:
boxes = []
text_tags = []
with open(label_path, encoding='utf-8', mode='r') as f:
for line in f.readlines():
params = line.strip().strip('\ufeff').strip('\xef\xbb\xbf').split(',')
try:
box = order_points_clockwise(np.array(list(map(float, params[:8]))).reshape(-1, 2))
if cv2.arcLength(box, True) > 0:
boxes.append(box)
label = params[8]
if label == '*' or label == '###':
text_tags.append(False)
else:
text_tags.append(True)
except:
print('load label failed on {}'.format(label_path))
return np.array(boxes, dtype=np.float32), np.array(text_tags, dtype=np.bool)
示例6: __init__
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import arcLength [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
示例7: _find_document_corners
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import arcLength [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
示例8: get_border_point
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import arcLength [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
示例9: find_display_contour
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import arcLength [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
示例10: simplify
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import arcLength [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)
示例11: detect_edge
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import arcLength [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
示例12: approximate_contours
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import arcLength [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
示例13: get_output_image
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import arcLength [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
示例14: boundingRects
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import arcLength [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]
示例15: findEllipses
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import arcLength [as 別名]
def findEllipses(edges):
contours, _ = cv2.findContours(edges.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
ellipseMask = np.zeros(edges.shape, dtype=np.uint8)
contourMask = np.zeros(edges.shape, dtype=np.uint8)
pi_4 = np.pi * 4
for i, contour in enumerate(contours):
if len(contour) < 5:
continue
area = cv2.contourArea(contour)
if area <= 100: # skip ellipses smaller then 10x10
continue
arclen = cv2.arcLength(contour, True)
circularity = (pi_4 * area) / (arclen * arclen)
ellipse = cv2.fitEllipse(contour)
poly = cv2.ellipse2Poly((int(ellipse[0][0]), int(ellipse[0][1])), (int(ellipse[1][0] / 2), int(ellipse[1][1] / 2)), int(ellipse[2]), 0, 360, 5)
# if contour is circular enough
if circularity > 0.6:
cv2.fillPoly(ellipseMask, [poly], 255)
continue
# if contour has enough similarity to an ellipse
similarity = cv2.matchShapes(poly.reshape((poly.shape[0], 1, poly.shape[1])), contour, cv2.cv.CV_CONTOURS_MATCH_I2, 0)
if similarity <= 0.2:
cv2.fillPoly(contourMask, [poly], 255)
return ellipseMask, contourMask