Beispiel #1
0
 def time_series(self,
                 num_spectra=None,
                 delay=None,
                 update_progress=lambda p: p):  # delay in ms
     if num_spectra is None:
         num_spectra = self.num_spectra
     if delay is None:
         delay = self.delay
     delay /= 1000
     update_progress(0)
     metadata = self.metadata
     extra_metadata = {
         'number of spectra': num_spectra,
         'spectrum end-to-start delay': delay
     }
     metadata.update(extra_metadata)
     to_save = []
     times = []
     start = time.time()
     for spectrum_number in range(num_spectra):
         times.append(time.time() - start)
         to_save.append(self.read_spectrum())  # should be a numpy array
         time.sleep(delay)
         update_progress(spectrum_number)
     metadata.update({'start times': times})
     self.create_dataset(self.time_series_name,
                         data=to_save,
                         attrs=metadata)
     to_return = ArrayWithAttrs(to_save, attrs=metadata)
     return to_return
Beispiel #2
0
def irradiate(time=10.0, laser_power=10, number_of_spec=10):
    spectrum_list = []
    for i in range(number_of_spec):
        spectrum_list.append(spec.read_spectrum())
    attrs = spec.metadata
    attrs['hi'] = 5
    return ArrayWithAttrs(spectrum_list, attrs=attrs)
Beispiel #3
0
 def raw_snapshot(self, update_latest_frame=True):
     """Returns a True, stating a succesful snapshot, followed by a (100,100)
     picture randomly generated image"""
     if self.data == 'spectrum':
         ran = 100 * ArrayWithAttrs(np.random.random(100))
     else:
         ran = 100 * np.random.random((100, 100))
     self._latest_raw_frame = ran
     return True, ran
Beispiel #4
0
 def z_scan(self, dz=np.arange(-4, 4, 0.4)):
     """Take spectra at (relative) z positions dz and return as a 2D array"""
     spectra = []
     here = self.stage.position
     for z in dz:
         self.stage.move(np.array([0, 0, z]) + here)
         time.sleep(self.settling_time)
         spectra.append(self.spectrometer.read_spectrum())
     self.stage.move(here)
     return ArrayWithAttrs(spectra, attrs=self.spectrometer.metadata)
def focus_stack(N, dz, snap=None):
    """Shift the focus (using Zernike modes) and acquire images."""
    if snap is None:
        global cam
        snap = lambda: cam.color_image()[:,:,2]
    img = snap()
    focus_stack = ArrayWithAttrs(np.zeros((N,)+img.shape, dtype=img.dtype))
    for i, d in enumerate(np.linspace(-dz,dz,N)):
        z = zernike_coefficients.copy()
        z[1] += d
        slm.zernike_coefficients = z
        focus_stack[i,:,:] = snap()
    slm.zernike_coefficients=zernike_coefficients
    plt.figure()
    plt.imshow(focus_stack[:,240,:],aspect="auto")
    focus_stack.attrs["dz"]=dz
    focus_stack.attrs["zernike_coefficients"]=zernike_coefficients
    dset = nplab.current_datafile().create_dataset("zstack_%d",data=focus_stack)
    return dset
def focus_stack(N, dz, snap=None):
    """Shift the focus (using Zernike modes) and acquire images."""
    if snap is None:
        global cam
        snap = lambda: cam.color_image()[:, :, 2]
    img = snap()
    focus_stack = ArrayWithAttrs(np.zeros((N, ) + img.shape, dtype=img.dtype))
    for i, d in enumerate(np.linspace(-dz, dz, N)):
        z = zernike_coefficients.copy()
        z[1] += d
        slm.zernike_coefficients = z
        focus_stack[i, :, :] = snap()
    slm.zernike_coefficients = zernike_coefficients
    plt.figure()
    plt.imshow(focus_stack[:, 240, :], aspect="auto")
    focus_stack.attrs["dz"] = dz
    focus_stack.attrs["zernike_coefficients"] = zernike_coefficients
    dset = nplab.current_datafile().create_dataset("zstack_%d",
                                                   data=focus_stack)
    return dset
def sequential_shack_hartmann(slm, snapshot_fn, spot, N, overlap=0.0, other_spots=[], pause=False,save=True):
    """Scan a spot over the SLM, recording intensities as we go"""
    results = ArrayWithAttrs(np.zeros((N, N, 3))) # For each position, find X,Y,I
    results.attrs['spot'] = spot
    results.attrs['n_apertures'] = N
    results.attrs['overlap'] = overlap
    results.attrs['other_spots'] = other_spots
    results.attrs['pause_between_spots'] = pause
    if pause:
        app = nplab.utils.gui.get_qt_app()
    for i in range(N):
        for j in range(N):
            slm.make_spots([spot + [float(i+0.5-N/2.0)/N, float(j+0.5-N/2.0)/N, 
                                (0.5 + overlap/2.0)/N, 0]] + other_spots)
            hdr = snapshot_fn()
            results[i,j,2] = hdr.sum()
            results[i,j,:2] = centroid(hdr)
            if pause:
                raw_input("spot %d, %d (hit enter for next)" % (i, j))
                app.processEvents()
            print '.',
    if save:
        dset = nplab.current_datafile().create_dataset("sequential_shack_hartmann_%d", data=results)
        return dset
    else:
        return results
Beispiel #8
0
 def read_spectrum(self, bundle_metadata=False):
     """Get the current reading from the spectrometer's sensor.
     
     Acquire a new spectrum and return it.  If bundle_metadata is true, this will be
     returned as an ArrayWithAttrs, including the current metadata."""
     e = ctypes.c_int()
     N = seabreeze.seabreeze_get_formatted_spectrum_length(self.index, byref(e))
     with self._comms_lock:
         spectrum_carray = (c_double * N)()  # this should create a c array of doubles, length N
         seabreeze.seabreeze_get_formatted_spectrum(self.index, byref(e), byref(spectrum_carray), N)
     check_error(e)  # throw an exception if something went wrong
     new_spectrum = np.array(list(spectrum_carray))
     if bundle_metadata:
         return ArrayWithAttrs(new_spectrum, attrs=self.metadata)
     else:
         return new_spectrum
Beispiel #9
0
def png_encode(image, compression=3):
    """Encode an image from a numpy array to a JPEG.
    
    This function allows compressed PNG images to be stored in an HDF5 file.
    You can pass in an OpenCV style image (i.e. an NxMx3 numpy array) and it
    will return a 1d array of uint8 that is smaller, depending on the
    quality factor specified.  It is returned as an array_with_attrs so that
    we can set attributes (that will be saved to HDF5 automatically) to say
    it was saved as a PNG.
    """
    ret, encoded_array = cv2.imencode('.png',image, 
                                      (cv2.cv.CV_IMWRITE_PNG_COMPRESSION, compression))
    assert ret, "Error encoding image"
    png = ArrayWithAttrs(encoded_array)
    png.attrs.create("image_format", "png")
    png.attrs.create("png_compression", compression)
    return png
Beispiel #10
0
def jpeg_encode(image, quality=90):
    """Encode an image from a numpy array to a JPEG.
    
    This function allows compressed JPEG images to be stored in an HDF5 file.
    You can pass in an OpenCV style image (i.e. an NxMx3 numpy array) and it
    will return a 1d array of uint8 that is smaller, depending on the
    quality factor specified.  It is returned as an array_with_attrs so that
    we can set attributes (that will be saved to HDF5 automatically) to say
    it was saved as a JPEG.
    """
    ret, encoded_array = cv2.imencode('.jpeg',image, 
                                      (cv2.cv.CV_IMWRITE_JPEG_QUALITY, quality))
    assert ret, "Error encoding image"
    jpeg = ArrayWithAttrs(encoded_array)
    jpeg.attrs.create("image_format", "jpeg")
    jpeg.attrs.create("jpeg_quality", quality)
    return jpeg
Beispiel #11
0
 def bundle_metadata(self, data, enable=True, **kwargs):
     """Add metadata to a dataset, returning an ArrayWithAttrs.
     
     Arguments:
     data : np.ndarray
         The data with which to bundle the metadata
     enable : boolean (optional, default to True)
         Set this argument to False to do nothing, i.e. just return data.
     **kwargs
         Addditional arguments are passed to get_metadata (for example, you 
         can specify a list of `property_names` to add to the default
         metadata, or a list of names to exclude.
     """
     if enable:
         return ArrayWithAttrs(data, attrs=self.get_metadata(**kwargs))
     else:
         return data
def sequential_shack_hartmann(slm,
                              snapshot_fn,
                              spot,
                              N,
                              overlap=0.0,
                              other_spots=[],
                              pause=False,
                              save=True):
    """Scan a spot over the SLM, recording intensities as we go"""
    results = ArrayWithAttrs(np.zeros(
        (N, N, 3)))  # For each position, find X,Y,I
    results.attrs['spot'] = spot
    results.attrs['n_apertures'] = N
    results.attrs['overlap'] = overlap
    results.attrs['other_spots'] = other_spots
    results.attrs['pause_between_spots'] = pause
    if pause:
        app = nplab.utils.gui.get_qt_app()
    for i in range(N):
        for j in range(N):
            slm.make_spots([
                spot + [
                    float(i + 0.5 - N / 2.0) / N,
                    float(j + 0.5 - N / 2.0) / N, (0.5 + overlap / 2.0) / N, 0
                ]
            ] + other_spots)
            hdr = snapshot_fn()
            results[i, j, 2] = hdr.sum()
            results[i, j, :2] = centroid(hdr)
            if pause:
                raw_input("spot %d, %d (hit enter for next)" % (i, j))
                app.processEvents()
            print '.',
    if save:
        dset = nplab.current_datafile().create_dataset(
            "sequential_shack_hartmann_%d", data=results)
        return dset
    else:
        return results