如何在R语言中不使用raster scan库分割256*256图像为8×8块并保存
Hey there! Let's work through how to split your 256x256 image into 8x8 blocks and save each with its bottom-left coordinate as the filename—all without using the raster package. Here's a step-by-step solution using base R and basic image handling packages:
raster Package) First, we'll use the png package for reading/writing PNG images (swap to the jpeg package if your image is JPEG format). Install it if you haven't already with install.packages("png").
Step 1: Read Your Image
Start by loading the package and reading your 256x256 image:
library(png) # Replace with your actual image path img <- readPNG("your_256x256_image.png")
Step 2: Define Block Parameters
Since your image is 256x256 and we're splitting into 8x8 blocks, we'll have 32 blocks along both the x and y axes (256 ÷ 8 = 32). Let's define that upfront:
block_size <- 8 n_blocks <- 256 / block_size # Equals 32
Step 3: Loop Through Blocks & Save
The key thing to note here is that R's image matrices use the top-left corner as the origin, but you want the bottom-left to be (0,0). We'll adjust the row indices to flip the y-axis and match your coordinate system.
Here's the full loop:
for (y_block in 1:n_blocks) { for (x_block in 1:n_blocks) { # Calculate bottom-left coordinates for the block bottom_left_x <- (x_block - 1) * block_size bottom_left_y <- (y_block - 1) * block_size # Convert to R's image matrix indices (flip y-axis) start_row <- (n_blocks - y_block + 1) * block_size - block_size + 1 end_row <- (n_blocks - y_block + 1) * block_size start_col <- (x_block - 1) * block_size + 1 end_col <- x_block * block_size # Extract the 8x8 block from the image block <- img[start_row:end_row, start_col:end_col, , drop = FALSE] # Create filename with bottom-left coordinates filename <- sprintf("block_%d_%d.png", bottom_left_x, bottom_left_y) # Save the block to your working directory writePNG(block, filename) } }
Key Details to Note
- Coordinate Flip: The
start_rowcalculation reverses the y-block order so that the first iteration saves the bottom-left block (namedblock_0_0.png) instead of the top-left. - File Naming: Each file will follow the pattern
block_[x]_[y].png, wherexandyare the bottom-left coordinates of the 8x8 block. - Format Flexibility: If you're working with JPEGs, replace
readPNG()/writePNG()withreadJPEG()/writeJPEG()from thejpegpackage.
Test with a Sample Image
If you don't have a test image handy, you can generate a gradient image to test the code:
# Create a 256x256 gradient image test_img <- matrix(seq(0, 1, length.out = 256*256), nrow = 256, ncol = 256) writePNG(test_img, "test_gradient.png")
Run the splitting code on this test image, and you'll get 1024 (32x32) 8x8 blocks, each correctly labeled with their bottom-left coordinates.
内容的提问来源于stack exchange,提问作者vaibhav Mishra

