some nooby questions
some nooby questions

Reputation: 693

Get array of coordinates of all white pixels of separated objects on picture OpenCV Python

I hava a image of white objects on black backgorund. How can I get array of coordinates of all white pixels of separated objects on picture? I am using OpenCV and Python.

If I have an matrix like this (1=255):

  m = np.array([
            [1,1,0,1,1],
            [1,1,0,1,1],
            [1,0,0,0,0],
            [0,0,0,1,1],
            [0,0,0,1,1],])

I should get matrix of coordinates like this:

[
[(0,0),(0,1),(1,0),(1,1),(2,0)]
[(0,3),(0,4),(1,3),(1,4)]
[(3,3),(3,4),(4,3),(4,4)]
]

I know there is a function findContoures (and I was using this: cnts = cv2.findContours(m, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)) but it doesn't give me all coordinates.

enter image description here

Upvotes: 3

Views: 1430

Answers (2)

fana
fana

Reputation: 1870

Maybe you can consider using connectedComponents instead of findContoures.

Upvotes: 1

Matt Hall
Matt Hall

Reputation: 8112

I don't totally follow the structure of the expected output but np.argwhere can probably do what you want. For example, this:

np.argwhere(m == 1)

Gives you this:

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

Upvotes: 2

Related Questions