Treating 2d array data as pixels defining a shape - is it possible to create an inside and a surface?

131 views Asked by At

Say I have the following array/matrix in python (any language will do, to be honest). A =

[0 0 0 0 0 0 0 0 0 0
 0 0 1 1 1 1 0 0 0 0
 0 1 1 1 1 1 0 0 0 0
 0 1 1 1 1 1 1 0 0 0
 0 0 1 1 1 1 1 1 0 0
 0 0 1 1 1 1 1 0 0 0
 0 0 1 1 1 1 1 0 0 0
 0 0 0 1 1 1 0 0 0 0
 0 0 0 0 0 0 0 0 0 0
 0 0 0 0 0 0 0 0 0 0]

Is there any easy way to manipulate entries in this array as if they are pixels. Example, would there be any way to create an interior and a surface of arbitrary length, to get, for example:

[0 0 0 0 0 0 0 0 0 0
 0 0 1 1 1 1 0 0 0 0
 0 1 1 0 0 1 0 0 0 0
 0 1 1 0 0 0 1 0 0 0
 0 0 1 0 0 0 1 1 0 0
 0 0 1 0 0 0 1 0 0 0
 0 0 1 1 0 1 1 0 0 0
 0 0 0 1 1 1 0 0 0 0
 0 0 0 0 0 0 0 0 0 0
 0 0 0 0 0 0 0 0 0 0]

Perhaps there is some way to recursively solve this, or maybe in a different way, which would rely on the entries around each element. Any thoughts?

2

There are 2 answers

0
maddin45 On BEST ANSWER

You can just check the value and the direct neighborhood of every pixel: Your resulting image is 1 where:

  • the original value was 1
  • and at least one neighbor is 0

It is 0 everywhere else. The image below might help to illustrate what I mean:

  • The center pixel of th red block will stay 1, since it is 1 in the original image and has a neighboring 0.
  • The center pixel of the blue block will stay 0, since it was 0in the original image.
  • The center pixel of the green block is the interesting case: It was 1 in the original image, but all its neighbors are 1 as well. Thus it becomes 0 in the result.

enter image description here

Test these conditions for each array entry. Just be careful at the boundaries.

If you have access to an image processing library there is another approach you can take: create a copy of your image, errode it by one pixel and subtract it from the original.

0
kezzos On

This looks like you want edge detection. @maddin45 is right, but you could also use scikit-image for this, for example with a canny edge detector:

import numpy as np
from skimage import filters
import matplotlib.pyplot as plt

arr = np.array([[0,0,0,0,0],
                [0,1,1,1,0],
                [0,1,1,1,0],
                [0,1,1,1,0],
                [0,0,0,0,0]], dtype=np.float64)

plt.figure()
plt.imshow(filters.canny(arr), interpolation='nearest')
plt.show()

enter image description here