对图片进行裁剪 / 批量裁剪
示例如图
![在这里插入图片描述](https://img-blog.csdnimg.cn/8de1cf619d18459091647d823afe0856.png#pic_center)
# 对图片进行裁剪
library(magick)
pic <- image_read('study.jpg')
plot(pic)
print(pic)
image_info(pic)
# 500x300+10+20" –
# Crop image to 500 by 300 at position 10,20
# 后面的参数选择可以在Windows系统自带的画图软件截取计算
# 原始图片大小
width=image_info(pic)[2];height=image_info(pic)[3]
widthRange=158 # 截图的矩形框直接大小
heightRange=115
# 截取范围的起始 鼠标放在看【像素】
widthBegin=163
heightBegin=118
geometry=paste0(widthRange,"x",heightRange,
"+",widthBegin,"+",heightBegin)
# geometry = "widthRange x heightRange+widthBegin + heightBegin "
pic2=image_crop(pic,geometry = geometry)
plot(pic2)
# 图片保存
image_write(image = pic2,"pic2.jpg" )
#循环批量处理
lf <-list.files(pattern = "study")
(files <- gsub("", "", lf)) # 是否需要敏感字符替换处理
# 批量读取
piclist=lapply(files, function(x) {image_read(x)})
# 裁剪
piclist2=lapply(piclist, function(x){image_crop(x,geometry = geometry)})
# 保存
for (i in 1:length(piclist2)){
image_write(image = piclist2[[i]],paste0("pic",i,".jpg"))
}