本文整理匯總了Python中cv2.contourArea方法的典型用法代碼示例。如果您正苦於以下問題:Python cv2.contourArea方法的具體用法?Python cv2.contourArea怎麽用?Python cv2.contourArea使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類cv2
的用法示例。
在下文中一共展示了cv2.contourArea方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: FindHullDefects
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import contourArea [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: segment
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import contourArea [as 別名]
def segment(image, threshold=25):
global bg
# find the absolute difference between background and current frame
diff = cv2.absdiff(bg.astype("uint8"), image)
# threshold the diff image so that we get the foreground
thresholded = cv2.threshold(diff, threshold, 255, cv2.THRESH_BINARY)[1]
# get the contours in the thresholded image
(_, cnts, _) = cv2.findContours(thresholded.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# return None, if no contours detected
if len(cnts) == 0:
return
else:
# based on contour area, get the maximum contour which is the hand
segmented = max(cnts, key=cv2.contourArea)
return (thresholded, segmented)
#-----------------
# MAIN FUNCTION
#-----------------
示例3: _find_size_candidates
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import contourArea [as 別名]
def _find_size_candidates(self, image):
binary_image = self._filter_image(image)
_, contours, _ = cv2.findContours(binary_image,
cv2.RETR_LIST,
cv2.CHAIN_APPROX_SIMPLE)
size_candidates = []
for contour in contours:
bounding_rect = cv2.boundingRect(contour)
contour_area = cv2.contourArea(contour)
if self._is_valid_contour(contour_area, bounding_rect):
candidate = (bounding_rect[2] + bounding_rect[3]) / 2
size_candidates.append(candidate)
return size_candidates
示例4: contour_filter
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import contourArea [as 別名]
def contour_filter(self, frame):
_, contours, _ = cv2.findContours(frame,
cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
new_frame = np.zeros(frame.shape, np.uint8)
for i, contour in enumerate(contours):
c_area = cv2.contourArea(contour)
if self.contour_min_area <= c_area <= self.contour_max_area:
mask = np.zeros(frame.shape, np.uint8)
cv2.drawContours(mask, contours, i, 255, cv2.FILLED)
mask = cv2.bitwise_and(frame, mask)
new_frame = cv2.bitwise_or(new_frame, mask)
frame = new_frame
if self.contour_disp_flag:
frame = cv2.cvtColor(frame, cv2.COLOR_GRAY2BGR)
cv2.drawContours(frame, contours, -1, (255, 0, 0), 1)
return frame
# A number of methods corresponding to the various trackbars available.
示例5: _append_boxes_from_saliency
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import contourArea [as 別名]
def _append_boxes_from_saliency(self, proto_objects_map, box_all):
"""Adds to the list all bounding boxes found with the saliency map
A saliency map is used to find objects worth tracking in each
frame. This information is combined with a mean-shift tracker
to find objects of relevance that move, and to discard everything
else.
:param proto_objects_map: proto-objects map of the current frame
:param box_all: append bounding boxes from saliency to this list
:returns: new list of all collected bounding boxes
"""
# find all bounding boxes in new saliency map
box_sal = []
cnt_sal, _ = cv2.findContours(proto_objects_map, 1, 2)
for cnt in cnt_sal:
# discard small contours
if cv2.contourArea(cnt) < self.min_cnt_area:
continue
# otherwise add to list of boxes found from saliency map
box = cv2.boundingRect(cnt)
box_all.append(box)
return box_all
示例6: find_squares
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import contourArea [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
示例7: find_corners_of_largest_polygon
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import contourArea [as 別名]
def find_corners_of_largest_polygon(img):
"""Finds the 4 extreme corners of the largest contour in the image."""
opencv_version = cv2.__version__.split('.')[0]
if opencv_version == '3':
_, contours, h = cv2.findContours(img.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # Find contours
else:
contours, h = cv2.findContours(img.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # Find contours
contours = sorted(contours, key=cv2.contourArea, reverse=True) # Sort by area, descending
polygon = contours[0] # Largest image
# Use of `operator.itemgetter` with `max` and `min` allows us to get the index of the point
# Each point is an array of 1 coordinate, hence the [0] getter, then [0] or [1] used to get x and y respectively.
# Bottom-right point has the largest (x + y) value
# Top-left has point smallest (x + y) value
# Bottom-left point has smallest (x - y) value
# Top-right point has largest (x - y) value
bottom_right, _ = max(enumerate([pt[0][0] + pt[0][1] for pt in polygon]), key=operator.itemgetter(1))
top_left, _ = min(enumerate([pt[0][0] + pt[0][1] for pt in polygon]), key=operator.itemgetter(1))
bottom_left, _ = min(enumerate([pt[0][0] - pt[0][1] for pt in polygon]), key=operator.itemgetter(1))
top_right, _ = max(enumerate([pt[0][0] - pt[0][1] for pt in polygon]), key=operator.itemgetter(1))
# Return an array of all 4 points using the indices
# Each point is in its own array of one coordinate
return [polygon[top_left][0], polygon[top_right][0], polygon[bottom_right][0], polygon[bottom_left][0]]
示例8: filter_prediction
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import contourArea [as 別名]
def filter_prediction(self, output, image):
if len(output) < 2:
return pd.DataFrame()
else:
df = pd.DataFrame(output)
df = df.assign(
area=lambda x: df[0].apply(lambda x: cv2.contourArea(x)),
bounding=lambda x: df[0].apply(lambda x: cv2.boundingRect(x))
)
df = df[df['area'] > MIN_AREA]
df_filtered = pd.DataFrame(
df['bounding'].values.tolist(), columns=['x1', 'y1', 'w', 'h'])
df_filtered = df_filtered.assign(
x1=lambda x: x['x1'].clip(0),
y1=lambda x: x['y1'].clip(0),
x2=lambda x: (x['x1'] + x['w']),
y2=lambda x: (x['y1'] + x['h']),
label=lambda x: x.index.astype(str),
class_name=lambda x: x.index.astype(str),
)
return df_filtered
示例9: hand_contour_find
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import contourArea [as 別名]
def hand_contour_find(contours):
max_area=0
largest_contour=-1
for i in range(len(contours)):
cont=contours[i]
area=cv2.contourArea(cont)
if(area>max_area):
max_area=area
largest_contour=i
if(largest_contour==-1):
return False,0
else:
h_contour=contours[largest_contour]
return True,h_contour
# 4. Detect & mark fingers
示例10: iou_rotate_calculate2
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import contourArea [as 別名]
def iou_rotate_calculate2(boxes1, boxes2):
ious = []
if boxes1.shape[0] != 0:
area1 = boxes1[:, 2] * boxes1[:, 3]
area2 = boxes2[:, 2] * boxes2[:, 3]
for i in range(boxes1.shape[0]):
temp_ious = []
r1 = ((boxes1[i][0], boxes1[i][1]), (boxes1[i][2], boxes1[i][3]), boxes1[i][4])
r2 = ((boxes2[i][0], boxes2[i][1]), (boxes2[i][2], boxes2[i][3]), boxes2[i][4])
int_pts = cv2.rotatedRectangleIntersection(r1, r2)[1]
if int_pts is not None:
order_pts = cv2.convexHull(int_pts, returnPoints=True)
int_area = cv2.contourArea(order_pts)
inter = int_area * 1.0 / (area1[i] + area2[i] - int_area)
temp_ious.append(inter)
else:
temp_ious.append(0.0)
ious.append(temp_ious)
return np.array(ious, dtype=np.float32)
示例11: remove_small_boxes
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import contourArea [as 別名]
def remove_small_boxes(contours, min_area, max_area=None):
"""
input - contour, min_area, max_are
return - thresholded contour
"""
contours = get_rotated_bbox(contours)
return_contours = []
for i in range(len(contours)):
area = cv2.contourArea(contours[i])
if area > min_area:
if max_area!=None:
if area < max_area:
return_contours.append(contours[i])
else:
return_contours.append(contours[i])
return return_contours
#Removes contours whose area is smaller than specified value or larger than max_area(if specified), and returns the remaining contours
示例12: __init__
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import contourArea [as 別名]
def __init__(self, points, orient, text):
self.orient = orient
self.text = text
remove_points = []
if len(points) > 4:
# remove point if area is almost unchanged after removing it
ori_area = cv2.contourArea(points)
for p in range(len(points)):
# attempt to remove p
index = list(range(len(points)))
index.remove(p)
area = cv2.contourArea(points[index])
if np.abs(ori_area - area) / ori_area < 0.017 and len(points) - len(remove_points) > 4:
remove_points.append(p)
self.points = np.array([point for i, point in enumerate(points) if i not in remove_points])
else:
self.points = np.array(points)
示例13: segment
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import contourArea [as 別名]
def segment(image, threshold=25):
global bg
# find the absolute difference between background and current frame
diff = cv2.absdiff(bg.astype("uint8"), image)
# threshold the diff image so that we get the foreground
thresholded = cv2.threshold(diff, threshold, 255, cv2.THRESH_BINARY)[1]
# get the contours in the thresholded image
(_, cnts, _) = cv2.findContours(thresholded.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# return None, if no contours detected
if len(cnts) == 0:
return
else:
# based on contour area, get the maximum contour which is the hand
segmented = max(cnts, key=cv2.contourArea)
return (thresholded, segmented)
#--------------------------------------------------------------
# To count the number of fingers in the segmented hand region
#--------------------------------------------------------------
示例14: get_single_centerpoint
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import contourArea [as 別名]
def get_single_centerpoint(self, mask):
contour, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
contour.sort(key=lambda x: cv2.contourArea(x), reverse=True) #only save the biggest one
'''debug IndexError: list index out of range'''
count = contour[0][:, 0, :]
try:
center = self.get_centerpoint(count)
except:
x,y = count.mean(axis=0)
center=[int(x), int(y)]
# max_points = 360
# if len(contour[0]) > max_points:
# compress_rate = len(contour[0]) // max_points
# contour[0] = contour[0][::compress_rate, ...]
return center, contour
示例15: get_single_centerpoint
# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import contourArea [as 別名]
def get_single_centerpoint(self, mask):
contour, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
contour.sort(key=lambda x: cv2.contourArea(x), reverse=True) # only save the biggest one
'''debug IndexError: list index out of range'''
count = contour[0][:, 0, :]
try:
center = self.get_centerpoint(count)
except:
x,y = count.mean(axis=0)
center=[int(x), int(y)]
#decrease the number of contour, to speed up
# 360 points should ok, the performance drop very tiny.
max_points = 360
if len(contour[0]) > max_points:
compress_rate = len(contour[0]) // max_points
contour[0] = contour[0][::compress_rate, ...]
return center, contour