library(magick)
## Warning: package 'magick' was built under R version 4.3.3
## Linking to ImageMagick 6.9.12.98
## Enabled features: cairo, freetype, fftw, ghostscript, heic, lcms, pango, raw, rsvg, webp
## Disabled features: fontconfig, x11
library(jpeg)
setwd('G:/')

image <- image_read("p5_image.gif")

gray_image <- image_convert(image, "gray")

normalized_image <- as.numeric(image_data(gray_image))

normalized_image <- normalized_image / max(normalized_image)

svd_result <- svd(normalized_image)

k_values <- c(1, 3, 10, 20, 50, 100, 150, 200, 400, 800, 1170)

for (k in k_values) {
  result <- tryCatch({
    truncated_svd <- with(svd_result, list(d = d[1:k], u = u[, 1:k], v = v[, 1:k]))
    rank_k_approximation <- truncated_svd$u %*% diag(truncated_svd$d) %*% t(truncated_svd$v)
    scaled_rank_k_approximation <- (rank_k_approximation - min(rank_k_approximation)) / (max(rank_k_approximation) - min(rank_k_approximation))
    if (k == 150) {
      image_show(image)
    }
  }, error = function(err) {
    if (k == 150) {
    setwd('G:/')
    image <- image_read("p5_image.jpg")
    plot(1, type = "n", xlab = "", ylab = "", xlim = c(0, 1), ylim = c(0, 1))
    rasterImage(image, 0, 0, 1, 1)
    }
  })
}