mapteksdk.data.images module
Image data objects.
Image objects are used to apply complicated textures to other objects.
- class Raster(object_id=None, lock_type=LockType.READWRITE, width=None, height=None, *, image=None)
Bases:
DataObject
Class representing raster images which can be draped onto other objects.
Topology objects which support raster association possess an associate_raster function which accepts a Raster and a RasterRegistration object which allows the raster to be draped onto that object.
- Parameters:
width (Optional[int]) – The width of the raster.
height (Optional[int]) – The height of the raster.
image (Optional[str | Image.Image | pathlib.Path]) – The path to an image file. The image will be opened using pillow and used to populate the pixels, width and height of the raster. Alternatively, this can be a PIL.Image.Image object which will be used to populate the pixels, width and height of the raster. If this argument is specified also specifying the width and height arguments will raise an error.
lock_type (LockType) –
- Raises:
TypeError – If image is not a string, pathlib.Path or Pil.Image.Image.
ValueError – If image is specified and width or height is specified.
FileNotFoundError – If image is the path to a non-existent file.
PIL.UnidentifiedImageError – If image is the path to a file which pillow does not recognise as an image.
PIL.DecompressionBombError – If image is the path to an image file which seems to be a “decompression bomb” - a maliciously crafted file intended to crash or otherwise disrupt the application when it is imported.
Notes
This object provides a consistent interface to the pixels of the raster image regardless of the underlying format. If the underlying format is JPEG or another format which does not support alpha, the alpha will always be read as 255 and any changes to the alpha components will be ignored.
See also
mapteksdk.data.facets.Surface.associate_raster
associate a raster with a surface.
- raster
Help page for this class.
Examples
Create a Raster sourcing the dimensions and pixels of the raster from a file called image.png.
>>> from mapteksdk.project import Project >>> from mapteksdk.data import Raster >>> project = Project() >>> # Raster typically have a path of None because they are associated >>> # with other objects. >>> with project.new(None, Raster(image="path/to/image.jpg")) as raster: ... # Perform operations on the raster here and associate it with ... # an object. ... pass
- classmethod static_type()
Return the type of raster as stored in a Project.
This can be used for determining if the type of an object is a raster.
- Return type:
int
- property id: ObjectID[Raster]
Object ID that uniquely references this object in the project.
- Returns:
The unique id of this object.
- Return type:
- property width: int
The width of the raster. This is the number of pixels in each row.
- property height: int
The height of the raster. This is the number of pixels in each column.
- resize(new_width, new_height, resize_image=True)
Resizes the raster to the new width and height.
- Parameters:
new_width (int) – The new width for the raster. Pass None to keep the width unchanged.
new_height (int) – The new height for the raster. Pass None to keep the height unchanged.
resize_image (bool) – If True (default) The raster will be resized to fill the new size using a simple nearest neighbour search if the size is reduced, or simple bilinear interpolation. This will also change the format to JPEG (and hence the alpha component of the pixels will be discarded). If False, the current pixels are discarded and replaced with transparent white (or white if the format does not support transparency). This will not change the underlying format.
- Raises:
TypeError – If width or height cannot be converted to an integer.
ValueError – If width or height is less than one.
RuntimeError – If called when creating a new raster.
Warning
After calling resize with resize_image=True it is an error to access pixels or pixels_2d until the object is closed and reopened.
Examples
Halve the size of all rasters on an object. Note that because resize_image is true, the existing pixels will be changed to make a smaller version of the image.
>>> from mapteksdk.project import Project >>> project = Project() >>> with project.read("surfaces/target") as read_object: >>> for raster in read_object.rasters.values(): ... with project.edit(raster) as edit_raster: ... edit_raster.resize(edit_raster.width // 2, ... edit_raster.height // 2, ... resize_image=True)
- property pixel_count: int
The total number of pixels in the raster.
- property pixels: numpy.ndarray
The pixels of the raster.
This pixels are represented as a numpy array of shape (pixel_count, 4) where each row is the colour of a pixel in the form: [Red, Green, Blue, Alpha].
See pixels_2d for the pixels reshaped to match the width and height of the raster.
- Raises:
RuntimeError – If accessed after calling resize with resize_image = True.
Examples
Accessing the pixels via this function is best when the two dimensional nature of the raster is not relevant or useful. The below example shows removing the green component from all of the pixels in an raster. Has no effect if the object at surfaces/target does not have an associated raster.
>>> from mapteksdk.project import Project >>> project = Project() >>> with project.read("surfaces/target") as read_object: >>> for raster in read_object.rasters.values(): ... with project.edit(raster) as edit_raster: ... edit_raster.pixels[:, 1] = 0
- property pixels_2d: numpy.ndarray
The pixels reshaped to match the width and height of the raster.
pixels_2d[0][0] is the colour of the pixel in the bottom left hand corner of the raster. pixels_2d[i][j] is the colour of the pixel i pixels to the right of the bottom left hand corner and j pixels above the bottom left hand corner.
The returned array will have shape (height, width, 4).
- Raises:
ValueError – If set using a string which cannot be converted to an integer.
ValueError – If set to a value which cannot be broadcast to the right shape.
TypeError – If set to a value which cannot be converted to an integer.
Notes
This returns the pixels in an ideal format to be passed to the raster.fromarray function in the 3rd party pillow library.
Examples
As pixels_2d allows access to the two dimensional nature of the raster, it can allow different transformations to be applied to different parts of the raster. The example below performs a different transformation to each quarter of the raster. Has no effect if the object at surfaces/target has no associated rasters.
>>> from mapteksdk.project import Project >>> project = Project() >>> with project.read("surfaces/target") as read_object: ... for raster in read_object.rasters.values(): ... with project.edit(raster) as edit_raster: ... width = edit_raster.width ... height = edit_raster.height ... half_width = edit_raster.width // 2 ... half_height = edit_raster.height // 2 ... # Remove red from the bottom left hand corner. ... edit_raster.pixels_2d[0:half_height, 0:half_width, 0] = 0 ... # Remove green from the top left hand corner. ... edit_raster.pixels_2d[half_height:height, ... 0:half_width, 1] = 0 ... # Remove blue from the bottom right hand corner. ... edit_raster.pixels_2d[0:half_height, ... half_width:width, 2] = 0 ... # Maximizes the red component in the top right hand corner. ... edit_raster.pixels_2d[half_height:height, ... half_width:width, 0] = 255
- property title: str
The title of the raster.
This is shown in the manage images panel. Generally this is the name of the file the raster was imported from.
- to_pillow()
Returns a Pillow.Image.Image object of the Raster.
- Returns:
A pillow image object with the same pixels as the raster.
- Return type:
PIL.Image.Image
Notes
Changing the returned object will not affect the Raster.
Examples
WARNING: These examples are incomplete and will not run by themselves. They assume a Project instance called project has been created and that raster_id has been set to the ObjectID of a raster object.
Save the pixels of the raster to a PNG file.
>>> with project.read(raster_id) as raster: ... pillow_image = raster.to_pillow() ... pillow_image.save(f"{raster.title}.png", "png")
Show the raster to the user in the standard image viewer.
>>> with project.read(raster_id) as raster: ... pillow_image = raster.to_pillow() ... pillow_image.show()
- property registration: RasterRegistration
Returns the registration for this raster.
The registration is an object which defines how the raster is draped onto Topology Objects.
If no raster registration is set, this will return a RasterRegistrationNone object. If raster registration is set, but the SDK does not support the type of registration (or if the application is too old for the SDK to read the registration information), it will return a RasterRegistrationUnsupported object. Otherwise it will return a RasterRegistration subclass representing the existing registration.
- Raises:
TypeError – If set to a value which is not a RasterRegistration.
ValueError – If set to an invalid RasterRegistration.
Notes
You should not assign to this property directly. Instead pass the registration to the associate_raster() function of the object you would like to associate the raster with.
- attribute_names()
Returns a list containing the names of all object-level attributes.
Use this to iterate over the object attributes.
- Returns:
List containing the attribute names.
- Return type:
list
Examples
Iterate over all object attributes of the object stared at “target” and print their values.
>>> from mapteksdk.project import Project >>> project = Project() >>> with project.read("target") as read_object: ... for name in read_object.attribute_names(): ... print(name, ":", read_object.get_attribute(name))
- close()
Closes the object.
This should be called as soon as you are finished working with an object. To avoid needing to remember to call this function, open the object using a with block and project.read(), project.new() or project.edit(). Those functions automatically call this function at the end of the with block.
A closed object cannot be used for further reading or writing. The ID of a closed object may be queried and this can then be used to re-open the object.
- property closed: bool
If this object has been closed.
Attempting to read or edit a closed object will raise an ObjectClosedError. Such an error typically indicates an error in the script and should not be caught.
Examples
If the object was opened with the Project.new(), Project.edit() or Project.read() in a “with” block, this will be True until the with block is closed and False afterwards.
>>> with self.project.new("cad/point_set", PointSet) as point_set: >>> point_set.points = [[1, 2, 3], [4, 5, 6]] >>> print("closed?", point_set.closed) >>> print("closed?", point_set.closed) closed? False closed? True
- property created_date: datetime
The date and time (in UTC) of when this object was created.
- Returns:
The date and time the object was created. 0:0:0 1/1/1970 if the operation failed.
- Return type:
datetime.datetime
- delete_all_attributes()
Delete all object attributes attached to an object.
This only deletes object attributes and has no effect on PrimitiveAttributes.
- Raises:
RuntimeError – If all attributes cannot be deleted.
- delete_attribute(attribute)
Deletes a single object-level attribute.
Deleting a non-existent object attribute will not raise an error.
- Parameters:
attribute (str) – Name of attribute to delete.
- Returns:
True if the object attribute existed and was deleted; False if the object attribute did not exist.
- Return type:
bool
- Raises:
RuntimeError – If the attribute cannot be deleted.
- get_attribute(name)
Returns the value for the attribute with the specified name.
- Parameters:
name (str) – The name of the object attribute to get the value for.
- Returns:
The value of the object attribute name. For dtype = datetime.datetime this is an integer representing the number of milliseconds since 1st Jan 1970. For dtype = datetime.date this is a tuple of the form: (year, month, day).
- Return type:
ObjectAttributeTypes
- Raises:
KeyError – If there is no object attribute called name.
Warning
In the future this function may be changed to return datetime.datetime and datetime.date objects instead of the current representation for object attributes of type datetime.datetime or datetime.date.
- get_attribute_type(name)
Returns the type of the attribute with the specified name.
- Parameters:
name (str) – Name of the attribute whose type should be returned.
- Returns:
The type of the object attribute name.
- Return type:
ObjectAttributeDataTypes
- Raises:
KeyError – If there is no object attribute called name.
- property is_read_only: bool
If this object is read-only.
This will return True if the object was open with Project.read() and False if it was open with Project.edit() or Project.new(). Attempting to edit a read-only object will raise an error.
- property lock_type: LockType
Indicates whether operating in read-only or read-write mode.
Use the is_read_only property instead for checking if an object is open for reading or editing.
- Returns:
The type of lock on this object. This will be LockType.ReadWrite if the object is open for editing and LockType.Read if the object is open for reading.
- Return type:
LockType
- property modified_date: datetime
The date and time (in UTC) of when this object was last modified.
- Returns:
The date and time this object was last modified. 0:0:0 1/1/1970 if the operation failed.
- Return type:
datetime.datetime
- save()
Save the changes made to the object.
Generally a user does not need to call this function, because it is called automatically at the end of a with block using Project.new() or Project.edit().
- Returns:
The change reasons for the operation. This depends on what changes to the object were saved. If the api_version is less than 1.9, this always returns ChangeReasons.NO_CHANGE.
- Return type:
- set_attribute(name, dtype, data)
Sets the value for the object attribute with the specified name.
This will overwrite any existing attribute with the specified name.
- Parameters:
name (str) – The name of the object attribute for which the value should be set.
dtype (type[Union[NoneType, Type[NoneType], ctypes.c_bool, ctypes.c_byte, ctypes.c_ubyte, ctypes.c_short, ctypes.c_ushort, ctypes.c_long, ctypes.c_ulong, ctypes.c_longlong, ctypes.c_ulonglong, ctypes.c_float, ctypes.c_double, ctypes.c_char_p, datetime.datetime, datetime.date, bool, int, float, str]] | None) – The type of data to assign to the attribute. This should be a type from the ctypes module or datetime.datetime or datetime.date. Passing bool is equivalent to passing ctypes.c_bool. Passing str is equivalent to passing ctypes.c_char_p. Passing int is equivalent to passing ctypes.c_int16. Passing float is equivalent to passing ctypes.c_double.
data (Any) – The value to assign to object attribute name. For dtype = datetime.datetime this can either be a datetime object or timestamp which will be passed directly to datetime.utcfromtimestamp(). For dtype = datetime.date this can either be a date object or a tuple of the form: (year, month, day).
- Raises:
ValueError – If dtype is an unsupported type.
TypeError – If value is an inappropriate type for object attribute name.
ValueError – If name starts or ends with whitespace or is empty.
RuntimeError – If a different error occurs.
Notes
If an error occurs after adding a new object attribute or editing an existing object attribute resulting in save() not being called, the changes to the object attributes can only be undone if the application’s API version is 1.6 or greater.
Prior to mapteksdk 1.6: Adding new object attributes, or editing the values of object attributes, will not be undone if an error occurs.
Examples
Create an object attribute on an object at “target” and then read its value.
>>> import ctypes >>> from mapteksdk.project import Project >>> project = Project() >>> with project.edit("target") as edit_object: ... edit_object.set_attribute("count", ctypes.c_int16, 0) ... with project.read("target") as read_object: ... print(read_object.get_attribute("count")) 0