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 7065395
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T04:57:03+00:00 2026-05-28T04:57:03+00:00

I’m using v2.1 with the built-in python interface. I’m trying to load an image

  • 0

I’m using v2.1 with the built-in python interface.
I’m trying to load an image from a file, transform it to lab
and get the clusters from the ab plane.

I have a working matlab code but don’t know how to do the same in opencv.
How do I reshape a jpeg or png images and feed it to kmeans?

Thanks

The error I’m getting:

OpenCV Error: Assertion failed (labels.isContinuous() && labels.type() == CV_32S && (labels.cols == 1 || labels.rows == 1) && labels.cols + labels.rows - 1 == data.rows) in cvKMeans2, file /build/buildd/opencv-2.1.0/src/cxcore/cxmatrix.cpp, line 1202
Traceback (most recent call last):
File "main.py", line 24, in <module>
(cv.CV_TERMCRIT_EPS + cv.CV_TERMCRIT_ITER, 10, 1.0))
cv.error: labels.isContinuous() && labels.type() == CV_32S && (labels.cols == 1 || labels.rows == 1) && labels.cols + labels.rows - 1 == data.rows

Thanks

Working matlab code:

im=imread(fName);
cform = makecform('srgb2lab');
lab_im = applycform(im,cform);
ab = double(lab_im(:,:,2:3));
ab = reshape(ab,nrows*ncols,2);
nColors = 2;
[cluster_idx cluster_center] = kmeans(ab,nColors,'distance','sqEuclidean','Replicates',3,'start', 'uniform');

python-opencv (not working)

img = cv.LoadImage("test.jpg")
clusters = cv.CreateImage((img.width*img.height, 1), img.depth, 1)
lab_img = cv.CreateImage(cv.GetSize(img), img.depth, 3)
cv.CvtColor(img, lab_img, cv.CV_RGB2Lab)

ab_img = cv.CreateImage(cv.GetSize(img), img.depth, 2)
cv.MixChannels([lab_img], [ab_img], [
    (1, 0),
    (2, 1)
])

cv.Reshape(ab_img, ab_img.channels, ab_img.width*ab_img.height)
cluster_count = 3
cv.KMeans2(ab_img, cluster_count, clusters,
    (cv.CV_TERMCRIT_EPS + cv.CV_TERMCRIT_ITER, 10, 1.0))
  • 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-05-28T04:57:04+00:00Added an answer on May 28, 2026 at 4:57 am

    I didn’t have to work out what the problem with your source was, but here’s my implementation:

    import cv
    import sys
    
    if len(sys.argv) < 3:
        print 'usage: %s image.png K' % __file__
        sys.exit(1)
    im = cv.LoadImage(sys.argv[1], cv.CV_LOAD_IMAGE_COLOR)
    K = int(sys.argv[2])
    
    #
    # Prepare the data for K-means.  Represent each pixel in the image as a 3D
    # vector (each dimension corresponds to one of B,G,R color channel value).
    # Create a column of such vectors -- it will be width*height tall, 1 wide
    # and have a total 3 channels.
    #
    col = cv.Reshape(im, 3, im.width*im.height)
    samples = cv.CreateMat(col.height, 1, cv.CV_32FC3)
    cv.Scale(col, samples)
    labels = cv.CreateMat(col.height, 1, cv.CV_32SC1)
    #
    # Run 10 iterations of the K-means algorithm.
    #
    crit = (cv.CV_TERMCRIT_EPS + cv.CV_TERMCRIT_ITER, 10, 1.0)
    cv.KMeans2(samples, K, labels, crit)
    #
    # Determine the center of each cluster.  The old OpenCV interface (C-style)
    # doesn't seem to provide an easy way to get these directly, so we have to
    # calculate them ourselves.
    #
    clusters = {}
    for i in range(col.rows):
        b,g,r,_ = cv.Get1D(samples, i)
        lbl,_,_,_ = cv.Get1D(labels, i)
        try:
            clusters[lbl].append((b,g,r))
        except KeyError:
            clusters[lbl] = [ (b,g,r) ]
    means = {}
    for c in clusters:
        b,g,r = zip(*clusters[c])
        means[c] = (sum(b)/len(b), sum(g)/len(g), sum(r)/len(r), _)
    
    #
    # Reassign each pixel in the original image to the center of its corresponding
    # cluster.
    #
    for i in range(col.rows):
        lbl,_,_,_ = cv.Get1D(labels, i)
        cv.Set1D(col, i, means[lbl])
    
    interactive = False
    if interactive:
        cv.ShowImage(__file__, im)
            cv.WaitKey(0)
    else:
        cv.SaveImage('kmeans-%d.png' % K, im)
    

    The following screenshots show the script in action. The image on the left is the original 128×128 pixel image. Images to its right are the result of clustering with K equal to 2, 4, 6 and 8, respectively.

    original K=2 K=4 K=6 K=8

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

Sidebar

Related Questions

We are using XSLT to translate a RIXML file to XML. Our RIXML contains
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
That's pretty much it. I'm using Nokogiri to scrape a web page what has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have just tried to save a simple *.rtf file with some websites and
For some reason, after submitting a string like this Jack’s Spindle from a text
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
I'm using v2.0 of ClassTextile.php, with the following call: $testimonial_text = $textile->TextileRestricted($_POST['testimonial']); ... and

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.