1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
|
# (C) Copyright 2005-2023 Enthought, Inc., Austin, TX
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in LICENSE.txt and may be redistributed only under
# the conditions described in the aforementioned license. The license
# is also available online at http://www.enthought.com/licenses/BSD.txt
#
# Thanks for using Enthought open source!
"""
Observation
===========
In our code so far, there is a problem that it is possible for certain related
values to get out of sync with one another. For example, if we change the
filename after we have read the image into memory, then the data in memory
still refers to the old image. It would be nice if we could automatically
re-load the image if the filename changes. Traits allows you to do this.
The Observe Decorator
---------------------
We want to have the `read_image` method run whenever the ``filename`` trait
changes. We can do this by adding an ``observe`` decorator to the method::
class Image(HasTraits):
...
@observe('filename')
def read_image(self, event):
...
The observer passes an event object to the function which contains information
about what changed, such as the old value of the trait, but we don't need that
information to react to the change, so it is ignored in the body of the
function.
For most traits, the observer will run only when the trait's value *actually*
changes, not just when the value is set. So if you do::
>>> image.filename = "sample_0001.png"
>>> image.filename = "sample_0001.png"
then the observer will only be run once.
Observing Multiple Traits
-------------------------
If you look at the computation of ``pixel_area`` in the original code, it
looks like this::
self.pixel_area = self.scan_height * self.scan_width / self.image.size
It depends on the ``scan_width``, ``scan_height`` and the ``image``, so we
would like to listen to changes to *all* of these. We could write three
``@observe`` functions, one for each trait, but the content would be the
same for each. A better way to do this is to have the observer listen to
all the traits at once::
class Image(HasTraits):
...
@observe('scan_width, scan_height, image')
def update_pixel_area(self, event):
if self.image.size > 0:
self.pixel_area = (
self.scan_height * self.scan_width / self.image.size
)
else:
self.pixel_area = 0
Dynamic Observers
-----------------
Sometimes you want to be able to observe changes to traits from a different
object or piece of code. The ``observe`` method on a ``HasTraits`` subclass
allows you to dynamically specify a function to be called if the value of a
trait changes::
image = Image(
filename="sample_0001.png",
sample_id="0001",
)
def print_filename_changed(event):
print("Filename changed")
image.observe(print_filename_changed, 'filename')
# will print "Filename changed" to the screen
image.filename="sample_0002.png"
Dynamic observers can also be disconnected using the same method, by adding
the argument ``remove=True``::
image.observe(print_filename_changed, 'filename', remove=True)
# nothing will print
image.filename="sample_0003.png"
Exercise
--------
Currently ``scan_height`` and ``scan_width`` are set from the parts of the
``scan_size`` trait as part of the ``traits_init`` method. Remove the
``traits_init`` method and have ``scan_height`` and ``scan_width`` methods
update whenever ``scan_size`` changes.
"""
import os
import datetime
from PIL import Image as PILImage
import numpy as np
from traits.api import (
Array, Date, File, Float, HasTraits, Str, Tuple, observe
)
class Image(HasTraits):
""" An SEM image stored in a file. """
filename = File(exists=True)
sample_id = Str()
operator = Str("N/A")
date_acquired = Date()
scan_size = Tuple(Float, Float)
scan_width = Float
scan_height = Float
image = Array(shape=(None, None), dtype='uint8')
pixel_area = Float()
def traits_init(self):
# useful secondary attributes
self.scan_width, self.scan_height = self.scan_size
# Trait observers
@observe('filename')
def read_image(self, event):
pil_image = PILImage.open(self.filename).convert("L")
self.image = np.array(pil_image)
@observe('scan_width, scan_height, image')
def update_pixel_area(self, event):
if self.image.size > 0:
self.pixel_area = (
self.scan_height * self.scan_width / self.image.size
)
else:
self.pixel_area = 0
# Trait default methods
def _date_acquired_default(self):
return datetime.date.today()
def _scan_size_default(self):
return (1e-5, 1e-5)
# ---------------------------------------------------------------------------
# Demo code
# ---------------------------------------------------------------------------
this_dir = os.path.dirname(__file__)
image_dir = os.path.join(this_dir, "images")
filename = os.path.join(image_dir, "sample_0001.png")
# load the image
image = Image(
filename=filename,
operator="Hannes",
sample_id="0001",
)
# perform some sample computations
print("Scan size:", image.scan_size)
print("Change scan width to 1e-4")
image.scan_width = 1e-4
print("Scan size:", image.scan_size)
for filename in os.listdir(image_dir):
if os.path.splitext(filename)[1] == '.png':
print()
print("Changing filename to {}".format(filename))
image.filename = os.path.join(image_dir, filename)
print(
"The pixel size of {} is {:0.3f} nm²".format(
filename,
image.pixel_area * 1e18,
)
)
|