Home > Software design >  Finding position of biggest section of green pixels in numpy
Finding position of biggest section of green pixels in numpy

Time:12-31

I have a program that creates a mask for green pixels in a screenshot (img). I need to get the approximate location of the biggest section of these pixels within the image. What would be the best way to get this info?

The image: eggnog  just after starting a match

My code for getting the mask (np is numpy, cv2 is OpenCV):

# define the list of color boundaries
boundaries = [
    ([0, 100, 0], [100, 255, 100]), # green
]

# loop over the boundaries
for (lower, upper) in boundaries:
    # create NumPy arrays from the boundaries
    lower = np.array(lower, dtype = "uint8")
    upper = np.array(upper, dtype = "uint8")
    # find the colors within the specified boundaries and apply the mask
    mask = cv2.inRange(img, lower, upper)
    output = cv2.bitwise_and(img, img, mask = mask)

CodePudding user response:

You can get the bounding rect of the biggest green area using cv2.findContours combined with cv2.boundingRect

import cv2

img = cv2.imread('game.png')
mask = cv2.inRange(img, (0, 100, 0), (100, 255, 100))

contours, _ = cv2.findContours(mask, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)
rects = map(cv2.boundingRect, contours)

# f[2] = width, f[3] = height
biggest = max(rects, key=lambda f: f[2]*f[3])

cv2.rectangle(img, biggest, (255, 0, 0),  2)

Result:

enter image description here

  • Related