當前位置: 首頁>>代碼示例>>Python>>正文


Python cv2.kmeans方法代碼示例

本文整理匯總了Python中cv2.kmeans方法的典型用法代碼示例。如果您正苦於以下問題:Python cv2.kmeans方法的具體用法?Python cv2.kmeans怎麽用?Python cv2.kmeans使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在cv2的用法示例。


在下文中一共展示了cv2.kmeans方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _detect_team_color

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import kmeans [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 [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 [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 [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: _kmeans_colour

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import kmeans [as 別名]
def _kmeans_colour(self, row: np.ndarray) -> Tuple:
        _, labels, palette = cv2.kmeans(
            row, self.k, None, self.criteria, 10, self.flags
        )
        _, counts = np.unique(labels, return_counts=True)

        return palette[np.argmax(counts)] / 255 
開發者ID:lucashadfield,項目名稱:speck,代碼行數:9,代碼來源:colour.py

示例6: drawBitmap

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import kmeans [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

示例7: get_dominant_color

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import kmeans [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

示例8: kmeans

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import kmeans [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

示例9: color_quantization

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import kmeans [as 別名]
def color_quantization(img, n_cluster, iteration, epsilon=1.0):
        Z = img.reshape((-1, 3))
        Z = np.float32(Z)

        criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, iteration, epsilon)
        ret, label, center = cv2.kmeans(Z, n_cluster, None, criteria, iteration, cv2.KMEANS_PP_CENTERS)

        labels = label.reshape((img.shape[0], img.shape[1], 1))
        # center = np.uint(center)
        # visual = center[label.flatten()]
        # visual = visual.reshape(img.shape)
        # visual = np.uint8(visual)

        return labels 
開發者ID:YoongiKim,項目名稱:Walk-Assistant,代碼行數:16,代碼來源:filter.py

示例10: test_kmeans

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import kmeans [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

示例11: k_means

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import kmeans [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

示例12: get_group_center

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import kmeans [as 別名]
def get_group_center(points1: np.ndarray, points2: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
    """輸入兩個相對應的點對數組,返回經kmeans優化後的兩個數組

    Args:
        points1 (np.ndarray): 數組一
        points2 (np.ndarray): 數組二

    Returns:
        Tuple[np.ndarray, np.ndarray]: 兩數組
    """

    k, labels = k_means(points1)
    labels = labels.flatten()
    selected_centers1 = []
    selected_centers2 = []
    for i in range(k):
        center1 = np.mean(points1[labels == i], axis=0)
        center2 = np.mean(points2[labels == i], axis=0)
        # center1 = points1[labels == i][0]
        # center2 = points2[labels == i][0]

        selected_centers1.append(center1)
        selected_centers2.append(center2)

    selected_centers1, selected_centers2 = np.array(
        selected_centers1), np.array(selected_centers2)

    # return selected_centers1, selected_centers2
    # return np.append(selected_centers1, points1, axis=0), np.append(selected_centers2, points2, axis=0)
    return points1, points2 
開發者ID:zhaobenx,項目名稱:Image-stitcher,代碼行數:32,代碼來源:k_means.py

示例13: k_means

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import kmeans [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

示例14: extract_cols

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import kmeans [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

示例15: color_quantization

# 需要導入模塊: import cv2 [as 別名]
# 或者: from cv2 import kmeans [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方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。