Clustering into 4 clusters

Hi,
I am using the following codes for clustering a grayscale image into 4 clusters. But, it gives error.

library(OpenImageR)

path = 'elephant.jpg'

im = readImage(path)

dim(im)

# convert to grayscale

im = OpenImageR::rgb_2gray(im)

# first resize the image to reduce the dimensions
imGryscale = resizeImage(im, 75, 75, method = 'bilinear')            

imageShow(imGryscale)                                                # plot the original image

# im2 = matrix(as.vector(im), nrow = nrow(im) * ncol(im), ncol = 1)

conv_to_3d = OpenImageR::List_2_Array(list(imGryscale, imGryscale, imGryscale))

im2 = apply(conv_to_3d, 3, as.vector) # vectorize

dim(im2)

# perform KMeans_rcpp clustering

km_rc = ClusterR::KMeans_rcpp(im2, clusters = 3, num_init = 5, max_iters = 100, 
                              initializer = 'optimal_init', verbose = F)

# km_rc$between.SS_DIV_total.SS

getcent = km_rc$centroids

getclust = km_rc$clusters

masks_lst = list()

for (j in sort(unique(getclust))) {

  mt = matrix(0, nrow = nrow(im2), ncol = ncol(im2))
  
  for (i in 1:length(getclust)) {
    
    if (getclust[i] == j) {
      
      mt[i, ] = as.vector(getcent[, j])
    }
  }
  
  masks_lst[[j]] = mt
}


lapply(masks_lst, dim)

out = list()

for (i in 1:length(masks_lst)) {
  
  tmp = masks_lst[[i]]
  
  dim(tmp) = c(nrow(conv_to_3d), ncol(conv_to_3d), 3)
  
  out[[i]] = tmp
}

lapply(out, dim)

for (k in 1:length(out)) {
  OpenImageR::imageShow(out[[k]])
  Sys.sleep(4)
}

The ERROR is:
Error in mt[i, ] <- as.vector(getcent[, j]) :
number of items to replace is not a multiple of replacement length

Could you please help me to solve this problem

Have you tried to google the error message "number of items to replace is not a multiple of replacement length"?

This is basically what is happening:

> a = 1:4
> a[2] = c(1,2)
Warning message:
In a[2] = c(1, 2) :
  number of items to replace is not a multiple of replacement length

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.