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


Python cv2.KMEANS_RANDOM_CENTERS属性代码示例

本文整理汇总了Python中cv2.KMEANS_RANDOM_CENTERS属性的典型用法代码示例。如果您正苦于以下问题:Python cv2.KMEANS_RANDOM_CENTERS属性的具体用法?Python cv2.KMEANS_RANDOM_CENTERS怎么用?Python cv2.KMEANS_RANDOM_CENTERS使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在cv2的用法示例。


在下文中一共展示了cv2.KMEANS_RANDOM_CENTERS属性的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _detect_team_color

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import KMEANS_RANDOM_CENTERS [as 别名]
def _detect_team_color(self, pixels):
        criteria = \
            (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)

        pixels = np.array(pixels.reshape((-1, 3)), dtype=np.float32)

        ret, label, center = cv2.kmeans(
            pixels, 2, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)

        # one is black, another is the team color.

        colors = np.array(center, dtype=np.uint8).reshape((1, 2, 3))
        colors_hsv = cv2.cvtColor(colors, cv2.COLOR_BGR2HSV)
        x = np.argmax(colors_hsv[:, :, 2])
        team_color_bgr = colors[0, x, :]
        team_color_hsv = colors_hsv[0, x, :]

        return {
            'rgb': cv2.cvtColor(colors, cv2.COLOR_BGR2RGB).tolist()[0][x],
            'hsv': cv2.cvtColor(colors, cv2.COLOR_BGR2HSV).tolist()[0][x],
        } 
开发者ID:hasegaw,项目名称:IkaLog,代码行数:23,代码来源:inklings_tracker.py

示例2: color_quantization

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import KMEANS_RANDOM_CENTERS [as 别名]
def color_quantization(image, k):
    """Performs color quantization using K-means clustering algorithm"""

    # Transform image into 'data':
    data = np.float32(image).reshape((-1, 3))
    # print(data.shape)

    # Define the algorithm termination criteria (the maximum number of iterations and/or the desired accuracy):
    # In this case the maximum number of iterations is set to 20 and epsilon = 1.0
    criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 20, 1.0)

    # Apply K-means clustering algorithm:
    ret, label, center = cv2.kmeans(data, k, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)

    # At this point we can make the image with k colors
    # Convert center to uint8:
    center = np.uint8(center)
    # Replace pixel values with their center value:
    result = center[label.flatten()]
    result = result.reshape(img.shape)
    return result


# Create the dimensions of the figure and set title: 
开发者ID:PacktPublishing,项目名称:Mastering-OpenCV-4-with-Python,代码行数:26,代码来源:k_means_color_quantization.py

示例3: kmeans

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import KMEANS_RANDOM_CENTERS [as 别名]
def kmeans(samples, k, criteria = None, attempts = 3, flags = None):
    import cv2
    
    if flags == None:
        flags = cv2.KMEANS_RANDOM_CENTERS
    if criteria == None:
        criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
    samples = np.asarray(samples, dtype = np.float32)
    _,labels,centers = cv2.kmeans(samples, k, criteria, attempts, flags)
    labels = util.np.flatten(labels)
    clusters = [None]*k
    for idx, label in enumerate(labels):
        if clusters[label] is None:
            clusters[label] = []
        clusters[label].append(idx)
        
    for  idx, cluster in enumerate(clusters):
        if cluster == None:
            logging.warn('Empty cluster appeared.')
            clusters[idx] = []
            
    return labels, clusters, centers 
开发者ID:HLIG,项目名称:HUAWEIOCR-2019,代码行数:24,代码来源:ml.py

示例4: kmeans

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import KMEANS_RANDOM_CENTERS [as 别名]
def kmeans(vs, ks, niter):
        criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER,
                    niter, 0.01)
        flags = cv2.KMEANS_RANDOM_CENTERS
        compactness, labels, centers = cv2.kmeans(
            vs, ks, criteria, 1, flags)
        return centers 
开发者ID:hdidx,项目名称:hdidx,代码行数:9,代码来源:util.py

示例5: drawBitmap

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import KMEANS_RANDOM_CENTERS [as 别名]
def drawBitmap(w_image):
    print('Reducing the colors...')
    Z = w_image.reshape((-1, 3))

    # convert to np.float32
    Z = np.float32(Z)

    # define criteria, number of clusters(K) and apply kmeans()
    criteria = (cv2.TERM_CRITERIA_EPS, 10, 1.0)
    global K
    ret, label, center = cv2.kmeans(
        Z, K, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)

    # Now convert back into uint8, and make original image
    center = np.uint8(center)
    res = center[label.flatten()]
    res = res.reshape(w_image.shape)
    no = 1
    for i in center:
        sys.stdout.write('\rDrawing: %.2f%% [' % (
            no / K * 100) + '#' * no + ' ' * (K - no) + ']')
        no += 1
        res2 = cv2.inRange(res, i, i)
        res2 = cv2.bitwise_not(res2)
        cv2.imwrite('.tmp.bmp', res2)
        os.system('potrace.exe .tmp.bmp -s --flat')
        # print(i)
        drawSVG('.tmp.svg', '#%02x%02x%02x' % (i[2], i[1], i[0]))
    os.remove('.tmp.bmp')
    os.remove('.tmp.svg')
    print('\n\rFinished, close the window to exit.')
    te.done() 
开发者ID:tfx2001,项目名称:python-turtle-draw-svg,代码行数:34,代码来源:main.py

示例6: get_dominant_color

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import KMEANS_RANDOM_CENTERS [as 别名]
def get_dominant_color(pixels, clusters, attempts):
        """
        Given a (N, Channels) array of pixel values, compute the dominant color via K-means
        """
        clusters = min(clusters, len(pixels))
        flags = cv2.KMEANS_RANDOM_CENTERS
        criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_MAX_ITER, 1, 10)
        _, labels, centroids = cv2.kmeans(pixels.astype(np.float32), clusters, None, criteria, attempts, flags)
        _, counts = np.unique(labels, return_counts=True)
        dominant = centroids[np.argmax(counts)]
        return dominant 
开发者ID:tasercake,项目名称:lowpolypy,代码行数:13,代码来源:process.py

示例7: kmeans

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import KMEANS_RANDOM_CENTERS [as 别名]
def kmeans(array: np.ndarray, k: int = 3):
        n_channels = 3 if len(np.shape(array)) == 3 else 1
        arr_values = array.reshape((-1, n_channels))
        arr_values = np.float32(arr_values)
        criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 0.2)
        _, labels, (centers) = cv2.kmeans(arr_values, k, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
        centers = np.uint8(centers)
        clustered_arr = centers[labels.flatten()]
        clustered_arr = clustered_arr.reshape(array.shape)
        return clustered_arr 
开发者ID:haruiz,项目名称:CvStudio,代码行数:12,代码来源:img_util.py

示例8: test_kmeans

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import KMEANS_RANDOM_CENTERS [as 别名]
def test_kmeans(img):
    ## K均值聚类
    z = img.reshape((-1, 3))
    z = np.float32(z)
    criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
    ret, label, center = cv2.kmeans(z, 20, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
    center = np.uint8(center)
    res = center[label.flatten()]
    res2 = res.reshape((img.shape))
    cv2.imshow('preview', res2)
    cv2.waitKey() 
开发者ID:NetEaseGame,项目名称:ATX,代码行数:13,代码来源:test_monkey.py

示例9: k_means

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import KMEANS_RANDOM_CENTERS [as 别名]
def k_means(points: np.ndarray):
    """返回一个数组经kmeans分类后的k值以及标签,k值由计算拐点给出

    Args:
        points (np.ndarray): 需分类数据

    Returns:
        Tuple[int, np.ndarry]: k值以及标签数组
    """

    # Define criteria = ( type, max_iter = 10 , epsilon = 1.0 )
    criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)

    # Set flags (Just to avoid line break in the code)
    flags = cv2.KMEANS_RANDOM_CENTERS
    length = []
    max_k = min(10, points.shape[0])
    for k in range(2, max_k + 1):
        avg = 0
        for i in range(5):
            compactness, _, _ = cv2.kmeans(
                points, k, None, criteria, 10, flags)
            avg += compactness
        avg /= 5
        length.append(avg)

    peek_pos = find_peek(length)
    k = peek_pos + 2
    # print(k)
    return k, cv2.kmeans(points, k, None, criteria, 10, flags)[1]  # labels 
开发者ID:zhaobenx,项目名称:Image-stitcher,代码行数:32,代码来源:k_means.py

示例10: k_means

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import KMEANS_RANDOM_CENTERS [as 别名]
def k_means(self, keypoints):
        # convert to np.float32
        X = [k.pt[0] for k in keypoints]
        Y = [k.pt[1] for k in keypoints]

        Z = np.float32(np.vstack((X, Y)).T)

        # define criteria and apply kmeans()
        criteria = (cv2.TERM_CRITERIA_EPS +
                    cv2.TERM_CRITERIA_MAX_ITER, 25, 1.0)

        K = 6

        ret, label, center = cv2.kmeans(
            Z, K, criteria, 25, cv2.KMEANS_RANDOM_CENTERS)

        Leaves = {}
        for x in range(K):
            Leaves['Center%d' % x] = Z[label.ravel() == x]

        Centers = {}
        for x in range(K):
            Centers['Center%d' % x] = center[
                label.flatten()][label.ravel() == x][0, :]

        ReferencePoint = np.array([0, 0])
        print Centers.values()

        Distances = {}
        for x in range(K):
            Distances['Center%d' % x] = distance.euclidean(
                ReferencePoint.ravel(), Centers['Center%d' % x])

        CentersOrderedList = sorted(Distances.items(), key=lambda x: x[1])

        leaves_data = {'SocketA': [Leaves[CentersOrderedList[0][0]], Centers[CentersOrderedList[0][0]], self.MaxLeavesSocketA],
                       'SocketB': [Leaves[CentersOrderedList[1][0]], Centers[CentersOrderedList[1][0]], self.MaxLeavesSocketB],
                       'SocketC': [Leaves[CentersOrderedList[2][0]], Centers[CentersOrderedList[2][0]], self.MaxLeavesSocketC],
                       'SocketD': [Leaves[CentersOrderedList[3][0]], Centers[CentersOrderedList[3][0]], self.MaxLeavesSocketD],
                       'SocketE': [Leaves[CentersOrderedList[4][0]], Centers[CentersOrderedList[4][0]], self.MaxLeavesSocketE],
                       'SocketF': [Leaves[CentersOrderedList[5][0]], Centers[CentersOrderedList[5][0]], self.MaxLeavesSocketF]}

        return leaves_data 
开发者ID:OpenAgricultureFoundation,项目名称:openag_cv,代码行数:45,代码来源:BlobDetector.py

示例11: extract_cols

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import KMEANS_RANDOM_CENTERS [as 别名]
def extract_cols(image, numCols):
    # convert to np.float32 matrix that can be clustered
    Z = image.reshape((-1,3))
    Z = np.float32(Z)

    # Set parameters for the clustering
    max_iter = 20
    epsilon = 1.0
    K = numCols
    criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, max_iter, epsilon)

    # cluster
    lab = []
    compactness, labels, centers = cv2.kmeans(data=Z, K=K, bestLabels=None, criteria=criteria, attempts=10, flags=cv2.KMEANS_RANDOM_CENTERS)

    clusterCounts = []
    for idx in range(K):
        count = len(Z[labels == idx])
        clusterCounts.append(count)

    #Reverse the cols stored in centers because cols are stored in BGR
    #in opencv.
    rgbCenters = []
    for center in centers:
        bgr = center.tolist()
        bgr.reverse()
        rgbCenters.append(bgr)

    cols = []
    for i in range(K):
        iCol = {
            "count": clusterCounts[i],
            "col": rgbCenters[i]
        }
        cols.append(iCol)

    return cols


#
# Calculates change data one one frame to the next one.
# 
开发者ID:tafsiri,项目名称:filmstrip,代码行数:44,代码来源:scene_detection.py

示例12: color_quantization

# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import KMEANS_RANDOM_CENTERS [as 别名]
def color_quantization(image, k):
    """Performs color quantization using K-means clustering algorithm"""

    # Transform image into 'data':
    data = np.float32(image).reshape((-1, 3))
    # print(data.shape)

    # Define the algorithm termination criteria (the maximum number of iterations and/or the desired accuracy):
    # In this case the maximum number of iterations is set to 20 and epsilon = 1.0
    criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 20, 1.0)

    # Apply K-means clustering algorithm:
    ret, label, center = cv2.kmeans(data, k, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)

    # At this point we can make the image with k colors
    # Convert center to uint8:
    center = np.uint8(center)
    # Replace pixel values with their center value:
    result = center[label.flatten()]
    result = result.reshape(img.shape)

    # Build the 'color_distribution' legend.
    # We will use the number of pixels assigned to each center value:
    counter = collections.Counter(label.flatten())
    print(counter)

    # Calculate the total number of pixels of the input image:
    total = img.shape[0] * img.shape[1]

    # Assign width and height to the color_distribution image:
    desired_width = img.shape[1]
    # The difference between 'desired_height' and 'desired_height_colors'
    # will be the separation between the images
    desired_height = 70
    desired_height_colors = 50

    # Initialize the color_distribution image:
    color_distribution = np.ones((desired_height, desired_width, 3), dtype="uint8") * 255
    # Initialize start:
    start = 0

    for key, value in counter.items():
        # Calculate the normalized value:
        value_normalized = value / total * desired_width

        # Move end to the right position:
        end = start + value_normalized

        # Draw rectangle corresponding to the current color:
        cv2.rectangle(color_distribution, (int(start), 0), (int(end), desired_height_colors), center[key].tolist(), -1)
        # Update start:
        start = end

    return np.vstack((color_distribution, result))


# Create the dimensions of the figure and set title: 
开发者ID:PacktPublishing,项目名称:Mastering-OpenCV-4-with-Python,代码行数:59,代码来源:k_means_color_quantization_distribution.py


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