Parallel Image Pipeline Without External Libraries
Arrays & HashingModel answerLast updated
Build a CPU-based image transformation engine that chains grayscale, brightness, and resize operations across multiple images using pure Python.
Problem
You will implement an in-memory image transformation system using only Python standard library features—no OpenCV, PIL, or NumPy. Images are represented as three-dimensional nested lists with shape (height, width, 3), where each pixel holds [R, G, B] integer values in the range [0, 255].
Your BatchImageProcessor class must support three core transformations and a batch execution method:
1. to_grayscale(image)
Convert an RGB image to grayscale while preserving the three-channel structure. Output a pixel with three identical channels [Y, Y, Y], where luminance Y is computed as:
Y = int(0.299 × R + 0.587 × G + 0.114 × B)
2. adjust_brightness(image, factor)
Scale every RGB channel by the given floating-point factor, then clamp results to [0, 255]. Convert scaled values to integers by truncation.
3. resize(image, new_h, new_w)
Resize an image using nearest-neighbor interpolation. Map each output coordinate (r, c) to the source coordinate:
source_row = int(r × original_height / new_h)
source_col = int(c × original_width / new_w)
4. process_batch(images, pipeline, max_workers)
Apply a sequence of transformations to a list of images. The pipeline parameter is a list of tuples describing operations:
("grayscale",)— convert to grayscale("brightness", factor)— adjust brightness by factor("resize", new_h, new_w)— resize to new dimensions
When max_workers > 1, parallelize processing across images.
Interface
class BatchImageProcessor:
@staticmethod
def to_grayscale(image: list[list[list[int]]]) -> list[list[list[int]]]:
pass
@staticmethod
def adjust_brightness(image: list[list[list[int]]], factor: float) -> list[list[list[int]]]:
pass
@staticmethod
def resize(image: list[list[list[int]]], new_h: int, new_w: int) -> list[list[list[int]]]:
pass
def process_batch(
self,
images: list[list[list[list[int]]]],
pipeline: list[tuple],
max_workers: int = 1
) -> list[list[list[list[int]]]]:
pass
Example Usage
processor = BatchImageProcessor()
# 2×2 RGB image
img = [
[[100, 150, 200], [50, 50, 50]],
[[0, 255, 0], [255, 255, 255]]
]
# Scale brightness by 1.5
bright = processor.adjust_brightness(img, 1.5)
# Top-left: [150, 225, 255] (200×1.5=300 clamped to 255)
# Shrink to 1×1
tiny = processor.resize(img, 1, 1)
# Result: [[[100, 150, 200]]]
# Chain operations
batch = [img]
pipeline = [("brightness", 0.8), ("grayscale",), ("resize", 4, 4)]
result = processor.process_batch(batch, pipeline, max_workers=2)
Constraints
1 ≤ height, width ≤ 20001 ≤ batch size ≤ 100factor ≥ 0.0new_h, new_w ≥ 1- All input images have valid RGB pixel data
Hints
Hint 1
Each transformation is independent—treat them as pure functions that build new images without mutating inputs
Hint 2
Images in a batch are completely independent, making this an embarrassingly parallel problem suitable for multiprocessing
Hint 3
Use integer division for resize mapping to avoid floating-point precision issues that could cause out-of-bounds access
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Each transformation is a pure function that scans pixels and produces a new image:
Grayscale applies the standard luminance formula to each pixel and replicates the result across all three channels, maintaining the (H, W, 3) shape for pipeline compatibility.
Brightness adjustment multiplies each channel by the scaling factor, truncates to an integer, then clamps to the valid [0, 255] range. The order matters: scale first, convert to int, then clamp.
Resize uses nearest-neighbor sampling. For each target coordinate (r, c), compute the source coordinate using integer division: source_r = r * orig_h // new_h. This avoids floating-point arithmetic that could yield values like 2.999999 and cause off-by-one errors.
A pipeline is a sequential composition of these operations applied to a single image. The batch runner applies the entire pipeline to each image independently. Since images don't depend on each other, we can process them in parallel using ProcessPoolExecutor. We use processes rather than threads because Python's GIL prevents true parallelism for CPU-bound pixel operations.
Implementation
from concurrent.futures import ProcessPoolExecutor
class BatchImageProcessor:
@staticmethod
def to_grayscale(image: list[list[list[int]]]) -> list[list[list[int]]]:
result = []
for row in image:
new_row = []
for r, g, b in row:
y = int(0.299 * r + 0.587 * g + 0.114 * b)
new_row.append([y, y, y])
result.append(new_row)
return result
@staticmethod
def adjust_brightness(image: list[list[list[int]]], factor: float) -> list[list[list[int]]]:
def clamp_scale(val: int) -> int:
scaled = int(val * factor)
if scaled < 0:
return 0
if scaled > 255:
return 255
return scaled
return [[[clamp_scale(channel) for channel in pixel]
for pixel in row]
for row in image]
@staticmethod
def resize(image: list[list[list[int]]], new_h: int, new_w: int) -> list[list[list[int]]]:
if new_h < 1 or new_w < 1:
raise ValueError("Dimensions must be >= 1")
orig_h = len(image)
orig_w = len(image[0])
# Pre-compute column mapping to avoid redundant calculation
col_indices = [c * orig_w // new_w for c in range(new_w)]
result = []
for r in range(new_h):
source_row_idx = r * orig_h // new_h
source_row = image[source_row_idx]
new_row = [list(source_row[col_idx]) for col_idx in col_indices]
result.append(new_row)
return result
def process_batch(
self,
images: list[list[list[list[int]]]],
pipeline: list[tuple],
max_workers: int = 1,
) -> list[list[list[list[int]]]]:
if not images:
return []
_validate_pipeline(pipeline)
# Sequential execution for small batches or single worker
if max_workers <= 1 or len(images) == 1:
return [_execute_pipeline(img, pipeline) for img in images]
# Parallel execution
worker_count = min(max_workers, len(images))
chunk_size = max(1, len(images) // (worker_count * 4))
with ProcessPoolExecutor(max_workers=worker_count) as executor:
results = executor.map(
_execute_pipeline,
images,
[pipeline] * len(images),
chunksize=chunk_size
)
return list(results)
# Module-level helpers for pickling compatibility
_OPERATION_ARITY = {"grayscale": 0, "brightness": 1, "resize": 2}
def _validate_pipeline(pipeline: list[tuple]) -> None:
for step in pipeline:
if not step:
raise ValueError(f"Empty pipeline step")
op_name = step[0]
if op_name not in _OPERATION_ARITY:
raise ValueError(f"Unknown operation: {op_name}")
expected_args = _OPERATION_ARITY[op_name]
actual_args = len(step) - 1
if actual_args != expected_args:
raise ValueError(
f"{op_name} expects {expected_args} args, got {actual_args}"
)
def _execute_pipeline(image, pipeline):
"""Apply pipeline steps sequentially. Must be module-level for pickling."""
current = image
for step in pipeline:
op_name = step[0]
if op_name == "grayscale":
current = BatchImageProcessor.to_grayscale(current)
elif op_name == "brightness":
current = BatchImageProcessor.adjust_brightness(current, step[1])
elif op_name == "resize":
current = BatchImageProcessor.resize(current, step[1], step[2])
return current
Complexity
Let N = number of images, H × W = average image dimensions, P = pipeline length.
- Time: O(N × P × H × W) total work, divided roughly by
max_workerswhen parallel - Space: O(N × H × W) for output storage; each worker holds one intermediate image
Individual operations:
to_grayscale: O(H × W) time, O(H × W) spaceadjust_brightness: O(H × W) time, O(H × W) spaceresize(new_h, new_w): O(new_h × new_w) time and space
Edge Cases
Empty batch: Return empty list immediately without starting a process pool.
Single worker or single image: Execute sequentially to avoid multiprocessing overhead—pickling nested lists is expensive.
Factor edge cases: factor=0 produces a black image; factor=1.0 creates an identical copy.
Resize to same dimensions: Produces a deep copy. Resize to 1×1: Samples only pixel (0, 0).
Invalid pipeline: Validation catches unknown operations or incorrect argument counts before processing begins.
Pickling constraint: The pipeline executor must be a module-level function. Lambdas and closures cannot be pickled for ProcessPoolExecutor. On spawn-based platforms (macOS, Windows), guard execution with if __name__ == "__main__":.
Common Mistakes
-
Floating-point resize coordinates: Using
int(r * orig_h / new_h)risks precision issues. Integer divisionr * orig_h // new_his exact and safer. -
Mutating input: Modifying pixel lists in place corrupts the input when the same image object appears multiple times.
-
Wrong clamp order: Clamping before scaling
brightness * min(val, 255)gives incorrect results. Scale first, then clamp. -
Thread pool instead of process pool: Python's GIL prevents threads from running pure-Python loops in parallel. Processes are required for speedup on CPU-bound work.
-
Grayscale shape change: Dropping to a single-channel output breaks downstream operations that expect three channels.