如何使用opencv或任何其他python库找到红色区域的宽度?

问题描述 投票:0回答:1

上面的红色图片是游戏中敌方单位的生命值。我有一个可以截屏的 python 应用程序,它必须能够确定剩余生命值的百分比。在本例中,考虑到红条的大小,该值约为 70%。我尝试了谷歌 Bard AI 建议中的几种方法,但没有一个 100% 有效。我该怎么办?

python opencv image-processing computer-vision game-automation
1个回答
0
投票

这是在 Python/OpenCV 中执行此操作的一种方法。只需使用 cv2.inRange() 进行阈值处理。然后从阈值图像中获取白色区域的边界框。然后获取边界框的宽度占图像宽度的百分比。

输入:

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)

阈值图像:

文本输出:

percent width: 60.13986013986014
© www.soinside.com 2019 - 2024. All rights reserved.