Scipy filter with multi-dimensional (or non-scalar) output

2024/10/1 17:18:18

Is there a filter similar to ndimage's generic_filter that supports vector output? I did not manage to make scipy.ndimage.filters.generic_filter return more than a scalar. Uncomment the line in the code below to get the error: TypeError: only length-1 arrays can be converted to Python scalars.

I'm looking for a generic filter that process 2D or 3D arrays and returns a vector at each point. Thus the output would have one added dimension. For the example below I'd expect something like this:

m.shape    # (10,10)
res.shape  # (10,10,2)

Example Code

import numpy as np
from scipy import ndimagea = np.ones((10, 10)) * np.arange(10)footprint = np.array([[1,1,1],[1,0,1],[1,1,1]])def myfunc(x):r = sum(x)#r = np.array([1,1])  # uncomment thisreturn rres = ndimage.generic_filter(a, myfunc, footprint=footprint)
Answer

The generic_filter expects myfunc to return a scalar, never a vector. However, there is nothing that precludes myfunc from also adding information to, say, a list which is passed to myfunc as an extra argument.

Instead of using the array returned by generic_filter, we can generate our vector-valued array by reshaping this list.


For example,

import numpy as np
from scipy import ndimagea = np.ones((10, 10)) * np.arange(10)footprint = np.array([[1,1,1],[1,0,1],[1,1,1]])ndim = 2
def myfunc(x, out):r = np.arange(ndim, dtype='float64')out.extend(r)return 0result = []
ndimage.generic_filter(a, myfunc, footprint=footprint, extra_arguments=(result,))
result = np.array(result).reshape(a.shape+(ndim,))
https://en.xdnf.cn/q/70947.html

Related Q&A

How do I stop execution inside exec command in Python 3?

I have a following code:code = """ print("foo")if True: returnprint("bar") """exec(code) print(This should still be executed)If I run it I get:Tracebac…

sqlalchemy concurrency update issue

I have a table, jobs, with fields id, rank, and datetime started in a MySQL InnoDB database. Each time a process gets a job, it "checks out" that job be marking it started, so that no other p…

Python matplotlib: Change axis labels/legend from bold to regular weight

Im trying to make some publication-quality plots, but I have encountered a small problem. It seems by default that matplotlib axis labels and legend entries are weighted heavier than the axis tick mark…

Negative extra_requires in Python setup.py

Id like to make a Python package that installs a dependency by default unless the user specially signals they do not want that.Example:pip install package[no-django]Does current pip and setup.py mechan…

Get Type in Robot Framework

Could you tell me about how to get the variable type in Robot Framework.${ABC} Set Variable Test ${XYZ} Set Variable 1233Remark: Get the variable Type such as string, intget ${ABC} type = strin…

Keras 2, TypeError: cant pickle _thread.lock objects

I am using Keras to create an ANN and do a grid search on the network. I have encountered the following error while running the code below:model = KerasClassifier(build_fn=create_model(input_dim), verb…

How to remove minimize/maximize buttons while preserving the icon?

Is it possible to display the icon for my toplevel and root window after removing the minimize and maximize buttons? I tried using -toolwindow but the icon cant be displayed afterwards. Is there anoth…

Undefined reference to `PyString_FromString

I have this C code:... [SNIP] ... for(Node = Plugin.Head; Node != NULL; Node = Node->Next) {//Create new python sub-interpreterNode->Interpreter = Py_NewInterpreter();if(Node->Interpreter == N…

How to call a method from a different blueprint in Flask?

I have an application with multiple blueprinted modules.I would like to call a method (a route) that would normally return a view or render a template, from within a different blueprints route.How can …

Dynamically define functions with varying signature

What I want to accomplish:dct = {foo:0, bar:1, baz:2} def func(**dct):pass #function signature is now func(foo=0, bar=1, baz=2)However, the ** syntax is obviously clashing here between expanding a dict…