R用户转Python:如何使用NumPy为固定高度的图像数组左右补零至3840*2160分辨率
Hey there! Let's sort out that padding problem you're facing. The issue with your current code is that np.pad applies padding to all sides when you pass a single value. Since you only want to add black borders to the left and right (keeping the height fixed at 2160), we need to explicitly tell NumPy where to apply the padding.
Step-by-Step Solution
Calculate the required padding
First, figure out how much total padding you need on the left and right combined. Your target width is 3840, so subtract your image's current width from that to get the total padding. Then split that total between left and right (we'll handle odd numbers by adding the extra pixel to one side).Use precise padding parameters with
np.pad
For 2D arrays (your images),pad_widthtakes a tuple where each element defines padding for a dimension:- The first element
(0, 0)means no padding on the top/bottom (height stays 2160) - The second element
(pad_left, pad_right)defines how many pixels to add to the left and right respectively.
- The first element
Example Code
import numpy as np # Example image array (height=2160, width=2000 as a sample) img_arr = np.random.randint(0, 255, size=(2160, 2000), dtype=np.uint8) target_width = 3840 current_height, current_width = img_arr.shape # Calculate total padding needed total_pad = target_width - current_width # Split padding between left and right (handle odd totals) pad_left = total_pad // 2 pad_right = total_pad - pad_left # Apply padding ONLY to left and right padded_img = np.pad( img_arr, pad_width=((0, 0), (pad_left, pad_right)), # No top/bottom padding mode='constant', constant_values=0 # Black color (0 for 8-bit images) ) # Verify the result print(f"Original shape: {img_arr.shape}") print(f"Padded shape: {padded_img.shape}") # Should be (2160, 3840)
Testing with Your Sample Array
If you want to test with your small sample array:
arr = np.array([[1,1,1],[1,1,1],[1,1,1],[1,1,1]]) target_width = 20 current_height, current_width = arr.shape total_pad = target_width - current_width pad_left = total_pad // 2 pad_right = total_pad - pad_left arr2 = np.pad(arr, pad_width=((0, 0), (pad_left, pad_right)), mode='constant', constant_values=0) print(arr2.shape) # Output: (4, 20) – only left/right have 0s, top/bottom unchanged
Why Your Original Code Didn't Work
Your original code np.pad(arr, FinalWidth/2, pad_with) applies FinalWidth/2 padding to both dimensions (rows and columns), which is why you got borders on all sides. By specifying pad_width=((0,0), (pad_left, pad_right)), we restrict padding to only the left and right of the width dimension.
内容的提问来源于stack exchange,提问作者Eischias

