R语言 copy:尝试将一批图像复制到不同的文件夹中

wwtsj6pe  于 2023-06-27  发布在  其他
关注(0)|答案(1)|浏览(89)

我目前正试图写一个代码,将读取通过文件列表,确认它是一个图像,然后将此文件复制到其适当的IMG文件夹。目录的设置当前按月将图像放在一个文件夹中,在此目录中是松散的图像,沿着使用phenopix的structureFolder函数设置的其他4个文件夹。
我目前使用for循环,并检查(使用stringr包)图像的名称是否包含'. jpg',如果为True,我希望将此文件复制到使用structureFolder包创建的IMG文件夹中,这是(我假设)该特定目录的文件夹路径的快捷方式。我不知道我做错了什么,但我知道if语句工作正常,因为我已经使用简单的print语句测试过了,只是文件.copy没有被正确读取。任何帮助都非常感谢!

# here is what I have currently
wd <- "~/Desktop/codes/phenocam/DSM/2023/02"
> wd <- "~/Desktop/codes/phenocam/DSM/2023/02"

files <- list.files(wd)
print(files)
> files <- list.files(wd)
> print(files)
   [1] "2023-02-01_10_30_00.jpg" "2023-02-01_11_00_00.jpg"
   [3] "2023-02-01_11_30_00.jpg" "2023-02-01_12_00_00.jpg"
   [5] "2023-02-01_12_30_00.jpg" "2023-02-01_13_00_00.jpg"
# ommitted the majority of file names since it is repetitive

my_path = structureFolder(wd, showWarnings = F)
> my_path = structureFolder(wd, showWarnings = F)
Put all your images in ~/Desktop/codes/phenocam/DSM/2023/02/IMG/ 
Put your reference image in ~/Desktop/codes/phenocam/DSM/2023/02/REF/ 
Draw your ROI with DrawROI():
 set path_img_ref to  ~/Desktop/codes/phenocam/DSM/2023/02/REF/ 
 set path_ROIs to ~/Desktop/codes/phenocam/DSM/2023/02/ROI/ 
Then you can extractVIs(): 
 set img.path as ~/Desktop/codes/phenocam/DSM/2023/02/IMG/ 
 set roi.path as ~/Desktop/codes/phenocam/DSM/2023/02/ROI/ 
 set vi.path to ~/Desktop/codes/phenocam/DSM/2023/02/VI/ 
------------------------
Alternatively, assign this function to an object and use named elements of the returned list

for (file in files) {
  if (stringr::str_detect(file, '.jpg')) {
    file.copy(from = wd, to = my_path$img)
  }
}

在for循环之后没有输出,并且检查IMG文件夹显示没有图像被复制。再次,任何帮助是非常感谢(也任何建议,使它有点简单,因为我是一个新的(ish)编码器!Thanks:)

hsgswve4

hsgswve41#

欢迎。请提供可复制的例子,因为这对任何想帮助你的人都有帮助。
我希望我没有得到这个完美的,但你应该能够从这里建立使用这个例子。

# Create list of files and path, include recursive = TRUE only if you want to search sub-directories; use "pattern" to filter to only image files
my_files <- as_tibble(list.files(recursive = TRUE, full.names = TRUE, pattern = "jpg")) %>%
# this column brings in only the file name (assuming no sub-folders)
  cbind(as_tibble(list.files(recursive = TRUE, full.names = FALSE, pattern = "jpg")))

# rename columns
colnames(my_files) <- c("full_path_name", "file_name")
 
# create lists of each name
my_files_full_path_name <- unlist(my_files$full_path_name)
my_files_short_name <- unlist(my_files$file_name)

# copy jpeg files to my IMG file
file.copy(from = my_files_full_path_name,
          to   = paste("IMG/",my_files_short_name),
          overwrite = TRUE, recursive = FALSE, copy.mode = TRUE)

记住,list.files和file.copy是向量化函数,所以不需要循环。
希望这能帮上忙。

相关问题