我不知道如何找到具有相同像素的区域并获取这些区域的坐标?我尝试循环遍历所有像素,但时间太长了。
整个代码
from PIL import Image, ImageChops
from pathlib import Path
from mss import mss
import numpy as np
import pyautogui
import keyboard
import time
class Object_search:
def __init__(self):
self.BASE_DIR = Path(__file__).resolve().parent
def screenshot(self):
image_1 = pyautogui.screenshot(region = (0, 0, 1920, 1080))
time.sleep(0.1)
image_2 = pyautogui.screenshot(region = (0, 0, 1920, 1080))
return image_1, image_2
def comparison(self, image_1, image_2):
result = ImageChops.difference(image_1, image_2)
result = result.convert('L')
result = result.point(lambda x: 0 if x < 1 else 255, '1')
result.save(r'{}\data\screenshot\screen.png'.format(self.BASE_DIR))
return result
while True:
if keyboard.is_pressed('5'):
print('screenshot')
image = Object_search().screenshot()
time.sleep(0.1)
elif keyboard.is_pressed('6'):
print('comparison')
comparison = Object_search().comparison(image[0], image[1])
time.sleep(0.1)
elif keyboard.is_pressed('8'):
print('exit')
time.sleep(0.1)```


在 OpenCV 中,我会这样做 - 使用形态闭合变换 (
closing = dilation + erosion) 将对象的分散像素合并在一起。然后选择连接的组件,每个组件都有一个可用的周围矩形。PIL中可能存在类似的东西