问题描述
我正在尝试使用 mss 和 opencv 在屏幕上查找图像。但是,每当我尝试将区域与 mss 一起使用时,都会出现此错误:
这个问题似乎与一些资源没有被释放有关:python mss mss.exception.ScreenShotError:
我发现另一种解决方案是不使用区域并查看整个屏幕,但是为小图像找到正确的图像变得更加困难。另外,在修改区域坐标时,错误可能会无缘无故消失(例如不适用于600、600、1200、800,但适用于200、200、1200、800)。
test.py
from python_imagesearch.imagesearch import *
imagesearcharea("images/fermer.png",600,1200,800)
imagesearch.py
def region_grabber(region):
if is_retina: region = [n * 2 for n in region]
x1 = region[0]
y1 = region[1]
width = region[2]
height = region[3]
region = x1,y1,width,height
with mss.mss() as sct:
return sct.grab(region)
def imagesearcharea(image,x1,x2,y2,precision=0.8,im=None):
if im is None:
im = region_grabber(region=(x1,y2))
if is_retina:
im.thumbnail((round(im.size[0] * 0.5),round(im.size[1] * 0.5)))
img_rgb = np.array(im)
img_gray = cv2.cvtColor(img_rgb,cv2.COLOR_BGR2GRAY)
template = cv2.imread(image,0)
if template is None:
raise FileNotFoundError('Image file not found: {}'.format(image))
res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_norMED)
min_val,max_val,min_loc,max_loc = cv2.minMaxLoc(res)
if max_val < precision:
return [-1,-1]
return max_loc
我的mss版本是6.1,python是3.7,使用windows 10 您是否有任何解决方案的想法,或者您是否知道替代 mss 的替代库?
解决方法
经过数小时的调查,我没有找到任何解决方案来使其工作。 如果您使用 mss.grab,则 API 为grab(region),其中区域为 (x,y,width,length)。因此,x1 + 宽度不应大于您的屏幕分辨率,就像我的示例一样。
然而,考虑到这些信息,它仍然没有,所以我决定转移到另一个名为 PIL 的库。 我换了这个
with mss.mss() as sct:
sct.grab(region)
由此
ImageGrab.grab(bbox)
至少它有效