當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。