Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8392681
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T19:34:33+00:00 2026-06-09T19:34:33+00:00

I am considering to use OpenCV’s Kmeans implementation since it says to be faster…

  • 0

I am considering to use OpenCV’s Kmeans implementation since it says to be faster…

Now I am using package cv2 and function kmeans,

I can not understand the parameters’ description in their reference:

Python: cv2.kmeans(data, K, criteria, attempts, flags[, bestLabels[, centers]]) → retval, bestLabels, centers
samples – Floating-point matrix of input samples, one row per sample.
clusterCount – Number of clusters to split the set by.
labels – Input/output integer array that stores the cluster indices for every sample.
criteria – The algorithm termination criteria, that is, the maximum number of iterations and/or the desired accuracy. The accuracy is specified as criteria.epsilon. As soon as each of the cluster centers moves by less than criteria.epsilon on some iteration, the algorithm stops.
attempts – Flag to specify the number of times the algorithm is executed using different initial labelings. The algorithm returns the labels that yield the best compactness (see the last function parameter).
flags –
Flag that can take the following values:
KMEANS_RANDOM_CENTERS Select random initial centers in each attempt.
KMEANS_PP_CENTERS Use kmeans++ center initialization by Arthur and Vassilvitskii [Arthur2007].
KMEANS_USE_INITIAL_LABELS During the first (and possibly the only) attempt, use the user-supplied labels instead of computing them from the initial centers. For the second and further attempts, use the random or semi-random centers. Use one of KMEANS_*_CENTERS flag to specify the exact method.
centers – Output matrix of the cluster centers, one row per each cluster center.

what is the argument flags[, bestLabels[, centers]]) mean? and what about his one: → retval, bestLabels, centers ?

Here’s my code:

import cv, cv2
import scipy.io
import numpy

# read data from .mat file
mat = scipy.io.loadmat('...')
keys = mat.keys()
values = mat.viewvalues()

data_1 = mat[keys[0]]
nRows = data_1.shape[1] 
nCols = data_1.shape[0]
samples = cv.CreateMat(nRows, nCols, cv.CV_32FC1)
labels = cv.CreateMat(nRows, 1, cv.CV_32SC1)
centers = cv.CreateMat(nRows, 100, cv.CV_32FC1)
#centers = numpy.

for i in range(0, nCols):
    for j in range(0, nRows):
        samples[j, i] = data_1[i, j]


cv2.kmeans(data_1.transpose,
                              100,
                              criteria=(cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_MAX_ITER, 0.1, 10),
                              attempts=cv2.KMEANS_PP_CENTERS,
                              flags=cv2.KMEANS_PP_CENTERS,
)

And I encounter such error:

flags=cv2.KMEANS_PP_CENTERS,
TypeError: <unknown> is not a numpy array

How should I understand the parameter list and the usage of cv2.kmeans? Thanks

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-09T19:34:35+00:00Added an answer on June 9, 2026 at 7:34 pm

    the documentation on this function is almost impossible to find. I wrote the following Python code in a bit of a hurry, but it works on my machine. It generates two multi-variate Gaussian Distributions with different means and then classifies them using cv2.kmeans(). You may refer to this blog post to get some idea of the parameters.

    Handle imports:

    import cv
    import cv2
    import numpy as np
    import numpy.random as r
    

    Generate some random points and shape them appropriately:

    samples = cv.CreateMat(50, 2, cv.CV_32FC1)
    random_points = r.multivariate_normal((100,100), np.array([[150,400],[150,150]]), size=(25))
    random_points_2 = r.multivariate_normal((300,300), np.array([[150,400],[150,150]]), size=(25))   
    samples_list = np.append(random_points, random_points_2).reshape(50,2)  
    random_points_list = np.array(samples_list, np.float32) 
    samples = cv.fromarray(random_points_list)
    

    Plot the points before and after classification:

    blank_image = np.zeros((400,400,3))
    blank_image_classified = np.zeros((400,400,3))
    
    for point in random_points_list:
        cv2.circle(blank_image, (int(point[0]),int(point[1])), 1, (0,255,0),-1)
    
    temp, classified_points, means = cv2.kmeans(data=np.asarray(samples), K=2, bestLabels=None,
    criteria=(cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_MAX_ITER, 1, 10), attempts=1, 
    flags=cv2.KMEANS_RANDOM_CENTERS)   #Let OpenCV choose random centers for the clusters
    
    for point, allocation in zip(random_points_list, classified_points):
        if allocation == 0:
            color = (255,0,0)
        elif allocation == 1:
            color = (0,0,255)
        cv2.circle(blank_image_classified, (int(point[0]),int(point[1])), 1, color,-1)
    
    cv2.imshow("Points", blank_image)
    cv2.imshow("Points Classified", blank_image_classified)
    cv2.waitKey()
    

    Here you can see the original points:

    Points before classification

    Here are the points after they have been classified:
    Points after classification

    I hope that this answer may help you, it is not a complete guide to k-means, but it will at least show you how to pass the parameters to OpenCV.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am considering to use a function that was introduced in an iPhone OS
I am using Ruby on Rails 3 and I am considering to use ActiveResource
i'm building a site where we are considering to use a custom font (using
Im considering use CSLA.NET 3.8 for example for Security and Identity Management on a
I am considering the use of a tab control on a parent form for
In considering languages to use in creating a web-application that interfaces with a database
I'm considering starting to use this technic of icons as fonts, as it seems
I am considering whether I should use Turbogears or Pylons for my project. I
I wonder if the below use of between in the link is correct considering
Possible Duplicate: Why use document.write? Considering the negative effects of document.write(), why are most

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.