In Python, CVB provides a convenient way to access pixel data by either mapping an image to a NumPy array (if possible) or copying it. The pixel values of the NumPy array can be accessed through np_array[row, col, plane]
.
There are two ways to obtain the NumPy array and modify its pixel values, depending on the underlying memory layout:
with
statement for all objects that hold resources with critical lifetimes, such as devices and images, to ensure proper resource management.Additionally to the code in this section, a sample program can be found in the CVB installation under %cvb%Tutorial\Image Manager\CVBpy\ImagePixelAccess
. Alternatively, the example can be accessed via the following link: ImagePixelAccess
Mapping an image to a NumPy array allows direct access to pixel data without creating a copy, making it an efficient approach whenever supported.
The following example demonstrates how to map an RGB image to a NumPy array:
(1) An RGB 8-bit unsigned image is created. The with
statement should be used to manage the image's lifetime automatically.
(2) The image is mapped to a NumPy array without copying, allowing direct access to pixel data.
(3) Check whether the mapping was successful; if OWNDATA
is True
, the image could not be mapped. In this case, the image has to be copied by setting copy=True
in previous call (see the next example).
(4) Modify all pixel values in the NumPy array, which directly updates the underlying image data.
(5) Save the modified image to a file.
Whenever mapping the image is not possible, it must be copied instead. Note, when copying an image to a NumPy array, the pixel data is duplicated, meaning modifications to the NumPy array do not affect the original image data. To continue processing the modified image, the NumPy array can be mapped to a cvb.WrappedImage.
(1) Copy the image data to a new NumPy array, being aware that modifications do not affect the original image.
(2) Modify the copied NumPy array; since the image was copied, the original data remains unchanged.
(3) Map the NumPy array to a cvb.WrappedImage without copying. Use cvb.BufferLayout.HeightWidthPlane as the layout for NumPy arrays. The with
statement should be used for lifetime management.
(4) Save the modified image to a file.