Example #1
0
def test_new_instance():
    img = ismrmrd.Image()
    eq_(type(img.getHead()), ismrmrd.ImageHeader)
    eq_(img.getHead().data_type, ismrmrd.DATATYPE_CXFLOAT)
    eq_(type(img.data), np.ndarray)
    eq_(img.data.dtype, np.complex64)

    attr = "this is a fake attribute string"
    head = ismrmrd.ImageHeader()
    head.attribute_string_len = len(attr)       # must set attribute_string_len
    head.data_type = ismrmrd.DATATYPE_CXFLOAT   # must set data_type
    img = ismrmrd.Image(head, attribute_string=attr)
    eq_(img.attribute_string, attr)
def _transform_from_legacy_image(items):
    items = list(items) + [""]
    header, data, meta = items[:3]
    header.attribute_string_len = len(meta)
    image = ismrmrd.Image(header, meta)
    image.data[:] = numpy.reshape(numpy.transpose(data), image.data.shape)
    return image
Example #3
0
def test_read_only_fields():
    img = ismrmrd.Image()
    for field in ['data_type', 'matrix_size', 'channels', 'attribute_string_len']:
        try:
            setattr(img, field, None)
        except AttributeError:
            pass
        else:
            raise Exception("Setting read-only attribute did not raise exception.")
Example #4
0
    def read_image(self):
        self.recvImages += 1
        logging.info("<-- Received MRD_MESSAGE_ISMRMRD_IMAGE (1022)")
        # return ismrmrd.Image.deserialize_from(self.read)

        # Explicit version of deserialize_from() for more verbose debugging
        logging.debug("   Reading in %d bytes of image header",
                      ctypes.sizeof(ismrmrd.ImageHeader))
        header_bytes = self.read(ctypes.sizeof(ismrmrd.ImageHeader))

        attribute_length_bytes = self.read(ctypes.sizeof(ctypes.c_uint64))
        attribute_length = ctypes.c_uint64.from_buffer_copy(
            attribute_length_bytes)
        logging.debug("   Reading in %d bytes of attributes",
                      attribute_length.value)

        attribute_bytes = self.read(attribute_length.value)
        if (attribute_length.value > 25000):
            logging.debug("   Attributes (truncated): %s",
                          attribute_bytes[0:24999].decode('utf-8'))
        else:
            logging.debug("   Attributes: %s", attribute_bytes.decode('utf-8'))

        image = ismrmrd.Image(header_bytes, attribute_bytes.decode('utf-8'))

        logging.info(
            "    Image is size %d x %d x %d with %d channels of type %s",
            image.matrix_size[0], image.matrix_size[1], image.matrix_size[2],
            image.channels, ismrmrd.get_dtype_from_data_type(image.data_type))

        def calculate_number_of_entries(nchannels, xs, ys, zs):
            return nchannels * xs * ys * zs

        nentries = calculate_number_of_entries(image.channels,
                                               *image.matrix_size)
        nbytes = nentries * ismrmrd.get_dtype_from_data_type(
            image.data_type).itemsize

        logging.debug("Reading in %d bytes of image data", nbytes)
        data_bytes = self.read(nbytes)

        image.data.ravel()[:] = np.frombuffer(
            data_bytes,
            dtype=ismrmrd.get_dtype_from_data_type(image.data_type))

        if self.savedata is True:
            if self.dset is None:
                self.create_save_file()

            image.attribute_string = ismrmrd.Meta.deserialize(
                image.attribute_string.split(
                    '\x00', 1)[0]).serialize()  # Strip off null teminator
            self.dset.append_image("images_%d" % image.image_series_index,
                                   image)

        return image
Example #5
0
def test_read_only_fields():
    img = ismrmrd.Image()

    for field in [
            'data_type', 'matrix_size', 'channels', 'attribute_string_len'
    ]:
        try:
            setattr(img, field, None)
        except:
            pass
        else:
            assert False, "assigned to read-only field of Image"
Example #6
0
def test_set_head():
    img = ismrmrd.Image()
    nchan, nx, ny, nz = 8, 256, 128, 32
    head = ismrmrd.ImageHeader()
    head.data_type = ismrmrd.DATATYPE_CXDOUBLE
    head.channels = nchan
    head.matrix_size[0] = nx
    head.matrix_size[1] = ny
    head.matrix_size[2] = nz

    img.setHead(head)

    eq_(img.data.shape, (nchan, nz, ny, nx))
    eq_(img.data_type, ismrmrd.DATATYPE_CXDOUBLE)
    eq_(img.data.dtype, np.complex128)
Example #7
0
    def read(self, sock):
        # read image header
        serialized_header = readsock(sock, ismrmrd.hdf5.image_header_dtype.itemsize)
        img = ismrmrd.Image(serialized_header)

        # now the image's data should be a valid NumPy array of zeros
        dtype = img.data.dtype
        data_bytes = len(img.data.flat) * dtype.itemsize
        serialized_data = readsock(sock, data_bytes)
        img.data.ravel()[:] = np.frombuffer(serialized_data,dtype=dtype)

        if not self.dataset:
            # open dataset
            self.dataset = ismrmrd.Dataset(self.filename, self.groupname)

        self.dataset.append_image("image_%d" % img.image_series_index, img)
Example #8
0
    def read_image(self, impath, imnum):
        if impath not in self._dataset:
            raise LookupError("Image data not found in the dataset.")
        
        # create an image
        # and fill with the header and attribute string for this image
        im = ismrmrd.Image(self._dataset[impath]['header'][imnum], self._dataset[impath]['attributes'][imnum])

        # copy the data
        # ismrmrd complex data is stored as pairs named real and imag
        # TODO do we need to store and reset or the config local to the module?
        cplxcfg = h5py.get_config().complex_names;
        h5py.get_config().complex_names = ('real','imag')
        im.data[:] = self._dataset[impath]['data'][imnum]
        h5py.get_config().complex_names = cplxcfg

        return im
Example #9
0
    def read_image(self):
        logging.info("<-- Received MRD_MESSAGE_ISMRMRD_IMAGE (1022)")
        # return ismrmrd.Image.deserialize_from(self.read)

        # Explicit version of deserialize_from() for more verbose debugging
        logging.debug("   Reading in %d bytes of image header",
                      ctypes.sizeof(ismrmrd.ImageHeader))
        header_bytes = self.read(ctypes.sizeof(ismrmrd.ImageHeader))

        attribute_length_bytes = self.read(ctypes.sizeof(ctypes.c_uint64))
        attribute_length = ctypes.c_uint64.from_buffer_copy(
            attribute_length_bytes)
        logging.debug("   Reading in %d bytes of attributes",
                      attribute_length.value)

        attribute_bytes = self.read(attribute_length.value)
        logging.debug("   Attributes: %s", attribute_bytes)

        image = ismrmrd.Image(header_bytes, attribute_bytes.decode('utf-8'))

        logging.debug("    Image is size %d x %d x %d of type %s",
                      image.matrix_size[0], image.matrix_size[1],
                      image.matrix_size[2],
                      ismrmrd.get_dtype_from_data_type(image.data_type))

        def calculate_number_of_entries(nchannels, xs, ys, zs):
            return nchannels * xs * ys * zs

        nentries = calculate_number_of_entries(image.channels,
                                               *image.matrix_size)
        nbytes = nentries * ismrmrd.get_dtype_from_data_type(
            image.data_type).itemsize

        logging.debug("Reading in %d bytes of image data", nbytes)
        data_bytes = self.read(nbytes)

        image.data.ravel()[:] = np.frombuffer(
            data_bytes,
            dtype=ismrmrd.get_dtype_from_data_type(image.data_type))

        if (self.savedata is True):
            self.dset.append_image("images_%d" % image.image_series_index,
                                   image)

        return image
Example #10
0
def gen_image_to_send(header: ismrmrd.xsd.ismrmrdHeader,
                      acqs: typing.List[ismrmrd.Acquisition] = None,
                      connection: gadgetron.external.Connection = None):
    # target picture size, should get get from header in the future
    recon_matrix = header.encoding[0].reconSpace.matrixSize
    ic = 1  # channel
    iz = 1  # z size
    iy = recon_matrix.y  # height
    ix = recon_matrix.x  # width
    dpi = 100  # data per inch
    figure = plt.gcf()  # type: Figure
    figure.set_size_inches(ix / dpi, iy / dpi)

    print(rf'--------------------plot begin-----------------------')
    t = np.arange(0.0, 2.0, 0.01)
    s = np.sin(2 * np.pi * t)

    plt.plot(t, s)
    plt.title(r'$\alpha_i > \beta_i$', fontsize=20)
    plt.text(1, -0.6, r'$\sum_{i=0}^\infty x_i$', fontsize=20)
    plt.text(0.6, 0.6, r'$\mathcal{A}\mathrm{sin}(2 \omega t)$', fontsize=20)
    plt.xlabel('time (s)')
    plt.ylabel('volts (mV)')

    plt.savefig("result.png", dpi=dpi)  # 3x100, 2x100
    print(rf'--------------------plot end-----------------------')

    h = ismrmrd.ImageHeader()  # type: ismrmrd.ImageHeader
    #h.data_type = ismrmrd.DATATYPE_USHORT
    h.data_type = ismrmrd.DATATYPE_FLOAT
    h.image_type = ismrmrd.IMTYPE_MAGNITUDE
    h.channels = ic
    h.matrix_size = (ix, iy, iz)

    i = ismrmrd.Image(h)

    gray_scale_img = PILImage.open('result.png').convert(
        'L')  # gray scale image uint 8
    img_data = np.array(gray_scale_img)

    #TODO how to stand this code?
    #i.data[:] = img_data[:, ::-1].data[:]
    i.data[:] = img_data.data[:]
    return i
Example #11
0
    def read(self, sock):
        # read image header
        serialized_header = readsock(sock, ismrmrd.hdf5.image_header_dtype.itemsize)
        # read meta attributes
        msg = readsock(self.sock, SIZEOF_GADGET_MESSAGE_ATTRIB_LENGTH)
        attrib_len = GadgetMessageAttribLength.unpack(msg)[0]
        attribs = readsock(self.sock, attrib_len)

        # make a new image
        img = ismrmrd.Image(serialized_header, attribs)

        # now the image's data should be a valid NumPy array of zeros
        dtype = img.data.dtype
        data_bytes = len(img.data.flat) * dtype.itemsize
        serialized_data = readsock(sock, data_bytes)
        img.data.ravel()[:] = np.fromstring(serialized_data, dtype=dtype)

        if not self.dataset:
            # open dataset
            self.dataset = ismrmrd.Dataset(self.filename, self.groupname)

        self.dataset.append_image("image_%d" % img.image_series_index, img)
    g0 = define_gadget_chain()  #Call function from imported file

    #%% Load file
    if not os.path.isfile(filename):
        print("%s is not a valid file" % filename)
        raise SystemExit
    dset = ismrmrd.Dataset(filename, 'dataset', create_if_needed=False)

    #%% Send in data
    #First ISMRMRD XML header
    gadget_config(g0, dset.read_xml_header())

    # Loop through the rest of the acquisitions and stuff
    for acqnum in range(0, dset.number_of_acquisitions()):
        acq = dset.read_acquisition(acqnum)
        g0.process(acq.getHead(), acq.data.astype('complex64'))

    #%%
    gadget_wait_function(g0)

    res = get_last_gadget(g0).get_results()
    print "Received " + str(len(res)) + " result items"

    out_dset = ismrmrd.Dataset(filename_out, "out")
    for o in res:
        print "Appending image to out file"
        img = ismrmrd.Image(head=o[0])
        img.data.ravel()[:] = o[1].ravel()[:]
        out_dset.append_image("image_%d" % img.image_series_index, img)
Example #13
0
import ismrmrd

acq = ismrmrd.Acquisition()
acq.version = 42
print(acq.version)

img = ismrmrd.Image()

f = ismrmrd.Dataset('./testdata.h5', '/dataset', True)
print(f._file)
# xml = f.readHeader()
Example #14
0
def test_resize():
    img = ismrmrd.Image()
    nchan, nx, ny, nz = 8, 256, 128, 32
    img.resize(nchan, nz, ny, nx)
    eq_(img.data.shape, (nchan, nz, ny, nx))
    eq_(img.matrix_size, (nz, ny, nx))