本文整理汇总了Python中cv2.CHAIN_APPROX_SIMPLE属性的典型用法代码示例。如果您正苦于以下问题:Python cv2.CHAIN_APPROX_SIMPLE属性的具体用法?Python cv2.CHAIN_APPROX_SIMPLE怎么用?Python cv2.CHAIN_APPROX_SIMPLE使用的例子?那么, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在类cv2
的用法示例。
在下文中一共展示了cv2.CHAIN_APPROX_SIMPLE属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: FindHullDefects
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import CHAIN_APPROX_SIMPLE [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_size_candidates
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import CHAIN_APPROX_SIMPLE [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
示例3: segment
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import CHAIN_APPROX_SIMPLE [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
#-----------------
示例4: contour_filter
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import CHAIN_APPROX_SIMPLE [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: __get_annotation__
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import CHAIN_APPROX_SIMPLE [as 别名]
def __get_annotation__(self, mask, image=None):
_, contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
segmentation = []
for contour in contours:
# Valid polygons have >= 6 coordinates (3 points)
if contour.size >= 6:
segmentation.append(contour.flatten().tolist())
RLEs = cocomask.frPyObjects(segmentation, mask.shape[0], mask.shape[1])
RLE = cocomask.merge(RLEs)
# RLE = cocomask.encode(np.asfortranarray(mask))
area = cocomask.area(RLE)
[x, y, w, h] = cv2.boundingRect(mask)
if image is not None:
image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
cv2.drawContours(image, contours, -1, (0,255,0), 1)
cv2.rectangle(image,(x,y),(x+w,y+h), (255,0,0), 2)
cv2.imshow("", image)
cv2.waitKey(1)
return segmentation, [x, y, w, h], area
示例6: prediction
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import CHAIN_APPROX_SIMPLE [as 别名]
def prediction(self, image):
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
image = cv2.GaussianBlur(image, (21, 21), 0)
if self.avg is None:
self.avg = image.copy().astype(float)
cv2.accumulateWeighted(image, self.avg, 0.5)
frameDelta = cv2.absdiff(image, cv2.convertScaleAbs(self.avg))
thresh = cv2.threshold(
frameDelta, DELTA_THRESH, 255,
cv2.THRESH_BINARY)[1]
thresh = cv2.dilate(thresh, None, iterations=2)
cnts = cv2.findContours(
thresh.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
self.avg = image.copy().astype(float)
return cnts
示例7: contours
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import CHAIN_APPROX_SIMPLE [as 别名]
def contours(mask):
"""Extracts contours and the relationship between them from a binary mask.
Args:
mask: the binary mask to find contours in.
Returns:
The detected contours as a list of points and the contour hierarchy.
Note: the hierarchy can be used to re-construct polygons with holes as one entity.
"""
contours, hierarchy = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
return contours, hierarchy
# Todo: should work for lines, too, but then needs other epsilon criterion than arc length
示例8: overlay_masks
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import CHAIN_APPROX_SIMPLE [as 别名]
def overlay_masks(im, masks, alpha=0.5):
colors = np.load(os.path.join(os.path.dirname(__file__), 'pascal_map.npy'))/255.
if isinstance(masks, np.ndarray):
masks = [masks]
assert len(colors) >= len(masks), 'Not enough colors'
ov = im.copy()
im = im.astype(np.float32)
total_ma = np.zeros([im.shape[0], im.shape[1]])
i = 1
for ma in masks:
ma = ma.astype(np.bool)
fg = im * alpha+np.ones(im.shape) * (1 - alpha) * colors[i, :3] # np.array([0,0,255])/255.0
i = i + 1
ov[ma == 1] = fg[ma == 1]
total_ma += ma
# [-2:] is s trick to be compatible both with opencv 2 and 3
contours = cv2.findContours(ma.copy().astype(np.uint8), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[-2:]
cv2.drawContours(ov, contours[0], -1, (0.0, 0.0, 0.0), 1)
ov[total_ma == 0] = im[total_ma == 0]
return ov
示例9: find_squares
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import CHAIN_APPROX_SIMPLE [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
示例10: find_corners_of_largest_polygon
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import CHAIN_APPROX_SIMPLE [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]]
示例11: overlay_mask
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import CHAIN_APPROX_SIMPLE [as 别名]
def overlay_mask(self, image, predictions):
"""
Adds the instances contours for each predicted object.
Each label has a different color.
Arguments:
image (np.ndarray): an image as returned by OpenCV
predictions (BoxList): the result of the computation by the model.
It should contain the field `mask` and `labels`.
"""
masks = predictions.get_field("mask").numpy()
labels = predictions.get_field("labels")
colors = self.compute_colors_for_labels(labels).tolist()
for mask, color in zip(masks, colors):
thresh = mask[0, :, :, None]
contours, hierarchy = cv2_util.findContours(
thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE
)
image = cv2.drawContours(image, contours, -1, color, 3)
composite = image
return composite
示例12: findPossibleCharsInPlate
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import CHAIN_APPROX_SIMPLE [as 别名]
def findPossibleCharsInPlate(imgGrayscale, imgThresh):
listOfPossibleChars = [] # this will be the return value
contours = []
imgThreshCopy = imgThresh.copy()
# find all contours in plate
contours, npaHierarchy = cv2.findContours(imgThreshCopy, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours: # for each contour
possibleChar = PossibleChar.PossibleChar(contour)
if checkIfPossibleChar(possibleChar): # if contour is a possible char, note this does not compare to other chars (yet) . . .
listOfPossibleChars.append(possibleChar) # add to list of possible chars
# end if
# end if
return listOfPossibleChars
# end function
###################################################################################################
示例13: tightboundingbox
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import CHAIN_APPROX_SIMPLE [as 别名]
def tightboundingbox(self, image):
ret, thresh = cv2.threshold(np.array(image, dtype=np.uint8), 0, 255, 0)
im2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
bb = []
for c in contours:
x, y, w, h = cv2.boundingRect(c)
# +1 is done to encapsulate entire figure
w += 2
h += 2
x -= 1
y -= 1
x = np.max([0, x])
y = np.max([0, y])
bb.append([y, x, w, h])
bb = self.nms(bb)
return bb
示例14: segment
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import CHAIN_APPROX_SIMPLE [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
#--------------------------------------------------------------
示例15: compare_ssim_debug
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import CHAIN_APPROX_SIMPLE [as 别名]
def compare_ssim_debug(image_a, image_b, color=(255, 0, 0)):
"""
Args:
image_a, image_b: opencv image or PIL.Image
color: (r, g, b) eg: (255, 0, 0) for red
Refs:
https://www.pyimagesearch.com/2017/06/19/image-difference-with-opencv-and-python/
"""
ima, imb = conv2cv(image_a), conv2cv(image_b)
score, diff = compare_ssim(ima, imb, full=True)
diff = (diff * 255).astype('uint8')
_, thresh = cv2.threshold(diff, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)
cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
cv2color = tuple(reversed(color))
im = ima.copy()
for c in cnts:
x, y, w, h = cv2.boundingRect(c)
cv2.rectangle(im, (x, y), (x+w, y+h), cv2color, 2)
# todo: show image
cv2pil(im).show()
return im