如何用Python去除已转为NumPy数组的灰度图像下方无用白色区域
Hey there! Let's fix those annoying blank white sections at the bottom of your images. Since you already have your grayscale images loaded as NumPy arrays, here's a straightforward, efficient approach using NumPy and OpenCV:
Step-by-Step Explanation
First, remember that in grayscale images, pure white is represented by the value 255. We'll identify rows that are entirely (or nearly) white, then crop the image to keep only the rows with actual content.
1. Define a Reusable Crop Function
Create a function to handle the cropping logic, including a tolerance parameter to account for minor gray noise that might be present in your "white" areas:
import numpy as np def crop_bottom_white(image, white_threshold=255, tolerance=0): # Check each row to see if all pixels are close enough to white # Adjust tolerance if your white areas have faint gray artifacts is_white_row = np.all(image >= (white_threshold - tolerance), axis=1) # Find the last row that isn't fully white non_white_rows = np.where(is_white_row == False)[0] if len(non_white_rows) == 0: # Edge case: entire image is white, return original to avoid errors return image last_valid_row = non_white_rows[-1] # Crop the image to keep everything up to (and including) that row return image[:last_valid_row + 1, :]
2. Integrate with Your Existing Code
Update your image loading loop to apply the cropping function to each image before adding it to your list:
import cv2 import glob data_dir = "/Users/leon/Projects/inpainting/data/" images = [] files = glob.glob(data_dir + "*.jpg") for file in files: # Load grayscale image image = cv2.imread(file, 0) # Crop the bottom white area - adjust tolerance if needed (e.g., 5 for minor noise) cropped_image = crop_bottom_white(image, tolerance=5) images.append(cropped_image)
Key Notes
- Tolerance Adjustment: If your "white" areas aren't perfectly
255(e.g., have faint gray artifacts), increase thetolerancevalue (try 5-10) to ensure those rows are still recognized as blank. - Edge Cases: The function handles images that are entirely white by returning the original image, so you won't run into index errors.
- Efficiency: Using NumPy's vectorized operations makes this much faster than looping through each row manually, which is crucial if you have a large batch of images.
内容的提问来源于stack exchange,提问作者Hao Chen

