我是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()
我try 过这个,但pyautogui.Click(50,500)和print(CountGooglyFound)在if或else陈述之前执行.其他一切似乎都运行顺利,因为它可以检测到图像或不检测到图像.