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

uidvcgyl  于 2023-11-22  发布在  其他
关注(0)|答案(1)|浏览(192)

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

i5desfxk

i5desfxk1#

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

  1. import cv2
  2. import numpy as np
  3. # read input
  4. img = cv2.imread('red_bar.png')
  5. hh, ww = img.shape[:2]
  6. # threshold on red
  7. lower=(0,0,140)
  8. upper=(40,40,220)
  9. thresh = cv2.inRange(img, lower, upper)
  10. # get bounding box
  11. x,y,w,h = cv2.boundingRect(thresh)
  12. # print width of red as percent of width of image
  13. width = 100*(w-x)/ww
  14. print("percent width:", width)
  15. # save results
  16. cv2.imwrite('red_bar_thresh.png', thresh)
  17. # show results
  18. cv2.imshow('thresh', thresh)
  19. cv2.waitKey(0)

字符串
保留图像:



文本输出:

  1. percent width: 60.13986013986014

展开查看全部

相关问题