Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
402 views
in Technique[技术] by (71.8m points)

python - How to find top_left, top_right, bottom_left, right coordinates in 2d mask where cell has specified value?

I have 2D numpy array which is a mask from an image. Each cell has 0 or 1 value. So I would like to find top:left,right, bottom:left,right in an array where value is 1.

For example input array:

[00000]
[01110]
[01100]
[00000]

Expected output: (1,1), (1,3), (2,1), (2,2)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Using np.argwhere and itertools.product:

import numpy as np
from itertools import product

def corners(np_array):
    ind = np.argwhere(np_array)
    res = []
    for f1, f2 in product([min,max], repeat=2):
        res.append(f1(ind[ind[:, 0] == f2(ind[:, 0])], key=lambda x:x[1]))
    return res
corners(arr)

Output:

[array([1, 1], dtype=int64),
 array([2, 1], dtype=int64),
 array([1, 3], dtype=int64),
 array([2, 2], dtype=int64)]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...