здраствуйте нужна помощь по коду вероятно ошибка связана с cv2 но я не могу её решить помогите!

Max_Lu

Новичок
Пользователь
Янв 21, 2024
1
0
1
вот сам код:
Python:
import cv2

import numpy as np

from skimage.metrics import structural_similarity as ssim

import pyautogui

import time

import os



def capture_screenshot(x, y, width, height):

screenshot = pyautogui.screenshot(region=(x, y, width, height))

screenshot = cv2.cvtColor(np.array(screenshot), cv2.COLOR_RGB2BGR)

return screenshot



def compare_images_ssim(img1, img2, threshold=0.9):

if img1 is None or img2 is None:

return False

    min_size = min(img1.shape[0], img1.shape[1], img2.shape[0], img2.shape[1])

win_size = min_size if min_size % 2 == 1 else min_size - 1

    if img1.shape != img2.shape:

img2 = cv2.resize(img2, (img1.shape[1], img1.shape[0]))

score, _ = ssim(img1, img2, win_size=win_size, full=True, multichannel=True)

return score > threshold



def send_message_to_chat(message):

print(f"Отправка сообщения в чат: {message}")



def main():

region = (1103, 414, 1151, 898)

if not os.path.isfile('normal_screenshot.png'):

print("Ошибка: Файл normal_screenshot.png не найден.")

return



    reference_screenshot = cv2.imread('normal_screenshot.png', cv2.IMREAD_COLOR)



while True:

        current_screenshot = capture_screenshot(*region)

changes_detected = not compare_images_ssim(reference_screenshot, current_screenshot)



if changes_detected:

send_message_to_chat("Обнаружены изменения в указанной области.")



time.sleep(1)



if __name__ == "__main__":

    main()




вот ошибка что он выдаёт:
C:\Users\Max\PycharmProjects\pixelcheck\venv\Scripts\python.exe C:\Users\Max\PycharmProjects\pixelcheck\ыы.py
Traceback (most recent call last):
File "C:\Users\Max\PycharmProjects\pixelcheck\ыы.py", line 44, in <module>
main()
File "C:\Users\Max\PycharmProjects\pixelcheck\ыы.py", line 36, in main
changes_detected = not compare_images_ssim(reference_screenshot, current_screenshot)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Max\PycharmProjects\pixelcheck\ыы.py", line 20, in compare_images_ssim
score, _ = ssim(img1, img2, win_size=win_size, full=True, multichannel=True)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Max\PycharmProjects\pixelcheck\venv\Lib\site-packages\skimage\metrics\_structural_similarity.py", line 178, in structural_similarity
raise ValueError(
ValueError: win_size exceeds image extent. Either ensure that your images are at least 7x7; or pass win_size explicitly in the function call, with an odd value less than or equal to the smaller side of your images. If your images are multichannel (with color channels), set channel_axis to the axis number corresponding to the channels.

Process finished with exit code 1
 
Последнее редактирование:

hellscoder

Новичок
Пользователь
Янв 28, 2024
12
1
3
Python:
import cv2
import numpy as np
from skimage.metrics import structural_similarity as ssim
import pyautogui
import time
import os

def capture_screenshot(x, y, width, height):
    # Captures a screenshot of a specified region
    screenshot = pyautogui.screenshot(region=(x, y, width, height))
    screenshot = cv2.cvtColor(np.array(screenshot), cv2.COLOR_RGB2BGR)
    return screenshot

def compare_images_ssim(img1, img2, threshold=0.9):
    # Compares two images using SSIM
    if img1 is None or img2 is None:
        return False

    # Ensuring the window size is odd
    min_size = min(img1.shape[0], img1.shape[1], img2.shape[0], img2.shape[1])
    win_size = min_size if min_size % 2 == 1 else min_size - 1

    # Resize img2 to match img1's shape if different
    if img1.shape != img2.shape:
        img2 = cv2.resize(img2, (img1.shape[1], img1.shape[0]))

    score, _ = ssim(img1, img2, win_size=win_size, full=True, multichannel=True)
    return score > threshold

def send_message_to_chat(message):
    # Placeholder for sending a message
    print(f"Sending message to chat: {message}")

def main():
    region = (1103, 414, 1151, 898)

    # Check if reference image file exists
    if not os.path.isfile('normal_screenshot.png'):
        print("Error: File normal_screenshot.png not found.")
        return

    try:
        reference_screenshot = cv2.imread('normal_screenshot.png', cv2.IMREAD_COLOR)
    except Exception as e:
        print(f"Error reading file: {e}")
        return

    while True:
        current_screenshot = capture_screenshot(*region)
        changes_detected = not compare_images_ssim(reference_screenshot, current_screenshot)

        if changes_detected:
            send_message_to_chat("Changes detected in the specified region.")

        time.sleep(1)

if __name__ == "__main__":
    main()
 

Форум IT Специалистов