How to use 2-d numpy array with interactive panel floatslider for a python image Plot?

Asked

Viewed 32 times

-2

Using holloviews and panel. How to create a function that takes as arguments an np.array (2d, an array) and a "value cut". Return the 2d array plotted as image? Being what the argument "value cut" should be interactive (a Floatslider).

I tried in a few ways, but every time I put 2d array as argument of the function of an ex error:

**** Attempt 1 ****

Returns error: Valueerror: The Truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

###################

import numpy as np
import holoviews as hv
from holoviews import opts
hv.extension('bokeh')
import panel as pn
pn.extension()


mat = np.random.rand(50,50) #2d array

slider = pn.widgets.FloatSlider(start=0.0, end=2.0, value=0.5, name='Cota de Corte: ') #cria ao widget


def plota_imagem (M, slider_corte):

    corte = np.where(M <= slider_corte, M, np.nan)
    img = hv.Image(corte)
    return img


pn.interact(plota_imagem, M=mat, slider_corte=slider )

**** Attempt 2 ****

This way it works, but the 2d array is not as argument of the function and precise that it is.

##################

slider = pn.widgets.FloatSlider(start=0.0, end=1.0, value=0.5, name='Cota de Corte: ')

mat = np.random.rand(50,50) #2d array

def plota_imagem (slider_corte):

    corte = np.where(mat<=slider_corte, mat, np.nan)
    img = hv.Image(corte)
    return img

pn.interact(plota_imagem,slider_corte=slider )

#####################

Is there any solution for Attempt 1 to work, that is, array 2d (mat) is also a function argument?

1 answer

0

Imports:

import numpy as np
import holoviews as hv
from holoviews import opts
hv.extension('bokeh')
import panel as pn
pn.extension()

The way I found it was passed as a direct parameter in its plota_image function:

mat = np.random.rand(50,50)
slider = pn.widgets.FloatSlider(start=0.0, end=2.0, value=0.5, name='Cota de Corte: ') 

def plota_imagem (slider_corte, M = mat):

    corte = np.where(M <= slider_corte, M, np.nan)
    img = hv.Image(corte)
    return img

pn.interact(plota_imagem,slider_corte = slider)

This way any value of an np.random.Rand that you pass goes straight to the function.

def plota_imagem (slider_corte, M = mat)

Exit:

Saída

Browser other questions tagged

You are not signed in. Login or sign up in order to post.