Home > Software design >  How can i extract out the coordinates (top, bottom, left, right) of white mask (polygon) in image?
How can i extract out the coordinates (top, bottom, left, right) of white mask (polygon) in image?

Time:09-29

I am trying to extract out the coordinates (x, y) of binary image. I need the top, bottom, left right (x, y) points of the white mask which is i guess is polygon. The image shown below , how can i take out the points ?

Image: enter image description here

import cv2
import numpy as np

# read image
img = cv2.imread('white_blob.png')

# Method 1: bounding rect

# threshold on white
lower =(255,255,255)
upper = (255,255,255)
thresh = cv2.inRange(img, lower, upper)

# get points
points = np.column_stack(np.where(thresh.transpose() > 0))
x,y,w,h = cv2.boundingRect(points)
print(x,y,w,h)
min = (x,y)
max = (x w-1,y h-1)
print("min:", min)
print("max:", max)

# Method 2: Numpy
(Note: Numpy coordinates are y,x. So need to rearrange)

a = np.where(img != 0)
x1,y1,x2,y2 = np.min(a[1]), np.min(a[0]), np.max(a[1]), np.max(a[0])
min = (x1,y1)
max = (x2,y2)
print("min:", min)
print("max:", max)

Both methods produce (x,y):

min: (0, 293)
max: (127, 363)
  • Related