'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.
Solution 1:[1]
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]])
Solution 2:[2]
Maybe you can consider using connectedComponents instead of findContoures.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | fmw42 |
| Solution 2 | fana |

