pythonopencvimage-processingcomputer-visiongame-automation

How to find the width of the red area using opencv or any other python library?


enter image description here

The red image above is the health meter for enemy units in a game. I got a python application that takes a screenshot and it must be able to determine the percentage of health remaining. In this case it would be ~70%, given the size of the red bar. I tried several ways from google Bard AI suggestions but none work 100%. How should I proceed?


Solution

  • Here is one way to do that in Python/OpenCV. Just threshold using cv2.inRange(). Then get the bounding box of the white region from the thresholded image. Then get the width of the bounding box as a percentage of the width of the image.

    Input:

    enter image description here

    import cv2
    import numpy as np
    
    # read input
    img = cv2.imread('red_bar.png')
    hh, ww = img.shape[:2]
    
    # threshold on red
    lower=(0,0,140)
    upper=(40,40,220)
    thresh = cv2.inRange(img, lower, upper)
    
    # get bounding box
    x,y,w,h = cv2.boundingRect(thresh)
    
    # print width of red as percent of width of image
    width = 100*(w-x)/ww
    print("percent width:", width)
    
    # save results
    cv2.imwrite('red_bar_thresh.png', thresh)
    
    # show results
    cv2.imshow('thresh', thresh)
    cv2.waitKey(0)
    

    Thresholded Image:

    enter image description here

    Text Output:

    percent width: 60.13986013986014