You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否在R中“暴力拼接”位图区域?可结合Python实现吗?

解决方案

纯R实现(使用magick包)

直接用R的magick包就能完成图像截取与拼接,无需额外工具:

  1. 安装并加载依赖包:
install.packages("magick")
library(magick)
  1. 读取已生成的两张位图:
graph1 <- image_read("graph1.png")
graph2 <- image_read("graph2.png")
  1. 截取graph2底部79像素的图例区域:
# 获取graph2的尺寸参数
graph2_dim <- image_info(graph2)
# 计算截取起始y坐标(总高度减去79)
crop_start_y <- graph2_dim$height - 79
# 执行裁剪,格式为「宽度x高度+起始x+起始y」,x从0开始,宽度沿用原图宽度
legend_crop <- image_crop(graph2, paste0(graph2_dim$width, "x79+0+", crop_start_y))
  1. 垂直拼接graph1和截取的图例:
# stack=TRUE表示垂直拼接,FALSE为水平拼接
final_plot <- image_append(c(graph1, legend_crop), stack = TRUE)
# 保存拼接后的图像
image_write(final_plot, "combined_plot.png", format = "png")

R集成Python代码实现(使用reticulate调用Pillow)

如果更熟悉Python的Pillow库,可以用reticulate在R脚本中嵌入Python代码完成操作:

  1. 安装并加载reticulate包:
install.packages("reticulate")
library(reticulate)
  1. 确保Python环境已安装Pillow(若未安装,执行以下命令):
py_install("Pillow")
  1. 嵌入Python代码完成图像处理:
py_run_string("
from PIL import Image

# 读取两张位图
img1 = Image.open('graph1.png')
img2 = Image.open('graph2.png')

# 截取img2底部79像素区域
width, height = img2.size
legend_part = img2.crop((0, height - 79, width, height))

# 创建空白画布,高度为两张图的高度之和
new_img = Image.new('RGB', (img1.width, img1.height + legend_part.height), 'white')
# 分别粘贴原图和图例
new_img.paste(img1, (0, 0))
new_img.paste(legend_part, (0, img1.height))

# 保存最终图像
new_img.save('combined_plot.png')
")

内容的提问来源于stack exchange,提问作者vlangen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 05:43:20