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

如何在R中编写函数批量将文件夹内图片转为黑白并保存?

Hey there! Let's get your batch image processing workflow sorted out—handling 600+ images one by one is no fun, so we'll expand your code to automate the whole process, including saving the grayscale (or true black-and-white) results to a dedicated folder.

First, Let's Break Down the Fixes

Your existing code works great for single images, but we need to add three key pieces to scale it up:

  1. A way to grab all image paths from your target folder
  2. A loop to process each image automatically
  3. A step to save processed images without overwriting your originals

Full Batch Processing Code (Grayscale Conversion)

Here's a ready-to-use script that handles everything end-to-end:

library("EBImage")

# Define your input/output folders
input_folder <- "C:\\Users\\Max Aleman\\Desktop\\Cotonesterlder - Copy"
output_folder <- file.path(input_folder, "Processed_Grayscale") # Creates a subfolder for results

# Create output folder if it doesn't exist yet
if (!dir.exists(output_folder)) {
  dir.create(output_folder)
}

# Get all PNG images in the input folder (matches both .PNG and .png)
image_paths <- list.files(
  path = input_folder,
  pattern = "\\.PNG$",
  full.names = TRUE,
  ignore.case = TRUE
)

# Loop through each image to process and save
for (img_path in image_paths) {
  # Read the original image
  orig <- readImage(img_path)
  
  # Convert to grayscale
  gray_img <- orig
  colorMode(gray_img) <- Grayscale
  
  # Generate output path (keeps original filename)
  img_filename <- basename(img_path)
  output_path <- file.path(output_folder, img_filename)
  
  # Save the processed image
  writeImage(gray_img, output_path, type = "PNG")
  
  # Optional: Print progress to track where you are
  cat("Finished processing:", img_filename, "\n")
}

If You Need True Binary (Black & White, No Grays)

If you meant full black-and-white (no gray gradients) instead of grayscale, add a thresholding step right after converting to grayscale. Adjust the offset value (0-1) to tweak how strict the binary cutoff is:

# Inside the loop, after converting to grayscale:
binary_img <- threshold(gray_img, w = 10, h = 10, offset = 0.05)
# Then save binary_img instead of gray_img
writeImage(binary_img, output_path, type = "PNG")
  • The w and h parameters set the size of the local window used to calculate the threshold (great for images with uneven lighting)
  • Lower offset values mean more pixels turn white; higher values mean more turn black

Quick Tips to Avoid Headaches

  • If you haven't installed EBImage yet, run install.packages("EBImage") first
  • To include other image formats (like JPG), update the pattern to \\.(PNG|JPG|JPEG)$
  • The output subfolder keeps your original images completely safe—no accidental overwrites!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:51:35