Exemplo n.º 1
0
    def writer(self, array, *args, **kwargs):
        if isinstance(self.file, tuple):  # remove file type if present
            self.file = self.file[0]

        if (self.method == 'amplitude'
                or self.method == 'intensity') and np.iscomplexobj(array):
            array = np.abs(array)

        array = np.squeeze(array)
        if array.ndim == 4:
            nchannels = np.prod(array.shape[0:array.ndim - 2])
            array = np.reshape(array,
                               (nchannels, ) + array.shape[array.ndim - 2:])

        if array.ndim == 3 and self.chscl == True:
            for k in range(array.shape[0]):
                array[k, ...] = array[k, ...] / np.mean(array[k, ...])

        if self.method == 'intensity' or self.method == 'amplitude':
            if self.method == 'amplitude':
                array **= 0.7
            if self.method == 'intensity':
                array **= 0.35
            out = sarscale(array, factor=self.scaling)
        elif self.method == 'phase':
            out = phascale(array)
        elif self.method == 'coherence':
            out = cohscale(array)
        elif self.method == 'minmax':
            start = array.min()
            end = array.max()
            out = np.uint8(
                np.clip((array - start) / (end - start) * 255, 0, 255))
        else:
            logging.error("Scaling method unknown")
            return False

        if array.ndim == 3:
            if out.shape[0] < 3:
                oshp = out.shape
                oshp[0] = 3
                out = np.resize(out, oshp)
            if out.shape[0] > 3:
                out = out[0:3, ...]
            out = np.rollaxis(np.rollaxis(out[self.order, ...], 2), 2)
        else:
            out = colortables(self.palette)[1][out]

        try:
            pilimg = Image.fromarray(out)
            pilimg.save(self.file, format=self.key)
            logging.info("FINISHED SAVING IMAGE")
            return True
        except IOError as err:
            logging.error("ERROR:" + str(err))
            return False
        else:
            logging.error("UNKNOWN ERROR")
            return False
Exemplo n.º 2
0
    def data2img(self, cut_box, scale=0):
        if self.config['colour'] is False:
            channel = [int(self.config['bwlayer'].split('D')[1])]
        else:
            channel = [
                int(foo.split('D')[1]) for foo in self.config['rgblayer']
            ]
        method = self.config['scaling']

        img = self.data[scale][..., cut_box[2]:cut_box[3],
                               cut_box[0]:cut_box[1]][channel, ...].copy()

        if img.dtype == 'uint8':
            img = img.copy()
        elif method == 'amplitude' or method == 'intensity' or method == None:
            if method == 'intensity':
                img = np.abs(img)**0.35
            else:
                img = np.abs(img)**0.7
            if self.config['colour'] is True:
                for k in range(img.shape[0]):
                    img[k, ...] /= np.mean(img[k, ...])
            img = sarscale(img, factor=self.sarscale)
        elif method == 'phase':
            img = np.uint8(np.clip(img / np.pi * 128 + 127, 0.0, 255.0))
        elif method == '0.0->1.0':
            img = np.uint8(np.clip(img * 255.0, 0.0, 255.0))
        elif method == 'min->max':
            img -= np.min(img)
            img = np.uint8(img / np.max(img) * 255.0)
        elif method == 'labels':
            img -= np.min(self.data[0])
            img = np.uint8(img / np.max(self.data[0]) * 255.0)
        else:
            img = np.uint8(int)

        # img = img[..., 0:img.shape[-2] // 4 * 4, 0:img.shape[-1] // 4 * 4]    # QT Limitation!!
        img = np.rollaxis(np.rollaxis(img, axis=2), axis=2)

        if self.config['palette'] != 0:
            self.img = colortables(self.config['palette'])[1][img]
        else:
            self.img = img

        # img = np.rot90(np.rollaxis(np.rollaxis(img, axis=2), axis=2))

        if self.config['colour'] is True:
            return QtGui.QImage(img.tostring(), img.shape[1], img.shape[0],
                                QtGui.QImage.Format_RGB888)
        else:
            return QtGui.QImage(img.tostring(), img.shape[1], img.shape[0],
                                QtGui.QImage.Format_Indexed8)
Exemplo n.º 3
0
    def writer(self, array, *args, **kwargs):
        if isinstance(self.file, tuple):  # remove file type if present
            self.file = self.file[0]

        if (self.method == 'amplitude' or self.method == 'intensity') and np.iscomplexobj(array):
            array = np.abs(array)

        array = np.squeeze(array)
        if array.ndim == 4:
            nchannels = np.prod(array.shape[0:array.ndim-2])
            array = np.reshape(array, (nchannels, )+array.shape[array.ndim-2:])

        if array.ndim == 3 and self.chscl == True:
            for k in range(array.shape[0]):
                array[k, ...] = array[k, ...] / np.mean(array[k, ...])

        if self.method == 'intensity' or self.method == 'amplitude':
            if self.method == 'amplitude':
                array **= 0.7
            if self.method == 'intensity':
                array **= 0.35
            out = sarscale(array, factor=self.scaling)
        elif self.method == 'phase':
            out = phascale(array)
        elif self.method == 'coherence':
            out = cohscale(array)
        elif self.method == 'minmax':
            start = array.min()
            end = array.max()
            out = np.uint8(np.clip((array - start) / (end - start) * 255, 0, 255))
        else:
            logging.error("Scaling method unknown")
            return False

        if array.ndim == 3:
            out = np.rollaxis(np.rollaxis(out[self.order, ...], 2), 2)
        else:
            out = colortables(self.palette)[1][out]

        try:
            pilimg = Image.fromarray(out)
            pilimg.save(self.file, format=self.key)
            logging.info("FINISHED SAVING IMAGE")
            return True
        except IOError as err:
            logging.error("ERROR:" + str(err))
            return False
        else:
            logging.error("UNKNOWN ERROR")
            return False
Exemplo n.º 4
0
    def writer(self, array, *args, **kwargs):
        if isinstance(self.file, tuple):  # remove file type if present
            self.file = self.file[0]

        if (self.method == 'amplitude'
                or self.method == 'intensity') and np.iscomplexobj(array):
            array = np.abs(array)

        array = np.squeeze(array)
        if array.ndim == 4:
            nchannels = np.prod(array.shape[0:array.ndim - 2])
            array = np.reshape(array,
                               (nchannels, ) + array.shape[array.ndim - 2:])

        if array.ndim == 3 and self.chscl == True:
            for k in range(array.shape[0]):
                array[k, ...] = array[k, ...] / np.mean(array[k, ...])

        if self.method == 'intensity' or self.method == 'amplitude':
            if self.method == 'amplitude':
                array **= 0.7
            if self.method == 'intensity':
                array **= 0.35
            out = sarscale(array, factor=self.scaling)
        elif self.method == 'phase':
            out = phascale(array)
        elif self.method == 'coherence':
            out = cohscale(array)
        else:
            logging.error("Scaling method unknown")
            return False

        if array.ndim == 3:
            out = np.rollaxis(np.rollaxis(out[self.order, ...], 2), 2)
        else:
            out = colortables(self.palette)[1][out]

        try:
            misc.imsave(self.file, out, format=self.key)
            logging.info("FINISHED SAVING IMAGE")
            return True
        except IOError as err:
            logging.error("ERROR:" + str(err))
            return False
        else:
            logging.error("UNKNOWN ERROR")
            return False
Exemplo n.º 5
0
    def writer(self, array, *args, **kwargs):
        if isinstance(self.file, tuple):  # remove file type if present
            self.file = self.file[0]

        if self.method == 'amplitude' or self.method == 'intensity' and np.iscomplexobj(
                array):
            array = np.abs(array)

        array = np.squeeze(array)
        out = np.zeros_like(array, dtype='uint8')
        if array.ndim == 3 and self.chscl == True:
            for k in range(array.shape[0]):
                array[k, ...] = array[k, ...] / np.mean(array[k, ...])

        if self.method == 'intensity' or self.method == 'amplitude':
            if self.method == 'amplitude':
                array **= 0.7
            if self.method == 'intensity':
                array **= 0.35
            out = sarscale(array, factor=self.scaling)
        elif self.method == 'phase':
            out = phascale(array)
        elif self.method == 'coherence':
            out = cohscale(array)
        else:
            logging.error("Scaling method unknown")
            return False

        if array.ndim == 3:
            out = out[self.order, ...]
        else:
            out = colortables(self.palette)[1][out]

        try:
            misc.imsave(self.file, out, format=self.key)
            return True
        except IOError as err:
            logging.error("ERROR:" + str(err))
            return False
        else:
            logging.error("UNKNOWN ERROR")
            return False
Exemplo n.º 6
0
    def processPicture(self, **kwargs):
        if "fitwin" in kwargs.keys():  # self.size  = size of data set
            self.scale = len(self.data) - 1  # self.scale = pyramid level
            while self.scale > 0:  # self.box   = displayed part
                if self.data[self.scale].shape[-1] > self.imageLabel.width() or \
                        self.data[self.scale].shape[-2] > self.imageLabel.height():
                    break
                self.scale -= 1
            self.box = [0, self.size[0], 0, self.size[1]]
            cut_box = [foo // 2**self.scale for foo in self.box]
        else:
            self.scale = len(self.data) - 1
            while self.scale > 0:
                cut_box = [foo // 2**self.scale for foo in self.box]
                if cut_box[1] - cut_box[0] > self.imageLabel.width() or \
                        cut_box[3] - cut_box[2] > self.imageLabel.height():
                    break
                self.scale -= 1

            cut_box = [foo // 2**self.scale for foo in self.box]

        cut_box[1] = cut_box[0] + (cut_box[1] -
                                   cut_box[0]) // 4 * 4  # QT Limitation!!
        cut_box[3] = cut_box[2] + (cut_box[3] - cut_box[2]) // 4 * 4
        self.scale = int(np.clip(self.scale, 0, len(self.data) - 1))
        self.box[1] = cut_box[1] * int(2**self.scale)
        self.box[3] = cut_box[3] * int(2**self.scale)

        img = self.data2img(cut_box, scale=self.scale)

        xWin = self.imageLabel.width()
        yWin = self.imageLabel.height()
        winRatio = 1.0 * xWin / yWin

        self.imgwidth = img.width()
        self.imgheight = img.height()

        imgRatio = 1.0 * self.imgwidth / self.imgheight

        if imgRatio >= winRatio:  # match widths
            self.imgwidth = xWin
            self.imgheight = int(xWin / imgRatio)
        else:  # match heights
            self.imgheight = yWin
            self.imgwidth = int(yWin * imgRatio)

        self.factor = int(100.0 * self.imgwidth / (self.box[1] - self.box[0]))
        if self.factor <= 100:
            img = img.scaled(self.imgwidth, self.imgheight)  # Bilinear?
        else:
            img = img.scaled(self.imgwidth,
                             self.imgheight)  # Nearest Neighbour

        self.statusBar.setMessage(size=1, zoom=1, level=1, scale=1)
        self.viewCombo.setItemText(0, str(int(self.factor)) + '%')

        # colortable = [QtGui.qRgb(i, i, i) for i in range(256)]
        p = colortables(self.config['palette'])[1]
        colortable = [
            QtGui.qRgb(p[i, 0], p[i, 1], p[i, 2]) for i in range(256)
        ]

        img.setColorTable(colortable)
        self.imageLabel.setPixmap(QtGui.QPixmap.fromImage(img))
Exemplo n.º 7
0
 def paletteChooser(self):
     wid = PaletteSelector(colortables(), current=0, parent=self)
     res = wid.exec_()
     if res == 1:
         self.display[self.current]['palette'] = wid.palette
         self.processPicture()
Exemplo n.º 8
0
class Pixmap(pyrat.ExportWorker):
    """
    Export to various pixmap formats.

    For possible parameters see source code ;-)
    """
    para = [{
        'var': 'file',
        'value': '',
        'type': 'savefile',
        'text': 'Save to :'
    }, {
        'var': 'chscl',
        'value': True,
        'type': 'bool',
        'text': 'Scale channels indiviually'
    }, {
        'var': 'method',
        'value': 'amplitude',
        'type': 'list',
        'range': ['amplitude', 'intensity', 'phase', 'coherence'],
        'text': 'Method'
    }, {
        'var': 'scaling',
        'value': 2.5,
        'type': 'float',
        'range': [0.1, 20.0],
        'text': 'SAR scaling factor'
    }, {
        'var': 'palette',
        'value': 'bw linear',
        'type': 'list',
        'range': colortables()[0],
        'text': 'Color table'
    }]
    key = None

    def __init__(self, *args, **kwargs):
        super(Pixmap, self).__init__(*args, **kwargs)
        self.name = "EXPORT TO PIXMAP"
        if len(args) == 1:
            self.file = args[0]
        if 'order' not in self.__dict__:
            self.order = [0, 1, 2]

    def writer(self, array, *args, **kwargs):
        if isinstance(self.file, tuple):  # remove file type if present
            self.file = self.file[0]

        if self.method == 'amplitude' or self.method == 'intensity' and np.iscomplexobj(
                array):
            array = np.abs(array)

        array = np.squeeze(array)
        out = np.zeros_like(array, dtype='uint8')
        if array.ndim == 3 and self.chscl == True:
            for k in range(array.shape[0]):
                array[k, ...] = array[k, ...] / np.mean(array[k, ...])

        if self.method == 'intensity' or self.method == 'amplitude':
            if self.method == 'amplitude':
                array **= 0.7
            if self.method == 'intensity':
                array **= 0.35
            out = sarscale(array, factor=self.scaling)
        elif self.method == 'phase':
            out = phascale(array)
        elif self.method == 'coherence':
            out = cohscale(array)
        else:
            logging.error("Scaling method unknown")
            return False

        if array.ndim == 3:
            out = out[self.order, ...]
        else:
            out = colortables(self.palette)[1][out]

        try:
            misc.imsave(self.file, out, format=self.key)
            return True
        except IOError as err:
            logging.error("ERROR:" + str(err))
            return False
        else:
            logging.error("UNKNOWN ERROR")
            return False
Exemplo n.º 9
0
class Pixmap(pyrat.ExportWorker):
    """
    Export to various pixmap formats.

    For possible parameters see source code ;-)
    """
    para = [{
        'var': 'file',
        'value': '',
        'type': 'savefile',
        'text': 'Save to :'
    }, {
        'var': 'chscl',
        'value': True,
        'type': 'bool',
        'text': 'Scale channels indiviually'
    }, {
        'var': 'method',
        'value': 'amplitude',
        'type': 'list',
        'range': ['amplitude', 'intensity', 'phase', 'coherence', 'minmax'],
        'text': 'Method'
    }, {
        'var': 'scaling',
        'value': 2.5,
        'type': 'float',
        'range': [0.1, 20.0],
        'text': 'SAR scaling factor'
    }, {
        'var': 'palette',
        'value': 'bw linear',
        'type': 'list',
        'range': colortables()[0],
        'text': 'Color table'
    }, {
        'var': 'order',
        'type': 'list',
        'value': '0',
        'range': ['0', '2', '1'],
        'text': 'Channel selection'
    }]
    key = None

    def __init__(self, *args, **kwargs):
        super(Pixmap, self).__init__(*args, **kwargs)
        if self.key:
            self.name = "EXPORT TO " + self.key
        else:
            self.name = "EXPORT TO PIXMAP"
        if len(args) == 1:
            self.file = args[0]

    def writer(self, array, *args, **kwargs):
        if isinstance(self.file, tuple):  # remove file type if present
            self.file = self.file[0]

        if (self.method == 'amplitude'
                or self.method == 'intensity') and np.iscomplexobj(array):
            array = np.abs(array)

        array = np.squeeze(array)
        if array.ndim == 4:
            nchannels = np.prod(array.shape[0:array.ndim - 2])
            array = np.reshape(array,
                               (nchannels, ) + array.shape[array.ndim - 2:])

        if array.ndim == 3 and self.chscl == True:
            for k in range(array.shape[0]):
                array[k, ...] = array[k, ...] / np.mean(array[k, ...])

        if self.method == 'intensity' or self.method == 'amplitude':
            if self.method == 'amplitude':
                array **= 0.7
            if self.method == 'intensity':
                array **= 0.35
            out = sarscale(array, factor=self.scaling)
        elif self.method == 'phase':
            out = phascale(array)
        elif self.method == 'coherence':
            out = cohscale(array)
        elif self.method == 'minmax':
            start = array.min()
            end = array.max()
            out = np.uint8(
                np.clip((array - start) / (end - start) * 255, 0, 255))
        else:
            logging.error("Scaling method unknown")
            return False

        if array.ndim == 3:
            out = np.rollaxis(np.rollaxis(out[self.order, ...], 2), 2)
        else:
            out = colortables(self.palette)[1][out]

        try:
            pilimg = Image.fromarray(out)
            pilimg.save(self.file, format=self.key)
            logging.info("FINISHED SAVING IMAGE")
            return True
        except IOError as err:
            logging.error("ERROR:" + str(err))
            return False
        else:
            logging.error("UNKNOWN ERROR")
            return False

    @classmethod
    def guirun(cls, viewer, title=None):
        if not hasattr(pyrat, "app"):
            return

        paras = [{
            'var': 'file',
            'value': '',
            'type': 'savefile',
            'text': 'Save to :'
        }, {
            'var': 'zoom',
            'value': True,
            'type': 'bool',
            'text': 'Save only current window content'
        }]

        if cls.key == 'JPEG':
            paras[0]['extensions'] = 'JPEG file (*.jpg, *.jpeg)'
        elif cls.key == 'PNG':
            paras[0]['extensions'] = 'PNG file (*.png)'
        elif cls.key == 'TIFF':
            paras[0]['extensions'] = 'TIFF file (*.tif *.tiff)'
        elif cls.key == 'PDF':
            paras[0]['extensions'] = 'PDF file (*.pdf)'
        elif cls.key == 'EPS':
            paras[0]['extensions'] = 'EPS file (*.eps)'
        else:
            cls.key = None

        wid = pyrat.viewer.Dialogs.FlexInputDialog(paras,
                                                   parent=viewer,
                                                   title="Save to " + cls.key,
                                                   doc=cls.__doc__)
        res = wid.exec_()

        if res == 1:
            para = {}
            for p in paras:
                para[p['var']] = p['value']

            if para['zoom'] is True:  # save only window content
                img = np.squeeze(viewer.img)
                try:
                    pilimg = Image.fromarray(img)
                    pilimg.save(para['file'], format=cls.key)
                    return True
                except IOError as err:
                    logging.error("ERROR:" + str(err))
                    return False
            else:  # save entire image
                channels = [
                    int(foo.split('D')[1]) for foo in viewer.config['rgblayer']
                ]
                plugin = cls(file=para['file'],
                             method=viewer.config['scaling'],
                             scaling=viewer.sarscale,
                             palette=viewer.display[viewer.current]['palette'],
                             order=channels)
                plugin.run()