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


Python cv2.moments方法代码示例

本文整理汇总了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 
开发者ID:gaborvecsei,项目名称:Color-Tracker,代码行数:19,代码来源:helpers.py

示例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 
开发者ID:mzucker,项目名称:page_dewarp,代码行数:22,代码来源:page_dewarp.py

示例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 
开发者ID:orig74,项目名称:DroneSimLab,代码行数:18,代码来源:hsv_track.py

示例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 
开发者ID:vsvinayak,项目名称:mnist-helper,代码行数:27,代码来源:mnist_helpers.py

示例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 
开发者ID:hoanglehaithanh,项目名称:Traffic-Sign-Detection,代码行数:21,代码来源:main.py

示例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 
开发者ID:hoanglehaithanh,项目名称:Traffic-Sign-Detection,代码行数:21,代码来源:main.py

示例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) 
开发者ID:rbaron,项目名称:omr,代码行数:20,代码来源:omr.py

示例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 
开发者ID:dwalton76,项目名称:rubiks-cube-tracker,代码行数:26,代码来源:__init__.py

示例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) 
开发者ID:osrf,项目名称:rosbook,代码行数:27,代码来源:follower_p.py

示例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训练 
开发者ID:wzh191920,项目名称:License-Plate-Recognition,代码行数:11,代码来源:predict.py

示例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 
开发者ID:hsSam,项目名称:PracticalPythonAndOpenCV_CaseStudies,代码行数:17,代码来源:dataset.py

示例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 
开发者ID:kwea123,项目名称:VTuber_Unity,代码行数:37,代码来源:misc.py

示例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 
开发者ID:makelove,项目名称:OpenCV-Python-Tutorial,代码行数:10,代码来源:digits.py

示例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] 
开发者ID:makelove,项目名称:OpenCV-Python-Tutorial,代码行数:13,代码来源:hogsvm.py

示例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 导数 
开发者ID:makelove,项目名称:OpenCV-Python-Tutorial,代码行数:13,代码来源:47.2-使用SVM进行-手写数据OCR.py


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