缩放R图像

Rob*_*ers 3 r image scale

我想在R中缩放图像以进行进一步分析,而不是立即绘图.

如果我可以使用EBImage,EBImage的resize()将是理想的,但我需要避免它,所以我必须找到一个替代方案.

我没有任何运气搜索.我可以手工实现双线性过滤,但在此之前,我想确认没有任何替代方案.

by0*_*by0 5

最近邻居调整大小是最常见和最简单的实现.

假设您的图像是一个图层/通道,因此是一个矩阵:

resizePixels = function(im, w, h) {
  pixels = as.vector(im)
  # initial width/height
  w1 = nrow(im)
  h1 = ncol(im)
  # target width/height
  w2 = w
  h2 = h
  # Create empty vector
  temp = vector('numeric', w2*h2)
  # Compute ratios
  x_ratio = w1/w2
  y_ratio = h1/h2
  # Do resizing
  for (i in 0:(h2-1)) {
    for (j in 0:(w2-1)) {
      px = floor(j*x_ratio)
      py = floor(i*y_ratio)
      temp[(i*w2)+j] = pixels[(py*w1)+px]
    }
  }

  m = matrix(temp, h2, w2)
  return(m)
}

我会让你弄清楚如何将它应用于RGB图像

以下是此图像红色通道上的代码测试运行:

lena = readImage('~/Desktop/lena.jpg')[,,1]
display(lena)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

r = resizePixels(lena, 150, 150)
display(r)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

r2 = resizePixels(lena, 50, 50)
display(r2)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

注意:

  1. 请注意,目标宽度和高度必须保持原始图像的纵横比,否则它将无法工作
  2. 如果你想避免EBImage,读/写图像尝试包jpeg方法readJPEGwriteJPEG