color_setGammaRGB.py 2.89 KB
title = "SetGammaRGB"
tip = "applies gamma correction to colorbar"
onein = True

import numpy as np

import guiqwt.colormap as cm
from guidata.qt.QtGui import QMessageBox
from guidata.dataset.datatypes import DataSet
from guidata.dataset.dataitems import (IntItem, StringItem, ChoiceItem, FloatItem, BoolItem)
#from guiqwt.colormap import get_colormap_list, get_cmap, register_extra_colormap
from guiqwt.config import _

from guiqwt.transitional import QwtLinearColorMap, QwtDoubleInterval
FULLRANGE = QwtDoubleInterval(0.0, 1.0)

def nint(x):
    if x > 0: return int(x+0.5)
    else: return int(x-0.5)

class NOD3_App:

    def __init__(self, parent):
        self.parent = parent
        self.parent.activateWindow()

    def Error(self, msg):
        QMessageBox.critical(self.parent.parent(), title,
                              _(u"Error:")+"\n%s" % str(msg))

    def compute_app(self, **args):
        class FuncParam(DataSet):
            gammaR = FloatItem('Gamma(red)', default=1.0, min=0.001, max=10.0)
            gammaG = FloatItem('Gamma(green)', default=1.0, min=0.001, max=10.0)
            gammaB = FloatItem('Gamma(blue)', default=1.0, min=0.001, max=10.0)
        name = title.replace(" ", "")
        if args == {}:
           param = FuncParam(_(title), "Set gamma correction to colormap:")
        else:
           param = self.parent.ScriptParameter(name, args)

        # if no parameter needed set param to None. activate next line
        #param = None
        self.parent.compute_11(name, lambda m, p: self.function(m, p), param, onein) 

    def Gamma(self, a, p, f=255.0):
        gammaR = 1.0/p.gammaR
        gammaG = 1.0/p.gammaG
        gammaB = 1.0/p.gammaB
        y = hex(a)[2:-1]
        x = [ord(c) for c in y.decode('hex')]
        r = (float(x[1])/f)**gammaR
        g = (float(x[2])/f)**gammaG
        b = (float(x[3])/f)**gammaB
        return r, g, b

    def setup_color_map(self, p, f=255.0):
        cmap_name = self.parent.cmap
        #table = cm.get_cmap(cmap_name)
        #cmap = table.colorTable(FULLRANGE)
        item = self.parent.items[self.parent.row]
        cmap = item.get_color_map().colorTable(FULLRANGE)
        lut = {'red': [], 'green': [], 'blue': []}
        for i in range(len(cmap)):
            r, g, b = self.Gamma(cmap[i], p)
            lut['red'].append((float(i)/f, r, r))
            lut['green'].append((float(i)/f, g, g))
            lut['blue'].append((float(i)/f, b, b))
        return lut

    def function(self, m, p):
        cmdata = self.setup_color_map(p)
        my_cmap = QwtLinearColorMap()
        cname = self.parent.cmap + "_gammaRGB"
        cm._setup_colormap(my_cmap, cmdata)
        cm.register_extra_colormap(cname, my_cmap)
        item = self.parent.items[self.parent.row]
        item.set_color_map(cname)
        plot = item.plot()
        if plot:
           #plot.update_colormap_axis(cm.get_cmap(cname))
           plot.replot()
        return [], p