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

uidvcgyl  于 6个月前  发布在  其他
关注(0)|答案(1)|浏览(58)

x1c 0d1x的数据
上面的红色图像是游戏中敌方单位的生命值。我得到了一个python应用程序,它可以截图,它必须能够确定剩余生命的百分比。在这种情况下,它将是~ 70%,考虑到红色条的大小。我尝试了谷歌Bard AI建议的几种方法,但没有100%有效。我应该如何进行?

i5desfxk

i5desfxk1#

这里有一种在Python/OpenCV中实现的方法。只需使用cv2.inRange()阈值。然后从阈值图像中获取白色区域的边界框。然后获取边界框的宽度占图像宽度的百分比。
输入:
x1c 0d1x的数据

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

相关问题