liveBook · Manning

Data conversion

As explained in Fast Python: High performance techniques for large datasets

Data conversion is the transformation of a value or data from one type, format, or representation to another, explicitly or implicitly.

In image-array arithmetic, converting pixel data to a wider type before a transformation can prevent 8-bit unsigned integer overflow. Convert back only after limiting values to the valid pixel range. section 4.2.3

Brightening an image

Doubling 8-bit pixel values can overflow without an obvious visual warning. Widen the array, multiply, cap values at 255, and cast back to uint8. section 4.2.3

brighter3_arr = image_arr.astype(np.uint16)
brighter3_arr = brighter3_arr * 2
print(brighter3_arr.max(), brighter3_arr.dtype)
brighter3_arr = np.minimum(brighter3_arr, 255)   #1
print(brighter3_arr.max(), brighter3_arr.dtype)
brighter3_arr = brighter3_arr.astype(np.uint8)
print(brighter3_arr.max(), brighter3_arr.dtype)
Image.fromarray(brighter3_arr).save("brighter3.png")

The sequence widens pixel values to uint16, doubles them, clips them to 255, then converts them back to uint8. section 4.2.3

How Fast Python: High performance techniques for large datasets covers it

How deep it goes
Demonstrates widening, clipping, and recasting through a worked pixel-brightening operation.
Examples
Uses grayscale image pixels, comparing addition and doubling before widening, clipping, and recasting.
What it assumes
Assumes familiarity with NumPy arrays and 8-bit unsigned pixel values rather than teaching them from zero.
What you can do after
Apply NumPy dtype widening, clipping, and recasting to preserve intended pixel values during brightness changes.
How it connects
Connects NumPy dtype conversion with unsigned integers, overflow, and image processing.

Also explained in

Compare how 21 books explain data conversion →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Fast Python: High performance techniques for large datasets. The section links point to the parts of the book it draws on.