首页 > 解决方案 > 如何在 R 中生成每个像素都是随机颜色的图像?

问题描述

我想在 R 中创建一个由随机彩色像素组成的图像。我有一个输入向量

colors <- as.data.frame(cbind(
    R = sample(0:255, 100, replace = T),
    G = sample(0:255, 100, replace = T),
    B = sample(0:255, 100, replace = T)))

有 100 种随机生成的颜色。如何生成一个 10x10 像素的图像来引用我的颜色矢量?

标签: r

解决方案


我之前使用包解决了类似grid的问题(这是其他包(如 ggplot2 用于生成绘图的基本包))。

这是 R 中的一个非常低级的包,所以它有点像手工创建情节,但在我看来它很有趣。这是带有注释的代码

# This function creates a grid that is represented by the units from 0 to 1
# in "npc" units, which is "natural parent coordinate" units. Basically (0, 0)
# is bottom-left, (1, 1) is top right.
make_grid = function(rows, cols) {
  lines_rows = grid::unit((0:rows) / rows, "npc")
  lines_cols = grid::unit((0:cols) / cols, "npc")
  return(list("row" = lines_rows, "col" = lines_cols))
}
# Create a 8x8 grid, i.e. 64 rectangles (squares in this case).
rows = 8
cols = 8
g = make_grid(rows, cols)

# Compute the center of each square in the grid. 
# We will be placing squares of color on top of this centers.
centers_rows = g$row[-1] - grid::unit(1 / (rows * 2), "npc")
centers_cols = g$col[-1] - grid::unit(1 / (cols * 2), "npc")

# for example, x_coords[1], y_coords[1] is the center of the rectangle on the bottom-left
# 
x_coords = rep(centers_cols, each = rows)
y_coords = rep(centers_rows, cols)

# Generate the random colors. Each row represents a rectangle. 
# Columns are R, G and B.
colors = matrix(data = sample(0:255, rows * cols * 3), rows * cols, 3)

# Now plot it!
# Open a new graph device
grid::grid.newpage()

# Fill it with a white background.
grid::grid.rect(gp = grid::gpar(col = NULL, fill = "white"))

# Push an empty viewport, basically an area we can plot.
grid::pushViewport(grid::viewport())

# Iterate over the rows of the matrix of colors.
for (r in 1:(rows * cols)) {
  # The positions of each rectangle are given by x_coords and y_coords
  grid::grid.rect(
    x = x_coords[r],
    y = y_coords[r],
    height = grid::unit(1 / rows, "npc"),
    width = grid::unit(1 / cols, "npc"),
    # This is a gpar that has no border color and fill given by the RGB 
    # we sampled above. 
    # I'm adding an alpha level because it looks better in my opinion.
    gp = grid::gpar(
      col = NA,
      fill = rgb(colors[r, 1], colors[r, 2], colors[r, 3], alpha = 200, maxColorValue = 255)
    )
  )
}

你有这样的东西

更新我使用了 8x8 网格,但您可以毫无问题地使用 10x10 网格。


推荐阅读