~gcg/+junk/trunk

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
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 25 19:56:48 2019

@author: gcg
"""

import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui
import numpy as np
import sys, copy
from matplotlib import cm
from numpy import ma

# Get the colormap
colormap = cm.get_cmap("nipy_spectral")  # cm.get_cmap("CMRmap")
colormap._init()
lut = (colormap._lut * 255).view(np.ndarray)  # Convert matplotlib colormap from 0-1 to 0 -255 for Qt

#pg.setConfigOptions(imageAxisOrder='row-major')

## Create CT image to display
nx, ny = 100, 50
structure = np.ones((nx, ny), dtype=float)
structure += np.random.normal(size=(nx,ny))

# create field image to overlay
field = np.ones((nx, ny)) * range(0, ny)

## create GUI
app = QtGui.QApplication([])
w = pg.GraphicsWindow(size=(1000,800), border=True)
w.setWindowTitle('pyqtgraph example: ROI Examples')
w1 = w.addLayout(row=0, col=0)
v1a = w1.addViewBox(row=1, col=0, lockAspect=True)

# this is the grey level CT image shwoing the structure
img1a = pg.ImageItem(structure)
v1a.addItem(img1a)
v1a.disableAutoRange('xy')
v1a.autoRange()

# this is the image that holds the transparent overlay
img2 = pg.ImageItem(pg.np.random.normal(size=(nx,ny)))
img2.setZValue(10)  # make sure this image is on top
img2.setOpacity(0.6)
img2.setLookupTable(lut)
v1a.addItem(img2)

rois = []
rois.append(pg.PolyLineROI([[80, 60], [90, 30], [60, 40]], pen=(6,9), closed=True))

def show_exception_and_exit(exc_type, exc_value, tb):
    import traceback
    traceback.print_exception(exc_type, exc_value, tb)
    raw_input("Press key to exit.")
    sys.exit(-1)
sys.excepthook = show_exception_and_exit

# generate index map
def generate_idxmap():
    idxmap = np.zeros((nx, ny, 2), dtype=int)
    for iy in xrange(ny):
        for ix in xrange(nx):
            idxmap[ix, iy, 0] = ix
            idxmap[ix, iy, 1] = iy
    return idxmap

def update(roi):
    pass
    #print roi.pos(), roi.boundingRect()
    rval = roi.getArrayRegion(idxmap, img1a, returnMappedCoords=False).astype(int)
    print "shape of rval is", np.shape(rval)
    
    # create an image to overlay on top of structure.
    # the overlay image is a copy of the underlying image, except within the selected region
    overlay_img = np.zeros((nx, ny))
    overlay_img = overlay_img.view(ma.MaskedArray)
    overlay_img.mask = True
    
    sx, sy, d = np.shape(rval)
    for ix in xrange(sx):
        for iy in xrange(sy):
            cx = rval[ix, iy, 0]
            cy = rval[ix, iy, 1]
            if cx and cy:
                icx = int(cx)
                icy = int(cy)
                overlay_img[icx, icy] = field[icx, icy]
    print "local bounds in ROI: ", overlay_img.min(), overlay_img.mean(), overlay_img.max()
    img2.setImage(overlay_img, levels=(field.min(), field.max())) # global min/max on colormap
    img2.setImage(overlay_img, levels=(overlay_img.min(), overlay_img.max())) # local min/max on colormap

idxmap = generate_idxmap()
    
for roi in rois:
    roi.sigRegionChanged.connect(update)
    v1a.addItem(roi)

update(rois[-1])
    



## Start Qt event loop unless running in interactive mode or using pyside.
if __name__ == '__main__':
    import sys
    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        QtGui.QApplication.instance().exec_()