Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

numpy

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)

like image 935
eugenn Avatar asked May 15 '19 13:05

eugenn


3 Answers

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)]
like image 140
Chris Avatar answered Sep 30 '22 07:09

Chris


xy=np.array([[0,0,0,0,0],[0,1,1,1,0],[0,1,1,0,0],[0,0,0,0,0]])
x,y=np.where(xy==1)
tl_i=np.argmin(x)
tl=[x[tl_i],y[tl_i]]
tr_i=np.argmax(y)
tr=[x[tr_i],y[tr_i]]
bl_i=np.argmax(x)
bl=[x[bl_i],y[bl_i]]
br_i=len(x)-1-np.argmax(np.flip(x))
br=[x[br_i],y[br_i]]
like image 27
Aly Hosny Avatar answered Sep 30 '22 05:09

Aly Hosny


You can use the numpy.amax operation for finding max values in a multi_dimensional array. As below

def corners_v2(np_array):
    max_values = np.amax(np_array)
    result = np.where(np_array == np.amax(np_array))
    x1 = np.min(result[0])
    x2 = np.max(result[0])
    y1 = np.min(result[1])
    y2 = np.max(result[1])
    return x1, y1, x2, y2
like image 32
Faiz Ul Wahab Avatar answered Sep 30 '22 05:09

Faiz Ul Wahab