如何在三维数据立方体中使用列表推导式进行值过滤?
Hey there! Let's figure out how to extend that list comprehension to handle your 3D image cube.
First, let's recap your working 2D code for a single image:
AM2 = [[x if x > 1e-5 else 0 for x in line] for line in AM[0]]
This iterates over each line in AM[0] (your first image), then each pixel value x in that line, replacing values below 1e-5 with 0.
For a 3D cube (where AM is a list of 2D images), you just need to add one more outer loop to iterate over each image in the cube. Here's the modified code:
AM_filtered = [[[x if x > 1e-5 else 0 for x in line] for line in image] for image in AM]
Let's break this down layer by layer:
- The outermost loop
for image in AMgoes through every 2D image in your 3D cube. - The middle loop
for line in imageprocesses each row (line) of the current image. - The innermost loop
for x in linechecks each pixel value, replacing it with 0 if it's ≤1e-5, otherwise keeping the original value.
Example to visualize the structure
Suppose your 3D cube AM looks like this (simplified with small values):
AM = [ [[0.0, 1.1e-5], [2.2e-5, 0.0]], # Image 1 [[3.3e-5, 0.0], [0.0, 4.4e-5]] # Image 2 ]
After applying the filtered list comprehension, AM_filtered would become:
[ [[0, 1.1e-5], [2.2e-5, 0]], # Image 1 (0s where values ≤1e-5) [[3.3e-5, 0], [0, 4.4e-5]] # Image 2 ]
Bonus: Faster alternative with NumPy (if applicable)
If you're working with large image datasets, list comprehensions can be slow. Using NumPy would make this operation much more efficient and concise:
import numpy as np AM_np = np.array(AM) AM_filtered_np = np.where(AM_np > 1e-5, AM_np, 0)
This vectorized operation does the same filtering in one line, and it's way faster for big 3D arrays.
Hope that solves your problem! 😊
内容的提问来源于stack exchange,提问作者Chicrala

