Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

After some attempts I already solved the errors: 1- sample Mat must be float32 so, sample.floatPtr(y + x*mat.rows)[z] = mat.ucharPtr(y,x)[z]; 2- TermCriteria is an object an it has to be created with new 3- In opencv.js the constants cv.TERM_CRITERIA_EPS and cv.TERM_CRITERIA_MAX_ITER are different cv.TermCriteria_EPS + cv.TermCriteria_MAX_ITER

The code is working, the only thing outputImage is float32 and the original image I used was u8Int, I am figuring out how convert it from float32 to u8int

`

<html>
<head>
<meta charset="utf-8">
<title>Hello OpenCV.js</title>
</head>
<body>
<script onload="onOpenCvReady();" src="opencv.js" async="" type="text/javascript"></script>
<h1>K Means Example</h1>
<p id="status">OpenCV.js is loading...</p>
<div>
<div class="inputoutput"><img id="imageSrc" alt="No Image" />
<div class="caption">imageSrc <input id="fileInput" name="file" type="file" /></div>
</div>
<div class="inputoutput"><canvas id="canvasOutput"></canvas>
<div class="caption">canvasOutput</div>
</div>
<script type="text/javascript">let imgElement = document.getElementById('imageSrc');
let imgElement = document.getElementById('imageSrc');
let inputElement = document.getElementById('fileInput');
inputElement.addEventListener('change', (e) => {
  imgElement.src = URL.createObjectURL(e.target.files[0]);
}, false);
imgElement.onload = function() {
  let mat = cv.imread(imgElement);

let sample= new cv.Mat(mat.rows * mat.cols, 3, cv.CV_32F);
for( var y = 0; y < mat.rows; y++ )
    for( var x = 0; x < mat.cols; x++ )
      for( var z = 0; z < 3; z++)
        sample.floatPtr(y + x*mat.rows)[z] = mat.ucharPtr(y,x)[z];

  var clusterCount = 8;
  var labels= new cv.Mat();
  var attempts = 5;
  var centers= new cv.Mat();

  var crite= new cv.TermCriteria(cv.TermCriteria_EPS + cv.TermCriteria_MAX_ITER, 10000, 0.0001);
  var criteria = [1,10,0.0001];

  cv.kmeans(sample, clusterCount, labels, crite, attempts, cv.KMEANS_RANDOM_CENTERS, centers );

 var newImage= new cv.Mat(mat.size(),mat.type());
 for( var y = 0; y < mat.rows; y++ )
    for( var x = 0; x < mat.cols; x++ )
    { 
      var cluster_idx = labels.intAt(y + x*mat.rows,0);
      newImage.floatPtr(y,x)[0] = centers.floatAt(cluster_idx, 0);
      newImage.floatPtr(y,x)[1] = centers.floatAt(cluster_idx, 1);
      newImage.floatPtr(y,x)[2] = centers.floatAt(cluster_idx, 2);
      newImage.floatPtr(y,x)[3] = 255;

    }
  cv.imshow('canvasOutput', newImage);
  mat.delete();

}

function onOpenCvReady() {
  document.getElementById('status').innerHTML = 'OpenCV.js is ready.';
}</script>
</div>
</body>
</html>

strong text`: