为什么我的 Python 代码执行 if-else 语句之后的行、if-else 语句内的行之前的行?

问题描述 投票:0回答:1

我是Python编程的初学者。 我用 Chatgpt 编写了一个程序,我并不完全理解,但我知道我想制作更多的 if-else 语句,而不会使嵌套变得复杂。 除了将 if-else 后面的行放在 if-else 语句中之外,我还能做什么?

import pyautogui
import numpy as np
import cv2
import time

CountGooglyFound = 0

def take_screenshot():
    # Take a screenshot
    screenshot = pyautogui.screenshot()
    # Convert the screenshot to a numpy array for further processing
    screenshot_np = np.array(screenshot)
    return screenshot_np

def search_for_image(image_path, screenshot):
    # Load the image to search for
    image_to_search = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
    # Convert the screenshot to grayscale
    screenshot_gray = cv2.cvtColor(screenshot, cv2.COLOR_BGR2GRAY)
    # Ensure both images have the same data type and depth
    screenshot_gray = np.uint8(screenshot_gray)
    image_to_search = np.uint8(image_to_search)
    # Perform template matching
    result = cv2.matchTemplate(screenshot_gray, image_to_search, cv2.TM_CCOEFF_NORMED)
    # Set a threshold for matching
    threshold = 0.75
    # Get the location of matched regions
    locations = np.where(result >= threshold)
    # Check if the image is found
    if len(locations[0]) > 0:
        return True, list(zip(*locations[::-1]))  # Return coordinates of matched regions
    else:
        return False, None

def main():
    # Take a screenshot and store it in a variable
    screenshot = take_screenshot()

    # Path to the image to search for within the screenshot
    image_path = r'C:\Users\Iris\Desktop\ImageTest\Googly.png'

    # Search for the image within the screenshot
    found, locations = search_for_image(image_path, screenshot)

    if found:
        print("Image found at the following locations:")
        print(locations)
        # Click at point (500,500)
        pyautogui.click(500, 500)
        CountGooglyFound =+ 1
        print(CountGooglyFound)
    else:
        print("Image not found in the screenshot.")
        pyautogui.click(500, 50)
    
pyautogui.click(50, 500)
print(CountGooglyFound)

if __name__ == "__main__":
    main()

我尝试了这个,但是 pyautogui.click(50, 500) 和 print(CountGooglyFound) 在 if 或 else 语句中执行。其他一切似乎都运行顺利,因为它可以检测到图像或不检测到它。

python windows if-statement python-3.9
1个回答
0
投票

您首先得到这 2 部分是因为在调用您的

main()
之前执行请求。为了避免您可以将其移至
main
函数的最后一部分。

pyautogui.click(50, 500)
print(CountGooglyFound)

For,避免嵌套 if - else 语句。你可以这样修改你的代码。它不会影响您的代码。基本上,如果 len(locations[0]) == 0 那么它将返回 False、None 并且不会执行以

print("Image found at the following locations:")
开头的其余部分。它可以帮助您使代码更加清晰。

if len(locations[0]) == 0:
    print("Image not found in the screenshot.")
    pyautogui.click(500, 50)
    return False, None

print("Image found at the following locations:")
print(list(zip(*locations[::-1])))
return True, list(zip(*locations[::-1]))
© www.soinside.com 2019 - 2024. All rights reserved.