基于数据框直接从R导出图像文件
Exporting image file direcly from R based on data frame
我在 R 中有以下数据框:
df <- data.frame(a = c(0, 0, 1, 1),
b = c(0, 1, 0, 1),
col = c("red", "green", "green", "yellow"))
我对导出光栅图像文件(png、tif 等)感兴趣,该文件将包含数据框中每个条目的一个像素,并具有适当的颜色。对于上面的示例,将有一个 2 x 2 的图像文件,如下所示:
我感觉 raster
包可能会有用,但据我所知,它只能导出地理空间光栅图像类型,不能导出普通图像。
这有效,使用 tiff
包:
library(tiff)
df <- data.frame(a = c(0, 0, 1, 1),
b = c(0, 1, 0, 1),
col = c("red", "green", "green", "yellow"))
mina <- min(df$a)
minb <- min(df$b)
maxa <- max(df$a)
maxb <- max(df$b)
colarray <- array(data = NA,
dim = c(maxb - minb + 1,
maxa - mina + 1,
3))
for (k in 1:nrow(df))
{
colarray[df[k, 2] - minb + 1,
df[k, 1] - mina + 1,
] <- col2rgb(df[k, 3]) / 255
}
writeTIFF(colarray, "res.tif", compression = "LZW")
它可能会更简洁一些,但对于 x&y 坐标不一定是 0 到 n 的情况,这种方法效果更好。
使用 png
等相关软件包,效果相同。
我在 R 中有以下数据框:
df <- data.frame(a = c(0, 0, 1, 1),
b = c(0, 1, 0, 1),
col = c("red", "green", "green", "yellow"))
我对导出光栅图像文件(png、tif 等)感兴趣,该文件将包含数据框中每个条目的一个像素,并具有适当的颜色。对于上面的示例,将有一个 2 x 2 的图像文件,如下所示:
我感觉 raster
包可能会有用,但据我所知,它只能导出地理空间光栅图像类型,不能导出普通图像。
这有效,使用 tiff
包:
library(tiff)
df <- data.frame(a = c(0, 0, 1, 1),
b = c(0, 1, 0, 1),
col = c("red", "green", "green", "yellow"))
mina <- min(df$a)
minb <- min(df$b)
maxa <- max(df$a)
maxb <- max(df$b)
colarray <- array(data = NA,
dim = c(maxb - minb + 1,
maxa - mina + 1,
3))
for (k in 1:nrow(df))
{
colarray[df[k, 2] - minb + 1,
df[k, 1] - mina + 1,
] <- col2rgb(df[k, 3]) / 255
}
writeTIFF(colarray, "res.tif", compression = "LZW")
它可能会更简洁一些,但对于 x&y 坐标不一定是 0 到 n 的情况,这种方法效果更好。
使用 png
等相关软件包,效果相同。