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

使用R语言EBImage库批量读取图片并生成像素数组DataFrame

Hey there! Let's break down what's going on here and fix your problem step by step. First, the error you're getting makes total sense—readImage() expects a single image file path, not a folder. Let's tackle your three requirements one by one:


1. Batch Read All Images in the Folder

First, we need to grab all valid image file paths from your folder, then read them one by one:

library(EBImage)

# Define your target folder path
img_folder <- "C:/Users/admin/Downloads/mypicture"

# Get full paths of all common image files (add formats like tiff if needed)
img_paths <- list.files(
  path = img_folder,
  pattern = "\\.(jpg|jpeg|png|bmp)$",  # Match standard image extensions
  full.names = TRUE,                   # Return complete file paths
  ignore.case = TRUE                   # Handle both uppercase/lowercase extensions
)

# Batch read images into a named list (names are the image filenames)
img_list <- lapply(img_paths, readImage)
names(img_list) <- basename(img_paths)  # Assign filenames as list names for easy tracking

2. Resize All Images

You can use either fixed dimensions or proportional scaling—here's how to do both:

Option 1: Fixed Width & Height

# Resize all images to 200px wide and 100px tall
resized_fixed <- lapply(img_list, resize, w = 200, h = 100)

Option 2: Proportional Scaling

# Resize all images to 50% of their original height (adjust ratio as needed)
resized_proportional <- lapply(img_list, function(img) {
  # dim(img)[1] = image height, dim(img)[2] = image width
  resize(img, dim(img)[1] / 2)
})

3. Extract Pixel Arrays & Build a Filename-Labeled DataFrame

We'll convert each image's pixel data into a tabular format, then add the image filename as a column:

# Helper function to process a single image into a DataFrame
img_to_pixel_df <- function(img, img_name) {
  # Convert pixel array to table format
  pixel_table <- as.table(img)
  pixel_df <- as.data.frame(pixel_table)
  
  # Rename columns based on image type (grayscale vs color)
  if (length(dim(img)) == 2) {
    # Grayscale image: rows, columns, intensity
    colnames(pixel_df) <- c("Y_Pixel", "X_Pixel", "Intensity")
  } else {
    # Color image: rows, columns, color channel, intensity
    colnames(pixel_df) <- c("Y_Pixel", "X_Pixel", "Channel", "Intensity")
  }
  
  # Add the image filename column
  pixel_df$Image_Name <- img_name
  return(pixel_df)
}

# Process all resized images (use resized_fixed or resized_proportional)
all_pixel_dfs <- mapply(
  img_to_pixel_df,
  resized_fixed,
  names(resized_fixed),
  SIMPLIFY = FALSE
)

# Combine all individual DataFrames into one final table
final_pixel_df <- do.call(rbind, all_pixel_dfs)

# Preview the result
head(final_pixel_df)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 03:46:20