如何在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:
- A way to grab all image paths from your target folder
- A loop to process each image automatically
- 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
wandhparameters set the size of the local window used to calculate the threshold (great for images with uneven lighting) - Lower
offsetvalues 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
patternto\\.(PNG|JPG|JPEG)$ - The output subfolder keeps your original images completely safe—no accidental overwrites!
内容的提问来源于stack exchange,提问作者Maximus German
相关产品推荐
相关产品推荐

