Exemple #1
0
def test_NonUniformImage_colormap():

    window = pg.GraphicsLayoutWidget()
    viewbox = pg.ViewBox()
    window.setCentralWidget(viewbox)
    window.resize(200, 200)
    window.show()

    x = [1.0, 3.0, 10.0]
    y = [1.0, 2.0, 4.0]
    X, Y = np.meshgrid(x, y, indexing='ij')
    Z = X * Y

    Z[:, 0] = [np.NINF, np.NAN, np.PINF]

    image = NonUniformImage(x, y, Z, border=fn.mkPen('g'))

    cmap = ColorMap(pos=[0.0, 1.0],
                    color=[(0.0, 0.0, 0.0, 1.0), (1.0, 1.0, 1.0, 1.0)])
    image.setColorMap(cmap)

    viewbox.addItem(image)

    QtTest.QTest.qWaitForWindowExposed(window)
    QtTest.QTest.qWait(100)

    assertImageApproved(window, 'nonuniform_image/colormap-3x3')
Exemple #2
0
def test_NonUniformImage_lut():

    window = pg.GraphicsLayoutWidget()
    viewbox = pg.ViewBox()
    window.setCentralWidget(viewbox)
    window.resize(200, 200)
    window.show()

    x = [1.0, 3.0, 10.0]
    y = [1.0, 2.0, 4.0]
    X, Y = np.meshgrid(x, y, indexing='ij')
    Z = X * Y

    image = NonUniformImage(x, y, Z, border=fn.mkPen('g'))
    viewbox.addItem(image)

    lut = pg.HistogramLUTItem()
    window.addItem(lut)

    image.setLookupTable(lut, autoLevel=True)

    h = image.getHistogram()
    lut.plot.setData(*h)

    QtTest.QTest.qWaitForWindowExposed(window)
    QtTest.QTest.qWait(100)

    assertImageApproved(window, 'nonuniform_image/lut-3x3')
Exemple #3
0
def test_PlotCurveItem():
    p = pg.GraphicsLayoutWidget()
    p.resize(200, 150)
    p.ci.setContentsMargins(4, 4, 4, 4)  # default margins vary by platform
    p.show()
    v = p.addViewBox()
    data = np.array(
        [1, 4, 2, 3, np.inf, 5, 7, 6, -np.inf, 8, 10, 9, np.nan, -1, -2, 0])
    c = pg.PlotCurveItem(data)
    v.addItem(c)
    v.autoRange()

    # Check auto-range works. Some platform differences may be expected..
    checkRange = np.array([[-1.1457564053237301, 16.145756405323731],
                           [-3.076811473165955, 11.076811473165955]])
    assert np.allclose(v.viewRange(), checkRange)

    assertImageApproved(p, 'plotcurveitem/connectall',
                        "Plot curve with all points connected.")

    c.setData(data, connect='pairs')
    assertImageApproved(p, 'plotcurveitem/connectpairs',
                        "Plot curve with pairs connected.")

    c.setData(data, connect='finite')
    assertImageApproved(p, 'plotcurveitem/connectfinite',
                        "Plot curve with finite points connected.")

    c.setData(data,
              connect=np.array(
                  [1, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0]))
    assertImageApproved(p, 'plotcurveitem/connectarray',
                        "Plot curve with connection array.")

    p.close()
def test_PlotCurveItem():
    p = pg.GraphicsWindow()
    p.ci.layout.setContentsMargins(4, 4, 4, 4)  # default margins vary by platform
    v = p.addViewBox()
    p.resize(200, 150)
    data = np.array([1, 4, 2, 3, np.inf, 5, 7, 6, -np.inf, 8, 10, 9, np.nan, -1, -2, 0])
    c = pg.PlotCurveItem(data)
    v.addItem(c)
    v.autoRange()

    # Check auto-range works. Some platform differences may be expected..
    checkRange = np.array([[-1.1457564053237301, 16.145756405323731], [-3.076811473165955, 11.076811473165955]])
    assert np.allclose(v.viewRange(), checkRange)

    assertImageApproved(p, "plotcurveitem/connectall", "Plot curve with all points connected.")

    c.setData(data, connect="pairs")
    assertImageApproved(p, "plotcurveitem/connectpairs", "Plot curve with pairs connected.")

    c.setData(data, connect="finite")
    assertImageApproved(p, "plotcurveitem/connectfinite", "Plot curve with finite points connected.")

    c.setData(data, connect=np.array([1, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0]))
    assertImageApproved(p, "plotcurveitem/connectarray", "Plot curve with connection array.")
Exemple #5
0
def check_getArrayRegion(roi, name, testResize=True, transpose=False):
    initState = roi.getState()

    #win = pg.GraphicsLayoutWidget()
    win = pg.GraphicsView()
    win.show()
    resizeWindow(win, 200, 400)
    # Don't use Qt's layouts for testing--these generate unpredictable results.
    #vb1 = win.addViewBox()
    #win.nextRow()
    #vb2 = win.addViewBox()

    # Instead, place the viewboxes manually
    vb1 = pg.ViewBox()
    win.scene().addItem(vb1)
    vb1.setPos(6, 6)
    vb1.resize(188, 191)

    vb2 = pg.ViewBox()
    win.scene().addItem(vb2)
    vb2.setPos(6, 203)
    vb2.resize(188, 191)

    img1 = pg.ImageItem(border='w')
    img2 = pg.ImageItem(border='w')

    vb1.addItem(img1)
    vb2.addItem(img2)

    np.random.seed(0)
    data = np.random.normal(size=(7, 30, 31, 5))
    data[0, :, :, :] += 10
    data[:, 1, :, :] += 10
    data[:, :, 2, :] += 10
    data[:, :, :, 3] += 10

    if transpose:
        data = data.transpose(0, 2, 1, 3)

    img1.setImage(data[0, ..., 0])
    vb1.setAspectLocked()
    vb1.enableAutoRange(True, True)

    roi.setZValue(10)
    vb1.addItem(roi)

    if isinstance(roi, pg.RectROI):
        if transpose:
            assert roi.getAffineSliceParams(data, img1, axes=(1, 2)) == ([
                28.0, 27.0
            ], ((1.0, 0.0), (0.0, 1.0)), (1.0, 1.0))
        else:
            assert roi.getAffineSliceParams(data, img1, axes=(1, 2)) == ([
                27.0, 28.0
            ], ((1.0, 0.0), (0.0, 1.0)), (1.0, 1.0))

    rgn = roi.getArrayRegion(data, img1, axes=(1, 2))
    #assert np.all((rgn == data[:, 1:-2, 1:-2, :]) | (rgn == 0))
    img2.setImage(rgn[0, ..., 0])
    vb2.setAspectLocked()
    vb2.enableAutoRange(True, True)

    app.processEvents()
    assertImageApproved(win, name + '/roi_getarrayregion',
                        'Simple ROI region selection.')

    with pytest.raises(TypeError):
        roi.setPos(0, False)

    roi.setPos([0.5, 1.5])
    rgn = roi.getArrayRegion(data, img1, axes=(1, 2))
    img2.setImage(rgn[0, ..., 0])
    app.processEvents()
    assertImageApproved(win, name + '/roi_getarrayregion_halfpx',
                        'Simple ROI region selection, 0.5 pixel shift.')

    roi.setAngle(45)
    roi.setPos([3, 0])
    rgn = roi.getArrayRegion(data, img1, axes=(1, 2))
    img2.setImage(rgn[0, ..., 0])
    app.processEvents()
    assertImageApproved(win, name + '/roi_getarrayregion_rotate',
                        'Simple ROI region selection, rotation.')

    if testResize:
        roi.setSize([60, 60])
        rgn = roi.getArrayRegion(data, img1, axes=(1, 2))
        img2.setImage(rgn[0, ..., 0])
        app.processEvents()
        assertImageApproved(win, name + '/roi_getarrayregion_resize',
                            'Simple ROI region selection, resized.')

    img1.setPos(0, img1.height())
    img1.setTransform(QtGui.QTransform().scale(1, -1).rotate(20), True)
    rgn = roi.getArrayRegion(data, img1, axes=(1, 2))
    img2.setImage(rgn[0, ..., 0])
    app.processEvents()
    assertImageApproved(win, name + '/roi_getarrayregion_img_trans',
                        'Simple ROI region selection, image transformed.')

    vb1.invertY()
    rgn = roi.getArrayRegion(data, img1, axes=(1, 2))
    img2.setImage(rgn[0, ..., 0])
    app.processEvents()
    # on windows, one edge of one ROI handle is shifted slightly; letting this slide with pxCount=10
    if pg.Qt.QT_LIB in {'PyQt4', 'PySide'}:
        pxCount = 10
    else:
        pxCount = -1
    assertImageApproved(win,
                        name + '/roi_getarrayregion_inverty',
                        'Simple ROI region selection, view inverted.',
                        pxCount=pxCount)

    roi.setState(initState)
    img1.setPos(0, 0)
    img1.setTransform(QtGui.QTransform.fromScale(1, 0.5))
    rgn = roi.getArrayRegion(data, img1, axes=(1, 2))
    img2.setImage(rgn[0, ..., 0])
    app.processEvents()
    assertImageApproved(
        win, name + '/roi_getarrayregion_anisotropic',
        'Simple ROI region selection, image scaled anisotropically.')

    # allow the roi to be re-used
    roi.scene().removeItem(roi)

    win.hide()
Exemple #6
0
def test_PolyLineROI():
    rois = [(pg.PolyLineROI([[0, 0], [10, 0], [0, 15]], closed=True,
                            pen=0.3), 'closed'),
            (pg.PolyLineROI([[0, 0], [10, 0], [0, 15]], closed=False,
                            pen=0.3), 'open')]

    #plt = pg.plot()
    plt = pg.GraphicsView()
    plt.show()
    resizeWindow(plt, 200, 200)
    vb = pg.ViewBox()
    plt.scene().addItem(vb)
    vb.resize(200, 200)
    #plt.plotItem = pg.PlotItem()
    #plt.scene().addItem(plt.plotItem)
    #plt.plotItem.resize(200, 200)

    plt.scene().minDragTime = 0  # let us simulate mouse drags very quickly.

    # seemingly arbitrary requirements; might need longer wait time for some platforms..
    QtTest.QTest.qWaitForWindowExposed(plt)
    QtTest.QTest.qWait(100)

    for r, name in rois:
        vb.clear()
        vb.addItem(r)
        vb.autoRange()
        app.processEvents()

        assertImageApproved(plt, 'roi/polylineroi/' + name + '_init',
                            'Init %s polyline.' % name)
        initState = r.getState()
        assert len(r.getState()['points']) == 3

        # hover over center
        center = r.mapToScene(pg.Point(3, 3))
        mouseMove(plt, center)
        assertImageApproved(plt, 'roi/polylineroi/' + name + '_hover_roi',
                            'Hover mouse over center of ROI.')

        # drag ROI
        mouseDrag(plt, center, center + pg.Point(10, -10),
                  QtCore.Qt.LeftButton)
        assertImageApproved(plt, 'roi/polylineroi/' + name + '_drag_roi',
                            'Drag mouse over center of ROI.')

        # hover over handle
        pt = r.mapToScene(pg.Point(r.getState()['points'][2]))
        mouseMove(plt, pt)
        assertImageApproved(plt, 'roi/polylineroi/' + name + '_hover_handle',
                            'Hover mouse over handle.')

        # drag handle
        mouseDrag(plt, pt, pt + pg.Point(5, 20), QtCore.Qt.LeftButton)
        assertImageApproved(plt, 'roi/polylineroi/' + name + '_drag_handle',
                            'Drag mouse over handle.')

        # hover over segment
        pt = r.mapToScene((pg.Point(r.getState()['points'][2]) +
                           pg.Point(r.getState()['points'][1])) * 0.5)
        mouseMove(plt, pt + pg.Point(0, 2))
        assertImageApproved(plt, 'roi/polylineroi/' + name + '_hover_segment',
                            'Hover mouse over diagonal segment.')

        # click segment
        mouseClick(plt, pt, QtCore.Qt.LeftButton)
        assertImageApproved(plt, 'roi/polylineroi/' + name + '_click_segment',
                            'Click mouse over segment.')

        # drag new handle
        mouseMove(
            plt, pt + pg.Point(10, -10)
        )  # pg bug: have to move the mouse off/on again to register hover
        mouseDrag(plt, pt, pt + pg.Point(10, -10), QtCore.Qt.LeftButton)
        assertImageApproved(plt,
                            'roi/polylineroi/' + name + '_drag_new_handle',
                            'Drag mouse over created handle.')

        # clear all points
        r.clearPoints()
        assertImageApproved(plt, 'roi/polylineroi/' + name + '_clear',
                            'All points cleared.')
        assert len(r.getState()['points']) == 0

        # call setPoints
        r.setPoints(initState['points'])
        assertImageApproved(plt, 'roi/polylineroi/' + name + '_setpoints',
                            'Reset points to initial state.')
        assert len(r.getState()['points']) == 3

        # call setState
        r.setState(initState)
        assertImageApproved(plt, 'roi/polylineroi/' + name + '_setstate',
                            'Reset ROI to initial state.')
        assert len(r.getState()['points']) == 3

    plt.hide()
Exemple #7
0
def test_ImageItem(transpose=False):
    w = pg.GraphicsLayoutWidget()
    w.show()
    view = pg.ViewBox()
    w.setCentralWidget(view)
    w.resize(200, 200)
    img = TransposedImageItem(border=0.5, transpose=transpose)

    view.addItem(img)

    # test mono float
    np.random.seed(0)
    data = np.random.normal(size=(20, 20))
    dmax = data.max()
    data[:10, 1] = dmax + 10
    data[1, :10] = dmax + 12
    data[3, :10] = dmax + 13
    img.setImage(data)

    QtTest.QTest.qWaitForWindowExposed(w)
    time.sleep(0.1)
    app.processEvents()
    assertImageApproved(
        w, 'imageitem/init',
        'Init image item. View is auto-scaled, image axis 0 marked by 1 line, axis 1 is marked by 2 lines. Origin in bottom-left.'
    )

    # ..with colormap
    cmap = pg.ColorMap([0, 0.25, 0.75, 1],
                       [[0, 0, 0, 255], [255, 0, 0, 255], [255, 255, 0, 255],
                        [255, 255, 255, 255]])
    img.setLookupTable(cmap.getLookupTable())
    assertImageApproved(w, 'imageitem/lut', 'Set image LUT.')

    # ..and different levels
    img.setLevels([dmax + 9, dmax + 13])
    assertImageApproved(w, 'imageitem/levels1', 'Levels show only axis lines.')

    img.setLookupTable(None)

    # test mono int
    data = np.fromfunction(lambda x, y: x + y * 10,
                           (129, 128)).astype(np.int16)
    img.setImage(data)
    assertImageApproved(w, 'imageitem/gradient_mono_int', 'Mono int gradient.')

    img.setLevels([640, 641])
    assertImageApproved(w, 'imageitem/gradient_mono_int_levels',
                        'Mono int gradient w/ levels to isolate diagonal.')

    # test mono byte
    data = np.fromfunction(lambda x, y: x + y, (129, 128)).astype(np.ubyte)
    img.setImage(data)
    assertImageApproved(w, 'imageitem/gradient_mono_byte',
                        'Mono byte gradient.')

    img.setLevels([127, 128])
    assertImageApproved(w, 'imageitem/gradient_mono_byte_levels',
                        'Mono byte gradient w/ levels to isolate diagonal.')

    # test monochrome image
    data = np.zeros((10, 10), dtype='uint8')
    data[:5, :5] = 1
    data[5:, 5:] = 1
    img.setImage(data)
    assertImageApproved(w, 'imageitem/monochrome',
                        'Ubyte image with only 0,1 values.')

    # test bool
    data = data.astype(bool)
    img.setImage(data)
    assertImageApproved(w, 'imageitem/bool', 'Boolean mask.')

    # test RGBA byte
    data = np.zeros((100, 100, 4), dtype='ubyte')
    data[..., 0] = np.linspace(0, 255, 100).reshape(100, 1)
    data[..., 1] = np.linspace(0, 255, 100).reshape(1, 100)
    data[..., 3] = 255
    img.setImage(data)
    assertImageApproved(w, 'imageitem/gradient_rgba_byte',
                        'RGBA byte gradient.')

    img.setLevels([[128, 129], [128, 255], [0, 1], [0, 255]])
    assertImageApproved(
        w, 'imageitem/gradient_rgba_byte_levels',
        'RGBA byte gradient. Levels set to show x=128 and y>128.')

    # test RGBA float
    data = data.astype(float)
    img.setImage(data / 1e9)
    assertImageApproved(w, 'imageitem/gradient_rgba_float',
                        'RGBA float gradient.')

    # checkerboard to test alpha
    img2 = TransposedImageItem(transpose=transpose)
    img2.setImage(np.fromfunction(lambda x, y: (x + y) % 2, (10, 10)),
                  levels=[-1, 2])
    view.addItem(img2)
    img2.setScale(10)
    img2.setZValue(-10)

    data[..., 0] *= 1e-9
    data[..., 1] *= 1e9
    data[..., 3] = np.fromfunction(lambda x, y: np.sin(0.1 * (x + y)),
                                   (100, 100))
    img.setImage(data, levels=[[0, 128e-9], [0, 128e9], [0, 1], [-1, 1]])
    assertImageApproved(w, 'imageitem/gradient_rgba_float_alpha',
                        'RGBA float gradient with alpha.')

    # test composition mode
    img.setCompositionMode(QtGui.QPainter.CompositionMode_Plus)
    assertImageApproved(
        w, 'imageitem/gradient_rgba_float_additive',
        'RGBA float gradient with alpha and additive composition mode.')

    img2.hide()
    img.setCompositionMode(QtGui.QPainter.CompositionMode_SourceOver)

    # test downsampling
    data = np.fromfunction(lambda x, y: np.cos(0.002 * x**2), (800, 100))
    img.setImage(data, levels=[-1, 1])
    assertImageApproved(w, 'imageitem/resolution_without_downsampling',
                        'Resolution test without downsampling.')

    img.setAutoDownsample(True)
    assertImageApproved(w, 'imageitem/resolution_with_downsampling_x',
                        'Resolution test with downsampling axross x axis.')
    assert img._lastDownsample == (4, 1)

    img.setImage(data.T, levels=[-1, 1])
    assertImageApproved(w, 'imageitem/resolution_with_downsampling_y',
                        'Resolution test with downsampling across y axis.')
    assert img._lastDownsample == (1, 4)

    w.hide()
Exemple #8
0
def check_getArrayRegion(roi, name, testResize=True, transpose=False):
    initState = roi.getState()
    
    #win = pg.GraphicsLayoutWidget()
    win = pg.GraphicsView()
    win.show()
    resizeWindow(win, 200, 400)
    # Don't use Qt's layouts for testing--these generate unpredictable results.
    #vb1 = win.addViewBox()
    #win.nextRow()
    #vb2 = win.addViewBox()
    
    # Instead, place the viewboxes manually 
    vb1 = pg.ViewBox()
    win.scene().addItem(vb1)
    vb1.setPos(6, 6)
    vb1.resize(188, 191)

    vb2 = pg.ViewBox()
    win.scene().addItem(vb2)
    vb2.setPos(6, 203)
    vb2.resize(188, 191)
    
    img1 = pg.ImageItem(border='w')
    img2 = pg.ImageItem(border='w')

    vb1.addItem(img1)
    vb2.addItem(img2)
    
    np.random.seed(0)
    data = np.random.normal(size=(7, 30, 31, 5))
    data[0, :, :, :] += 10
    data[:, 1, :, :] += 10
    data[:, :, 2, :] += 10
    data[:, :, :, 3] += 10
    
    if transpose:
        data = data.transpose(0, 2, 1, 3)
    
    img1.setImage(data[0, ..., 0])
    vb1.setAspectLocked()
    vb1.enableAutoRange(True, True)
    
    roi.setZValue(10)
    vb1.addItem(roi)

    if isinstance(roi, pg.RectROI):
        if transpose:
            assert roi.getAffineSliceParams(data, img1, axes=(1, 2)) == ([28.0, 27.0], ((1.0, 0.0), (0.0, 1.0)), (1.0, 1.0))
        else:
            assert roi.getAffineSliceParams(data, img1, axes=(1, 2)) == ([27.0, 28.0], ((1.0, 0.0), (0.0, 1.0)), (1.0, 1.0))

    rgn = roi.getArrayRegion(data, img1, axes=(1, 2))
    #assert np.all((rgn == data[:, 1:-2, 1:-2, :]) | (rgn == 0))
    img2.setImage(rgn[0, ..., 0])
    vb2.setAspectLocked()
    vb2.enableAutoRange(True, True)
    
    app.processEvents()
    assertImageApproved(win, name+'/roi_getarrayregion', 'Simple ROI region selection.')

    with pytest.raises(TypeError):
        roi.setPos(0, False)

    roi.setPos([0.5, 1.5])
    rgn = roi.getArrayRegion(data, img1, axes=(1, 2))
    img2.setImage(rgn[0, ..., 0])
    app.processEvents()
    assertImageApproved(win, name+'/roi_getarrayregion_halfpx', 'Simple ROI region selection, 0.5 pixel shift.')

    roi.setAngle(45)
    roi.setPos([3, 0])
    rgn = roi.getArrayRegion(data, img1, axes=(1, 2))
    img2.setImage(rgn[0, ..., 0])
    app.processEvents()
    assertImageApproved(win, name+'/roi_getarrayregion_rotate', 'Simple ROI region selection, rotation.')

    if testResize:
        roi.setSize([60, 60])
        rgn = roi.getArrayRegion(data, img1, axes=(1, 2))
        img2.setImage(rgn[0, ..., 0])
        app.processEvents()
        assertImageApproved(win, name+'/roi_getarrayregion_resize', 'Simple ROI region selection, resized.')

    img1.scale(1, -1)
    img1.setPos(0, img1.height())
    img1.rotate(20)
    rgn = roi.getArrayRegion(data, img1, axes=(1, 2))
    img2.setImage(rgn[0, ..., 0])
    app.processEvents()
    assertImageApproved(win, name+'/roi_getarrayregion_img_trans', 'Simple ROI region selection, image transformed.')

    vb1.invertY()
    rgn = roi.getArrayRegion(data, img1, axes=(1, 2))
    img2.setImage(rgn[0, ..., 0])
    app.processEvents()
    assertImageApproved(win, name+'/roi_getarrayregion_inverty', 'Simple ROI region selection, view inverted.')

    roi.setState(initState)
    img1.resetTransform()
    img1.setPos(0, 0)
    img1.scale(1, 0.5)
    rgn = roi.getArrayRegion(data, img1, axes=(1, 2))
    img2.setImage(rgn[0, ..., 0])
    app.processEvents()
    assertImageApproved(win, name+'/roi_getarrayregion_anisotropic', 'Simple ROI region selection, image scaled anisotropically.')
    
    # allow the roi to be re-used
    roi.scene().removeItem(roi)
Exemple #9
0
def test_PolyLineROI():
    rois = [
        (pg.PolyLineROI([[0, 0], [10, 0], [0, 15]], closed=True, pen=0.3), 'closed'),
        (pg.PolyLineROI([[0, 0], [10, 0], [0, 15]], closed=False, pen=0.3), 'open')
    ]
    
    #plt = pg.plot()
    plt = pg.GraphicsView()
    plt.show()
    resizeWindow(plt, 200, 200)
    vb = pg.ViewBox()
    plt.scene().addItem(vb)
    vb.resize(200, 200)
    #plt.plotItem = pg.PlotItem()
    #plt.scene().addItem(plt.plotItem)
    #plt.plotItem.resize(200, 200)
    

    plt.scene().minDragTime = 0  # let us simulate mouse drags very quickly.

    # seemingly arbitrary requirements; might need longer wait time for some platforms..
    QtTest.QTest.qWaitForWindowShown(plt)
    QtTest.QTest.qWait(100)
    
    for r, name in rois:
        vb.clear()
        vb.addItem(r)
        vb.autoRange()
        app.processEvents()
        
        assertImageApproved(plt, 'roi/polylineroi/'+name+'_init', 'Init %s polyline.' % name)
        initState = r.getState()
        assert len(r.getState()['points']) == 3
        
        # hover over center
        center = r.mapToScene(pg.Point(3, 3))
        mouseMove(plt, center)
        assertImageApproved(plt, 'roi/polylineroi/'+name+'_hover_roi', 'Hover mouse over center of ROI.')
        
        # drag ROI
        mouseDrag(plt, center, center + pg.Point(10, -10), QtCore.Qt.LeftButton)
        assertImageApproved(plt, 'roi/polylineroi/'+name+'_drag_roi', 'Drag mouse over center of ROI.')
        
        # hover over handle
        pt = r.mapToScene(pg.Point(r.getState()['points'][2]))
        mouseMove(plt, pt)
        assertImageApproved(plt, 'roi/polylineroi/'+name+'_hover_handle', 'Hover mouse over handle.')
        
        # drag handle
        mouseDrag(plt, pt, pt + pg.Point(5, 20), QtCore.Qt.LeftButton)
        assertImageApproved(plt, 'roi/polylineroi/'+name+'_drag_handle', 'Drag mouse over handle.')
        
        # hover over segment 
        pt = r.mapToScene((pg.Point(r.getState()['points'][2]) + pg.Point(r.getState()['points'][1])) * 0.5)
        mouseMove(plt, pt+pg.Point(0, 2))
        assertImageApproved(plt, 'roi/polylineroi/'+name+'_hover_segment', 'Hover mouse over diagonal segment.')
        
        # click segment
        mouseClick(plt, pt, QtCore.Qt.LeftButton)
        assertImageApproved(plt, 'roi/polylineroi/'+name+'_click_segment', 'Click mouse over segment.')

        # drag new handle
        mouseMove(plt, pt+pg.Point(10, -10)) # pg bug: have to move the mouse off/on again to register hover
        mouseDrag(plt, pt, pt + pg.Point(10, -10), QtCore.Qt.LeftButton)
        assertImageApproved(plt, 'roi/polylineroi/'+name+'_drag_new_handle', 'Drag mouse over created handle.')
        
        # clear all points
        r.clearPoints()
        assertImageApproved(plt, 'roi/polylineroi/'+name+'_clear', 'All points cleared.')
        assert len(r.getState()['points']) == 0
        
        # call setPoints
        r.setPoints(initState['points'])
        assertImageApproved(plt, 'roi/polylineroi/'+name+'_setpoints', 'Reset points to initial state.')
        assert len(r.getState()['points']) == 3
        
        # call setState
        r.setState(initState)
        assertImageApproved(plt, 'roi/polylineroi/'+name+'_setstate', 'Reset ROI to initial state.')
        assert len(r.getState()['points']) == 3
Exemple #10
0
def check_getArrayRegion(roi, name, testResize=True):
    initState = roi.getState()
    
    #win = pg.GraphicsLayoutWidget()
    win = pg.GraphicsView()
    win.show()
    win.resize(200, 400)
    
    # Don't use Qt's layouts for testing--these generate unpredictable results.
    #vb1 = win.addViewBox()
    #win.nextRow()
    #vb2 = win.addViewBox()
    
    # Instead, place the viewboxes manually 
    vb1 = pg.ViewBox()
    win.scene().addItem(vb1)
    vb1.setPos(6, 6)
    vb1.resize(188, 191)

    vb2 = pg.ViewBox()
    win.scene().addItem(vb2)
    vb2.setPos(6, 203)
    vb2.resize(188, 191)
    
    img1 = pg.ImageItem(border='w')
    img2 = pg.ImageItem(border='w')
    vb1.addItem(img1)
    vb2.addItem(img2)
    
    np.random.seed(0)
    data = np.random.normal(size=(7, 30, 31, 5))
    data[0, :, :, :] += 10
    data[:, 1, :, :] += 10
    data[:, :, 2, :] += 10
    data[:, :, :, 3] += 10
    
    img1.setImage(data[0, ..., 0])
    vb1.setAspectLocked()
    vb1.enableAutoRange(True, True)
    
    roi.setZValue(10)
    vb1.addItem(roi)

    rgn = roi.getArrayRegion(data, img1, axes=(1, 2))
    assert np.all((rgn == data[:, 1:-2, 1:-2, :]) | (rgn == 0))
    img2.setImage(rgn[0, ..., 0])
    vb2.setAspectLocked()
    vb2.enableAutoRange(True, True)
    
    app.processEvents()
    
    assertImageApproved(win, name+'/roi_getarrayregion', 'Simple ROI region selection.')

    with pytest.raises(TypeError):
        roi.setPos(0, False)

    roi.setPos([0.5, 1.5])
    rgn = roi.getArrayRegion(data, img1, axes=(1, 2))
    img2.setImage(rgn[0, ..., 0])
    app.processEvents()
    assertImageApproved(win, name+'/roi_getarrayregion_halfpx', 'Simple ROI region selection, 0.5 pixel shift.')

    roi.setAngle(45)
    roi.setPos([3, 0])
    rgn = roi.getArrayRegion(data, img1, axes=(1, 2))
    img2.setImage(rgn[0, ..., 0])
    app.processEvents()
    assertImageApproved(win, name+'/roi_getarrayregion_rotate', 'Simple ROI region selection, rotation.')

    if testResize:
        roi.setSize([60, 60])
        rgn = roi.getArrayRegion(data, img1, axes=(1, 2))
        img2.setImage(rgn[0, ..., 0])
        app.processEvents()
        assertImageApproved(win, name+'/roi_getarrayregion_resize', 'Simple ROI region selection, resized.')

    img1.scale(1, -1)
    img1.setPos(0, img1.height())
    img1.rotate(20)
    rgn = roi.getArrayRegion(data, img1, axes=(1, 2))
    img2.setImage(rgn[0, ..., 0])
    app.processEvents()
    assertImageApproved(win, name+'/roi_getarrayregion_img_trans', 'Simple ROI region selection, image transformed.')

    vb1.invertY()
    rgn = roi.getArrayRegion(data, img1, axes=(1, 2))
    img2.setImage(rgn[0, ..., 0])
    app.processEvents()
    assertImageApproved(win, name+'/roi_getarrayregion_inverty', 'Simple ROI region selection, view inverted.')

    roi.setState(initState)
    img1.resetTransform()
    img1.setPos(0, 0)
    img1.scale(1, 0.5)
    rgn = roi.getArrayRegion(data, img1, axes=(1, 2))
    img2.setImage(rgn[0, ..., 0])
    app.processEvents()
    assertImageApproved(win, name+'/roi_getarrayregion_anisotropic', 'Simple ROI region selection, image scaled anisotropically.')
def test_ImageItem(transpose=False):
    
    w = pg.GraphicsWindow()    
    view = pg.ViewBox()
    w.setCentralWidget(view)
    w.resize(200, 200)
    w.show()
    img = TransposedImageItem(border=0.5, transpose=transpose)

    view.addItem(img)
    
    # test mono float
    np.random.seed(0)
    data = np.random.normal(size=(20, 20))
    dmax = data.max()
    data[:10, 1] = dmax + 10
    data[1, :10] = dmax + 12
    data[3, :10] = dmax + 13
    img.setImage(data)
    
    QtTest.QTest.qWaitForWindowShown(w)
    time.sleep(0.1)
    app.processEvents()
    assertImageApproved(w, 'imageitem/init', 'Init image item. View is auto-scaled, image axis 0 marked by 1 line, axis 1 is marked by 2 lines. Origin in bottom-left.')
    
    # ..with colormap
    cmap = pg.ColorMap([0, 0.25, 0.75, 1], [[0, 0, 0, 255], [255, 0, 0, 255], [255, 255, 0, 255], [255, 255, 255, 255]])
    img.setLookupTable(cmap.getLookupTable())
    assertImageApproved(w, 'imageitem/lut', 'Set image LUT.')
    
    # ..and different levels
    img.setLevels([dmax+9, dmax+13])
    assertImageApproved(w, 'imageitem/levels1', 'Levels show only axis lines.')

    img.setLookupTable(None)

    # test mono int
    data = np.fromfunction(lambda x,y: x+y*10, (129, 128)).astype(np.int16)
    img.setImage(data)
    assertImageApproved(w, 'imageitem/gradient_mono_int', 'Mono int gradient.')
    
    img.setLevels([640, 641])
    assertImageApproved(w, 'imageitem/gradient_mono_int_levels', 'Mono int gradient w/ levels to isolate diagonal.')

    # test mono byte
    data = np.fromfunction(lambda x,y: x+y, (129, 128)).astype(np.ubyte)
    img.setImage(data)
    assertImageApproved(w, 'imageitem/gradient_mono_byte', 'Mono byte gradient.')
    
    img.setLevels([127, 128])
    assertImageApproved(w, 'imageitem/gradient_mono_byte_levels', 'Mono byte gradient w/ levels to isolate diagonal.')

    # test monochrome image
    data = np.zeros((10, 10), dtype='uint8')
    data[:5,:5] = 1
    data[5:,5:] = 1
    img.setImage(data)
    assertImageApproved(w, 'imageitem/monochrome', 'Ubyte image with only 0,1 values.')
    
    # test bool
    data = data.astype(bool)
    img.setImage(data)
    assertImageApproved(w, 'imageitem/bool', 'Boolean mask.')

    # test RGBA byte
    data = np.zeros((100, 100, 4), dtype='ubyte')
    data[..., 0] = np.linspace(0, 255, 100).reshape(100, 1)
    data[..., 1] = np.linspace(0, 255, 100).reshape(1, 100)
    data[..., 3] = 255
    img.setImage(data)
    assertImageApproved(w, 'imageitem/gradient_rgba_byte', 'RGBA byte gradient.')
    
    img.setLevels([[128, 129], [128, 255], [0, 1], [0, 255]])
    assertImageApproved(w, 'imageitem/gradient_rgba_byte_levels', 'RGBA byte gradient. Levels set to show x=128 and y>128.')
    
    # test RGBA float
    data = data.astype(float)
    img.setImage(data / 1e9)
    assertImageApproved(w, 'imageitem/gradient_rgba_float', 'RGBA float gradient.')

    # checkerboard to test alpha
    img2 = TransposedImageItem(transpose=transpose)
    img2.setImage(np.fromfunction(lambda x,y: (x+y)%2, (10, 10)), levels=[-1,2])
    view.addItem(img2)
    img2.scale(10, 10)
    img2.setZValue(-10)
    
    data[..., 0] *= 1e-9
    data[..., 1] *= 1e9
    data[..., 3] = np.fromfunction(lambda x,y: np.sin(0.1 * (x+y)), (100, 100))
    img.setImage(data, levels=[[0, 128e-9],[0, 128e9],[0, 1],[-1, 1]])
    assertImageApproved(w, 'imageitem/gradient_rgba_float_alpha', 'RGBA float gradient with alpha.')    

    # test composition mode
    img.setCompositionMode(QtGui.QPainter.CompositionMode_Plus)
    assertImageApproved(w, 'imageitem/gradient_rgba_float_additive', 'RGBA float gradient with alpha and additive composition mode.')    
    
    img2.hide()
    img.setCompositionMode(QtGui.QPainter.CompositionMode_SourceOver)
    
    # test downsampling
    data = np.fromfunction(lambda x,y: np.cos(0.002 * x**2), (800, 100))
    img.setImage(data, levels=[-1, 1])
    assertImageApproved(w, 'imageitem/resolution_without_downsampling', 'Resolution test without downsampling.')
    
    img.setAutoDownsample(True)
    assertImageApproved(w, 'imageitem/resolution_with_downsampling_x', 'Resolution test with downsampling axross x axis.')
    assert img._lastDownsample == (4, 1)
    
    img.setImage(data.T, levels=[-1, 1])
    assertImageApproved(w, 'imageitem/resolution_with_downsampling_y', 'Resolution test with downsampling across y axis.')
    assert img._lastDownsample == (1, 4)
    
    view.hide()