Determine adjacent regions in numpy array

2024/11/10 7:10:14

I am looking for the following. I have a numpy array which is labeled as regions. The numpy array represents a segmented image. A region is a number of adjacent cells with the same value. Each region has its own unique value. A simplified version with 3 regions would look like this:

x = np.array([[1, 1, 1], [1, 1, 2], [2, 2, 2], [3, 3, 3]], np.int32)

output:

array([[1, 1, 1],[1, 1, 2],[2, 2, 2],[3, 3, 3]])

In the above example we have 3 separate regions, each labeled with an unique value (1,2,3 in this case).

What I want is the value of adjacent (neighbor) regions for each individual region. So in this case:

  • Region 1 is adjacent to region 2
  • Region 2 is adjacent to region 1 and 3
  • Region 3 is adjacent to region 2

What would be the most elegant and fastest way of achieving this?

Many thanks!

Answer

I understand that the task is to return all distinct entries of the array that are adjacent to a given number (such as 2). One way to achieve this with NumPy methods is to use roll to shift the given region by one unit up, down, left, and right. The logical OR of the shifted regions is taken, and all distinct elements that match this condition are returned. It then remains to remove the region itself, since it's not considered its own neighbor.

Since roll re-introduces the values that move beyond array's bounds at the opposite ends (which is not desired here), an additional step is to replace this row or column with False.

import numpy as npx = np.array([[1, 1, 1], [1, 1, 2], [2, 2, 2], [3, 3, 3]], np.int32)
region = 2   # number of region whose neighbors we wanty = x == region  # convert to Booleanrolled = np.roll(y, 1, axis=0)          # shift down
rolled[0, :] = False             
z = np.logical_or(y, rolled)rolled = np.roll(y, -1, axis=0)         # shift up 
rolled[-1, :] = False
z = np.logical_or(z, rolled)rolled = np.roll(y, 1, axis=1)          # shift right
rolled[:, 0] = False
z = np.logical_or(z, rolled)rolled = np.roll(y, -1, axis=1)         # shift left
rolled[:, -1] = False
z = np.logical_or(z, rolled)neighbors = set(np.unique(np.extract(z, x))) - set([region])
print(neighbors)
https://en.xdnf.cn/q/72206.html

Related Q&A

Python: win32gui.SetForegroundWindow

I have just written simple script to launch an applciation and I am trying to use "SendKeys" module to send keystrokes to this application. There is one "Snapshot" button, but I can…

Building PyCrypto with fastmath (gmp or mpir) via pip on Windows

I installed PyCrypto on Windows via pip but i was not able to build Crypto.PublicKey._fastmath because GMP was not found.I know there is a binary version on voidspace but i would like to build the late…

Get name of current test in setup using nose

I am currently writing some functional tests using nose. The library I am testing manipulates a directory structure. To get reproducible results, I store a template of a test directory structure and cr…

python: find html tags and replace their attributes [duplicate]

This question already has answers here:Replace SRC of all IMG elements using Parser(2 answers)Closed 10 years ago.I need to do the following:take html document find every occurrence of img tag take the…

Django/Apache/mod_wsgi not using virtualenvs Python binary

I have a virtualenv at /opt/webapps/ff/ with its own Python installation. I have WSGIPythonHome set to /opt/webapps/ff in my Apache config file (and this is definitely getting used in some capacity, b…

How to open the users preferred mail application on Linux?

I wrote a simple native GUI script with python-gtk. Now I want to give the user a button to send an email with an attachment.The script runs on Linux desktops. Is there a way to open the users preferr…

finding a set of ranges that a number fall in

I have a 200k lines list of number ranges like start_position,stop position. The list includes all kinds of overlaps in addition to nonoverlapping ones.the list looks like this[3,5] [10,30] [15,25] [5…

Python Tornado Websocket Connections still open after being closed

I have a Tornado Websocket Server and I want to time out after 30 minutes of inactivity. I use self.close() to close the connection after 30 minutes of inactivity. But it seems that some connections st…

Vertical Print String - Python3.2

Im writing a script that will take as user inputed string, and print it vertically, like so:input = "John walked to the store"output = J w t t so a o h th l e on k re edIve written …

How to remove small particle background noise from an image?

Im trying to remove gradient background noise from the images I have. Ive tried many ways with cv2 without success.Converting the image to grayscale at first to make it lose some gradients that may hel…