首页 > 解决方案 > 使用 K-Means 聚类和 R 进行图像处理

问题描述

我正在编写代码以使用网页获取图像文件的路径,对其应用 k-means 聚类,然后在同一网页上显示原始图像和修改后的图像。我能够在图像上应用 k-means 聚类并将其保存在磁盘上,但无法在网页上显示修改后的图像。请帮我。

谢谢,

阿尔文德

我正在使用以下代码:

    library(shiny)

server <- shinyServer(function(input, output) {

  output$files <- renderTable(input$files)

  files <- reactive({
    files <- input$files
    files$datapath <- gsub("\\\\", "/", files$datapath)
    files
  })

  print(files)


  output$images <- renderUI({
    if(is.null(input$files)) return(NULL)
    image_output_list <- 
      lapply(1:nrow(files()),
             function(i)
             {
               imagename = paste0("image", i)
               imageOutput(imagename)
             })

    do.call(tagList, image_output_list)
  })

  observe({
    if(is.null(input$files)) return(NULL)
    for (i in 1:nrow(files()))
    {
      print(i)
      local({
        my_i <- i
        imagename = paste0("image", my_i)
        print(imagename)
        output[[imagename]] <- 
          renderImage({
            list(src = files()$datapath[my_i],
                 alt = "Image failed to render")
          }, deleteFile = FALSE)
      })
    }
    ###########source code for k means clustering###########################################
    print("###############starting k clustering#######################")
    if(is.null(input$files)) return(NULL)
    infile <- input$files
    cat("the file path before change is" , infile$datapath, "\n")
    infilepath <- gsub("\\\\", "\\", infile$datapath)
    cat("the file path is" , infilepath, "\n")
    #cat("the old file path is" , files$datapath, "\n")


    library(jpeg)
    #img <- readJPEG("C:\\rtst\\ColorfulBird.jpg")
    #inFile$datapath
    #img <- readJPEG(infilepath)
    img <- readJPEG(infile$datapath)
    print("#############FILE READNG COMPLETED################")
    img_Dm <- dim(img)
    print("#############img_dm Completed################")

    # Lets assign RGB channels to a data frame
    img_RGB <- data.frame(
      x_axis = rep(1:img_Dm[2], each = img_Dm[1]),
      y_axis = rep(img_Dm[1]:1, img_Dm[2]),
      Red = as.vector(img[,,1]),
      Green = as.vector(img[,,2]),
      Blue = as.vector(img[,,3])
    )
    print("#############img rgb Completed################")
    library(ggplot2)

    ggplot(data = img_RGB, aes(x = x_axis, y = y_axis)) +
      geom_point(colour = rgb(img_RGB[c("Red", "Green", "Blue")])) +
      labs(title = "Original Image") +
      xlab("x-axis") +
      ylab("y-axis")

    wssplot <- function(data, nc=15, seed=1234){
      wss <- (nrow(data)-1)*sum(apply(data,2,var))
      for (i in 2:nc){
        set.seed(seed)
        wss[i] <- sum(kmeans(data, centers=i)$withinss)}
      plot(1:nc, wss, type="b", xlab="Number of Clusters",
           ylab="Within groups sum of squares")}

    wssplot(img_RGB[c(3,4,5)],25)

    #running the k-means algorithm

    k_cluster <- 3
    k_img_clstr <- kmeans(img_RGB[, c("Red", "Green", "Blue")],
                          centers = k_cluster)
    k_img_colors <- rgb(k_img_clstr$centers[k_img_clstr$cluster,])

    #plotting the compressed image
    print("#############starting plotting################")
    ggplot(data = img_RGB, aes(x = x_axis, y = y_axis)) +
      geom_point(colour = k_img_colors) +
      labs(title = paste("k-Means Clustering of", k_cluster, "Colours")) +
      xlab("x") +
      ylab("y")
    print("#############plotting completed started saving################")
    ggsave("C:\\rtst\\plot.png")

    print("#############saving Completed################")
    imagename = "plot,png"
    #print(imagename)
    output[[imagename]] <- 
      renderImage({
        list(src = "C:\\rtst\\plot.png",
             alt = "Image failed to render")
      }, deleteFile = FALSE)  
    print("#############Modified Image displayed################")  

  })



})

ui <- shinyUI(fluidPage(

  titlePanel("Uploading Files"),
  sidebarLayout(
    sidebarPanel(
      fileInput(inputId = 'files', 
                label = 'Select an Image',
                multiple = TRUE,
                accept=c('image/png', 'image/jpeg'))
    ),
    mainPanel(
      tableOutput('files'),
      uiOutput('images')

    )

  )
))

shinyApp(ui=ui,server=server)

标签: rk-means

解决方案


推荐阅读