numpy get 2d array where last dimension is indexed according to a 2d array

2024/10/13 15:25:28

I did read on numpy indexing but I didn't find what I was looking for.

I have a 288*384 image, where each pixel can have a labelling in [0,15]. It is stored in a 3d (288,384,16)-shaped numpy array im.

With im[:,:,1], I can for example get the image where all pixels have the label 1.

I have another 2d array labelling, (288*384)-shaped, containing a label for each pixel.

How do I get the image where each pixel has the corresponding pixel using some clever slicing?

Using loops, that would be:

result = np.zeros((288,384))
for x,y in zip(range(288), range(384)):result[x,y] = im[x,y,labelling[x,y]]

But this is of course inefficient.

Answer

New Result

The short result is

np.choose(labelling,im.transpose(2,0,1))

Old Result

Try this

im[np.arange(288)[:,None],np.arange(384)[None,:],labelling]

It works for the following situation:

import numpy
import numpy.random
import itertoolsa = numpy.random.randint(5,size=(2,3,4))
array([[[4, 4, 0, 0],[0, 4, 1, 1],[3, 4, 4, 2]],[[4, 0, 0, 2],[1, 4, 2, 2],[4, 2, 4, 4]]])b = numpy.random.randint(4,size=(2,3))
array([[1, 1, 0],[1, 2, 2]])res = a[np.arange(2)[:,None],np.arange(3)[None,:],b]
array([[4, 4, 3],[0, 2, 4]])# note that zip is not doing what you expect it to do
result = np.zeros((2,3))
for x,y in itertools.product(range(2),range(3)):result[x,y] = a[x,y,b[x,y]]array([[4., 4., 3.],[0., 2., 4.]])

Note that zip is not doing what you expect

zip(range(2),range(3))
[(0, 0), (1, 1)]

Probably you meant something like itertools.product

list(itertools.product(range(2),range(3)))
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)]

The horribly looking [:,None] etc. can be avoided by using numpy.ix_

xx,yy = np.ix_( np.arange(2), np.arange(3) )res = a[xx,yy,b]
https://en.xdnf.cn/q/118064.html

Related Q&A

Error sending html email with mailgun python API

I can send text email with the Mailgun python API fine:def send_simple_message(mailtext, filename=""):requests.post("https://api.mailgun.net/v3/mydomain.in/messages",auth=("api…

How to take HTML user input and query it via Python SQL?

Is there a way to take user input from HTML, and use python to run the input through to a SQL database? Does the input need to be parsed? I want the the user to be able to type in a store name, and f…

Reading and taking specific file contents in a list in python

I have a file containing:name: Sam placing: 2 quote: Ill win.name: Jamie placing: 1 quote: Be the best.and I want to read the file through python and append specific contents into a list. I want my fir…

Scipy / ctypes build-config: How to load lib?

These docs have a nice example on how to compile some external C/C++ code and load this using ctypes. This works great with manual compilation (where im controlling the names of my library which later …

Webfaction Django 1.4.1: easy_thumbnails 3.0b – Couldnt get the thumbnail error

I use easy_thumbnails and it works fine on a development machine but in production I get errors like shown below, when I use {% thumbnail photo.image 300x170 %} templatetag. Though can directly browse …

acronym replacement with its value using python

i have dictionary like that i need to replace acronyms in text with its value in dictionary i use this code but it doesnt give me the appropriate result when i test the function using acronyms("we…

Grako - How to do error handling?

How do I do error handling with Grako?EBNF (MyGrammar.ebnf):pattern = { tag | function }* ; tag = tag:( "%" name:id "%" ); function = function:("$" name:id "…

How get the softlayer storage credendials?

Im trying to get the Username,password and host IQN of a authorized Softlayer Network Storage. I used this python script, but the shell returns []import SoftLayerAPI_USERNAME = xxxAPI_KEY = yyyystorage…

dopy.manager.DoError: Unable to authenticate you

Im trying to configure a Virtual Machine(with Vagrant and Ansible), that needs a file.py to the full correct configuration of this machine (according to the book that Im studying),Im was using the Digi…

subprocess.Popen: OSError: [Errno 2] No such file or directory only on Linux

This is not a duplicate of subprocess.Popen: OSError: [Errno 13] Permission denied only on Linux as that problem occurred due to wrong permissions. That has been fixed and this is an entirely different…