Почему мой код Python выполняет строки после оператора if-else перед строками внутри оператора if-else?Python

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 Почему мой код Python выполняет строки после оператора if-else перед строками внутри оператора if-else?

Сообщение Anonymous »

Я новичок в программировании на 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. Все остальное, кажется, работает гладко, поскольку оно может обнаружить изображение или не обнаружить его.

Подробнее здесь: https://stackoverflow.com/questions/783 ... before-the
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Python»