本文整理汇总了Python中cv2.moments方法的典型用法代码示例。如果您正苦于以下问题:Python cv2.moments方法的具体用法?Python cv2.moments怎么用?Python cv2.moments使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类cv2
的用法示例。
在下文中一共展示了cv2.moments方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_contour_centers
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import moments [as 别名]
def get_contour_centers(contours: np.ndarray) -> np.ndarray:
"""
Calculate the centers of the contours
:param contours: Contours detected with find_contours
:return: object centers as numpy array
"""
if len(contours) == 0:
return np.array([])
# ((x, y), radius) = cv2.minEnclosingCircle(c)
centers = np.zeros((len(contours), 2), dtype=np.int16)
for i, c in enumerate(contours):
M = cv2.moments(c)
center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"]))
centers[i] = center
return centers
示例2: blob_mean_and_tangent
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import moments [as 别名]
def blob_mean_and_tangent(contour):
moments = cv2.moments(contour)
area = moments['m00']
mean_x = moments['m10'] / area
mean_y = moments['m01'] / area
moments_matrix = np.array([
[moments['mu20'], moments['mu11']],
[moments['mu11'], moments['mu02']]
]) / area
_, svd_u, _ = cv2.SVDecomp(moments_matrix)
center = np.array([mean_x, mean_y])
tangent = svd_u[:, 0].flatten().copy()
return center, tangent
示例3: find_red
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import moments [as 别名]
def find_red(img):
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv,(130,130,180),(255,255,255))
mask = cv2.erode(mask, np.ones((2,1)) , iterations=1)
mask = cv2.dilate(mask, None, iterations=3)
cnts = cv2.findContours(mask, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)[-2]
frame=img.copy()
###based on example from http://www.pyimagesearch.com/2015/09/14/ball-tracking-with-opencv
if len(cnts) > 0:
c = max(cnts, key=cv2.contourArea)
((x, y), radius) = cv2.minEnclosingCircle(c)
M = cv2.moments(c)
center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"]))
if radius > 3:
cv2.circle(frame, (int(x), int(y)), 12,(0, 255, 255), 2)
return frame
示例4: deskew
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import moments [as 别名]
def deskew(image, image_shape, negated=False):
"""
This method deskwes an image using moments
:param image: a numpy nd array input image
:param image_shape: a tuple denoting the image`s shape
:param negated: a boolean flag telling whether the input image is a negated one
:returns: a numpy nd array deskewd image
"""
# negate the image
if not negated:
image = 255-image
# calculate the moments of the image
m = cv2.moments(image)
if abs(m['mu02']) < 1e-2:
return image.copy()
# caclulating the skew
skew = m['mu11']/m['mu02']
M = numpy.float32([[1, skew, -0.5*image_shape[0]*skew], [0,1,0]])
img = cv2.warpAffine(image, M, image_shape, flags=cv2.WARP_INVERSE_MAP|cv2.INTER_LINEAR)
return img
示例5: findLargestSign
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import moments [as 别名]
def findLargestSign(image, contours, threshold, distance_theshold):
max_distance = 0
coordinate = None
sign = None
for c in contours:
M = cv2.moments(c)
if M["m00"] == 0:
continue
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])
is_sign, distance = contourIsSign(c, [cX, cY], 1-threshold)
if is_sign and distance > max_distance and distance > distance_theshold:
max_distance = distance
coordinate = np.reshape(c, [-1,2])
left, top = np.amin(coordinate, axis=0)
right, bottom = np.amax(coordinate, axis = 0)
coordinate = [(left-2,top-2),(right+3,bottom+1)]
sign = cropSign(image,coordinate)
return sign, coordinate
示例6: findSigns
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import moments [as 别名]
def findSigns(image, contours, threshold, distance_theshold):
signs = []
coordinates = []
for c in contours:
# compute the center of the contour
M = cv2.moments(c)
if M["m00"] == 0:
continue
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])
is_sign, max_distance = contourIsSign(c, [cX, cY], 1-threshold)
if is_sign and max_distance > distance_theshold:
sign = cropContour(image, [cX, cY], max_distance)
signs.append(sign)
coordinate = np.reshape(c, [-1,2])
top, left = np.amin(coordinate, axis=0)
right, bottom = np.amax(coordinate, axis = 0)
coordinates.append([(top-2,left-2),(right+1,bottom+1)])
return signs, coordinates
示例7: calculate_contour_features
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import moments [as 别名]
def calculate_contour_features(contour):
"""Calculates interesting properties (features) of a contour.
We use these features to match shapes (contours). In this script,
we are interested in finding shapes in our input image that look like
a corner. We do that by calculating the features for many contours
in the input image and comparing these to the features of the corner
contour. By design, we know exactly what the features of the real corner
contour look like - check out the calculate_corner_features function.
It is crucial for these features to be invariant both to scale and rotation.
In other words, we know that a corner is a corner regardless of its size
or rotation. In the past, this script implemented its own features, but
OpenCV offers much more robust scale and rotational invariant features
out of the box - the Hu moments.
"""
moments = cv2.moments(contour)
return cv2.HuMoments(moments)
示例8: __init__
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import moments [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
示例9: image_callback
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import moments [as 别名]
def image_callback(self, msg):
image = self.bridge.imgmsg_to_cv2(msg,desired_encoding='bgr8')
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
lower_yellow = numpy.array([ 10, 10, 10])
upper_yellow = numpy.array([255, 255, 250])
mask = cv2.inRange(hsv, lower_yellow, upper_yellow)
h, w, d = image.shape
search_top = 3*h/4
search_bot = 3*h/4 + 20
mask[0:search_top, 0:w] = 0
mask[search_bot:h, 0:w] = 0
M = cv2.moments(mask)
if M['m00'] > 0:
cx = int(M['m10']/M['m00'])
cy = int(M['m01']/M['m00'])
cv2.circle(image, (cx, cy), 20, (0,0,255), -1)
# BEGIN CONTROL
err = cx - w/2
self.twist.linear.x = 0.2
self.twist.angular.z = -float(err) / 100
self.cmd_vel_pub.publish(self.twist)
# END CONTROL
cv2.imshow("window", image)
cv2.waitKey(3)
示例10: deskew
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import moments [as 别名]
def deskew(img):
m = cv2.moments(img)
if abs(m['mu02']) < 1e-2:
return img.copy()
skew = m['mu11']/m['mu02']
M = np.float32([[1, skew, -0.5*SZ*skew], [0, 1, 0]])
img = cv2.warpAffine(img, M, (SZ, SZ), flags=cv2.WARP_INVERSE_MAP | cv2.INTER_LINEAR)
return img
#来自opencv的sample,用于svm训练
示例11: de_skew
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import moments [as 别名]
def de_skew(image, width):
# Grab the width and height of the image and compute moments for the image
(h, w) = image.shape[:2]
moments = cv2.moments(image)
# De-skew the image by applying an affine transformation
skew = moments["mu11"] / moments["mu02"]
matrix = np.float32([[1, skew, -0.5 * w * skew], [0, 1, 0]])
image = cv2.warpAffine(image, matrix, (w, h), flags=cv2.WARP_INVERSE_MAP | cv2.INTER_LINEAR)
# Resize the image to have a constant width
image = imutils.resize(image, width=width)
# Return the de-skewed image
return image
示例12: detect_iris
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import moments [as 别名]
def detect_iris(frame, marks, side='left'):
"""
return:
x: the x coordinate of the iris.
y: the y coordinate of the iris.
x_rate: how much the iris is toward the left. 0 means totally left and 1 is totally right.
y_rate: how much the iris is toward the top. 0 means totally top and 1 is totally bottom.
"""
mask = np.full(frame.shape[:2], 255, np.uint8)
if side == 'left':
region = marks[36:42].astype(np.int32)
elif side == 'right':
region = marks[42:48].astype(np.int32)
try:
cv2.fillPoly(mask, [region], (0, 0, 0))
eye = cv2.bitwise_not(frame, frame.copy(), mask=mask)
# Cropping on the eye
margin = 4
min_x = np.min(region[:, 0]) - margin
max_x = np.max(region[:, 0]) + margin
min_y = np.min(region[:, 1]) - margin
max_y = np.max(region[:, 1]) + margin
eye = eye[min_y:max_y, min_x:max_x]
eye = cv2.cvtColor(eye, cv2.COLOR_RGB2GRAY)
eye_binarized = cv2.threshold(eye, np.quantile(eye, 0.2), 255, cv2.THRESH_BINARY)[1]
contours, _ = cv2.findContours(eye_binarized, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
contours = sorted(contours, key=cv2.contourArea)
moments = cv2.moments(contours[-2])
x = int(moments['m10'] / moments['m00']) + min_x
y = int(moments['m01'] / moments['m00']) + min_y
return x, y, (x-min_x-margin)/(max_x-min_x-2*margin), (y-min_y-margin)/(max_y-min_y-2*margin)
except:
return 0, 0, 0.5, 0.5
示例13: deskew
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import moments [as 别名]
def deskew(img):
m = cv2.moments(img)
if abs(m['mu02']) < 1e-2:
return img.copy()
skew = m['mu11']/m['mu02']
M = np.float32([[1, skew, -0.5*SZ*skew], [0, 1, 0]])
img = cv2.warpAffine(img, M, (SZ, SZ), flags=cv2.WARP_INVERSE_MAP | cv2.INTER_LINEAR)
return img
示例14: deskew
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import moments [as 别名]
def deskew(img):
m = cv2.moments(img)
if abs(m['mu02']) < 1e-2:
return img.copy()
skew = m['mu11']/m['mu02']
M = np.float32([[1, skew, -0.5*SZ*skew], [0, 1, 0]])
img = cv2.warpAffine(img,M,(SZ, SZ),flags=affine_flags)
return img
## [deskew]
## [hog]
示例15: deskew
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import moments [as 别名]
def deskew(img):
m = cv2.moments(img)
if abs(m['mu02']) < 1e-2:
return img.copy()
skew = m['mu11'] / m['mu02']
M = np.float32([[1, skew, -0.5 * SZ * skew], [0, 1, 0]])
img = cv2.warpAffine(img, M, (SZ, SZ), flags=affine_flags)
return img
# 计算图像 X 方向和 Y 方向的 Sobel 导数