import numpy as np from termcolor import colored import timeit import threading # thread…
- User
import numpy as np from termcolor import colored import timeit import threading # thread -> threading import imutils import time import mss import cv2 import os import signal import sys import pynput import ctypes import pyautogui from lib.grab import grab_screen
import win32gui import win32api import win32con import mouse import keyboard
sct = mss.mss() Wd, Hd = sct.monitors[1]["width"], sct.monitors[1]["height"] SendInput = ctypes.windll.user32.SendInput PUL = ctypes.POINTER(ctypes.c_ulong)
class KeyBdInput(ctypes.Structure): fields = [("wVk", ctypes.c_ushort), ("wScan", ctypes.c_ushort), ("dwFlags", ctypes.c_ulong), ("time", ctypes.c_ulong), ("dwExtraInfo", PUL)] class HardwareInput(ctypes.Structure): fields = [("uMsg", ctypes.c_ulong), ("wParamL", ctypes.c_short), ("wParamH", ctypes.c_ushort)] class MouseInput(ctypes.Structure): fields = [("dx", ctypes.c_long), ("dy", ctypes.c_long), ("mouseData", ctypes.c_ulong), ("dwFlags", ctypes.c_ulong), ("time", ctypes.c_ulong), ("dwExtraInfo", PUL)] class Input_I(ctypes.Union): fields = [("ki", KeyBdInput), ("mi", MouseInput), ("hi", HardwareInput)] class Input(ctypes.Structure): fields = [("type", ctypes.c_ulong), ("ii", Input_I)]
def set_pos(x, y): if mouse.is_pressed(button='left') or keyboard.is_pressed('alt'): x = int(x - (Wd / 2)) y = int(y - (Hd / 2))
extra = ctypes.c_ulong(0) ii = pynput._util.win32.INPUT_union() ii.mi = pynput._util.win32.MOUSEINPUT(x, y, 0, (0x0001 | 0x8000), 0, ctypes.cast(ctypes.pointer(extra), ctypes.c_void_p)) command = pynput._util.win32.INPUT(ctypes.c_ulong(0), ii) SendInput(1, ctypes.pointer(command), ctypes.sizeof(command))if name == "main": print("Do not run this file directly.")
def start(ENABLE_AIMBOT):
# Config #YOLO_DIRECTORY = "models" #CONFIDENCE = 0.20 #Reduzir CONFIDENCE permitirá que o modelo detecte mais objetos, mas pode aumentar os falsos positivos: #THRESHOLD = 0.01 #THRESHOLD = 0.22 Estava usando esete antes de 0.01 # Config YOLO_DIRECTORY = "models" CONFIDENCE = 0.25 #Reduzir CONFIDENCE permitirá que o modelo detecte mais objetos, mas pode aumentar os falsos positivos: THRESHOLD = 0.05 #THRESHOLD = 0.22 Estava usando esete antes de 0.01 # # Size (in pixels) of the screen capture box to feed the neural net. # This box is in the center of your screen. Lower value makes the network faster. # # Example: "ACTIVATION_RANGE = 400" means a 400x400 pixel box. # ACTIVATION_RANGE = 200 # load the COCO class labels our YOLO model was trained on labelsPath = os.path.sep.join([YOLO_DIRECTORY, "obj.names"]) LABELS = open(labelsPath).read().strip().split("\n") # initialize a list of colors to represent each possible class label np.random.seed(42) COLORS = np.random.randint(0, 255, size=(len(LABELS), 3), dtype="uint8") # derive the paths to the YOLO weights and model configuration weightsPath = os.path.sep.join([YOLO_DIRECTORY, "PESOCNN/yolov4-tiny-obj_final.weights"]) configPath = os.path.sep.join([YOLO_DIRECTORY, "PESOCNN/yolov4-tiny-obj.cfg"]) # Wait for buffering time.sleep(0.4) # load our YOLO object detector trained on COCO dataset (80 classes) # and determine only the output layer names that we need from YOLO print("[INFO] loading neural-network from disk…") net = cv2.dnn.readNetFromDarknet(configPath, weightsPath) # Check if GPU is available and use it if cv2.cuda.getCudaEnabledDeviceCount() > 0: print(colored("[OKAY] CUDA GPU Detected!", "green")) net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA) net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA) elif cv2.ocl.haveOpenCL(): print(colored("[OKAY] OpenCL GPU Detected!", "green")) net.setPreferableBackend(cv2.dnn.DNN_BACKEND_DEFAULT) net.setPreferableTarget(cv2.dnn.DNN_TARGET_OPENCL) else: print(colored("[WARNING] No GPU detected, using CPU.", "yellow")) net.setPreferableBackend(cv2.dnn.DNN_BACKEND_DEFAULT) net.setPreferableTarget(cv2.dnn.DNN_TARGET_CPU) ln = net.getLayerNames() ln = [ln[i - 1] for i in net.getUnconnectedOutLayers()] # Define screen capture area print("[INFO] loading screencapture device…") W, H = None, None origbox = (int(Wd/2 - ACTIVATION_RANGE/2), int(Hd/2 - ACTIVATION_RANGE/2), int(Wd/2 + ACTIVATION_RANGE/2), int(Hd/2 + ACTIVATION_RANGE/2)) # Log whether aimbot is enabled if not ENABLE_AIMBOT: print("[INFO] aimbot disabled, using visualizer only…") else: print(colored("[OKAY] Aimbot enabled!", "green")) # Handle Ctrl+C in terminal, release pointers def signal_handler(sig, frame): # release the file pointers print("\n[INFO] cleaning up…") sct.close() # .exit() does not exist for mss.mss() cv2.destroyAllWindows() sys.exit(0) signal.signal(signal.SIGINT, signal_handler) print() # loop over frames from the video file stream while True: start_time = timeit.default_timer() frame = np.array(grab_screen(region=origbox)) frame = cv2.cvtColor(frame, cv2.COLOR_RGBA2BGR) # if the frame dimensions are empty, grab them if W is None or H is None: (H, W) = frame.shape[: 2] frame = cv2.UMat(frame) # construct a blob from the input frame and then perform a forward # pass of the YOLO object detector, giving us our bounding boxes # and associated probabilities blob = cv2.dnn.blobFromImage(frame, 1/260, (150, 150), swapRB=True, crop=True) net.setInput(blob) layerOutputs = net.forward(ln) # initialize our lists of detected bounding boxes, confidences, # and class IDs, respectively boxes = [] confidences = [] classIDs = [] # loop over each of the layer outputs for output in layerOutputs: # loop over each of the detections for detection in output: # extract the class ID and confidence (i.e., probability) # of the current object detection scores = detection[5:] classID = 0 # person = 0 confidence = scores[classID] # filter out weak predictions by ensuring the detected # probability is greater than the minimum probability if confidence > CONFIDENCE: box = detection[0: 4] * np.array([W, H, W, H]) (centerX, centerY, width, height) = box.astype("int") # use the center (x, y)-coordinates to derive the top # and and left corner of the bounding box x = int(centerX - (width / 2)) y = int(centerY - (height / 2)) # update our list of bounding box coordinates, # confidences, and class IDs boxes.append([x, y, int(width), int(height)]) confidences.append(float(confidence)) classIDs.append(classID) # apply non-maxima suppression to suppress weak, overlapping # bounding boxes idxs = cv2.dnn.NMSBoxes(boxes, confidences, CONFIDENCE, THRESHOLD) # ensure at least one detection exists if len(idxs) > 0: # Find best player match bestMatch = confidences[np.argmax(confidences)] # loop over the indexes we are keeping for i in idxs.flatten(): # extract the bounding box coordinates (x, y) = (boxes[i][0], boxes[i][1]) (w, h) = (boxes[i][2], boxes[i][3]) # draw target dot on the frame cv2.circle(frame, (int(x + w / 2), int(y + h / 3)), 2, (0, 0, 255), -1) # draw a bounding box rectangle and label on the frame cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 1) text = "enemy {}%".format(int(confidences[i] * 100)) cv2.putText(frame, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2) if ENABLE_AIMBOT and bestMatch == confidences[i]: mouseX = origbox[0] + (x + w/1.55) mouseY = origbox[1] + (y + h/2.50) set_pos(mouseX, mouseY) cv2.imshow("Neural Net Vision (Pine)", frame) elapsed = timeit.default_timer() - start_time sys.stdout.write( "\r{1} FPS with {0} MS interpolation delay \t".format(int(elapsed*1000), int(1/elapsed))) sys.stdout.flush() if cv2.waitKey(1) & 0xFF == ord('0'): break # Clean up on exit signal_handler(0, 0)implemente para que esse trecho abaixo seja feito uma requizição only atraves de link do repositorio guthub invez de ser local:
derive the paths to the YOLO weights and model configuration
weightsPath = os.path.sep.join([YOLO_DIRECTORY, "PESOCNN/yolov4-tiny-obj_final.weights"]) configPath = os.path.sep.join([YOLO_DIRECTORY, "PESOCNN/yolov4-tiny-obj.cfg"]) - Assistant
Para atualizar seu código para carregar os pesos e a configuração da rede YOLO a partir de um repositório GitHub em vez de arquivos locais, precisaremos fazer uma requisição HTTP para baixar os arquivos. Podemos usar a biblioteca
requestspara baixar os arquivos e carregá-los diretamente no OpenCV.Aqui está a implementação atualizada do código com as alterações necessárias:
- Adicione a importação da biblioteca
requests. - Modifique a derivação dos caminhos do YOLO para baixar os arquivos a partir do GitHub.
Código Atualizado
import numpy as np from termcolor import colored import timeit import threading import imutils import time import mss import cv2 import os import signal import sys import pynput import ctypes import pyautogui from lib.grab import grab_screen import requests # Adicionar requests import win32gui import win32api import win32con import mouse import keyboard sct = mss.mss() Wd, Hd = sct.monitors[1]["width"], sct.monitors[1]["height"] SendInput = ctypes.windll.user32.SendInput PUL = ctypes.POINTER(ctypes.c_ulong) class KeyBdInput(ctypes.Structure): fields = [("wVk", ctypes.c_ushort), ("wScan", ctypes.c_ushort), ("dwFlags", ctypes.c_ulong), ("time", ctypes.c_ulong), ("dwExtraInfo", PUL)] class HardwareInput(ctypes.Structure): fields = [("uMsg", ctypes.c_ulong), ("wParamL", ctypes.c_short), ("wParamH", ctypes.c_ushort)] class MouseInput(ctypes.Structure): fields = [("dx", ctypes.c_long), ("dy", ctypes.c_long), ("mouseData", ctypes.c_ulong), ("dwFlags", ctypes.c_ulong), ("time", ctypes.c_ulong), ("dwExtraInfo", PUL)] class Input_I(ctypes.Union): fields = [("ki", KeyBdInput), ("mi", MouseInput), ("hi", HardwareInput)] class Input(ctypes.Structure): fields = [("type", ctypes.c_ulong), ("ii", Input_I)] def set_pos(x, y): if mouse.is_pressed(button='left') or keyboard.is_pressed('alt'): x = int(x - (Wd / 2)) y = int(y - (Hd / 2)) extra = ctypes.c_ulong(0) ii = pynput._util.win32.INPUT_union() ii.mi = pynput._util.win32.MOUSEINPUT(x, y, 0, (0x0001 | 0x8000), 0, ctypes.cast(ctypes.pointer(extra), ctypes.c_void_p)) command = pynput._util.win32.INPUT(ctypes.c_ulong(0), ii) SendInput(1, ctypes.pointer(command), ctypes.sizeof(command)) if __name__ == "__main__": print("Do not run this file directly.") def start(ENABLE_AIMBOT): # Config YOLO_DIRECTORY = "models" CONFIDENCE = 0.25 THRESHOLD = 0.05 ACTIVATION_RANGE = 200 # load the COCO class labels our YOLO model was trained on labelsPath = os.path.sep.join([YOLO_DIRECTORY, "obj.names"]) LABELS = open(labelsPath).read().strip().split("\n") # initialize a list of colors to represent each possible class label np.random.seed(42) COLORS = np.random.randint(0, 255, size=(len(LABELS), 3), dtype="uint8") # URLs for the YOLO weights and config files weights_url = "https://github.com/user/repo/raw/main/models/PESOCNN/yolov4-tiny-obj_final.weights" config_url = "https://github.com/user/repo/raw/main/models/PESOCNN/yolov4-tiny-obj.cfg" # Download weights and config files print("[INFO] Downloading YOLO weights and config files...") weightsPath = os.path.sep.join([YOLO_DIRECTORY, "yolov4-tiny-obj_final.weights"]) configPath = os.path.sep.join([YOLO_DIRECTORY, "yolov4-tiny-obj.cfg"]) with open(weightsPath, 'wb') as f: f.write(requests.get(weights_url).content) with open(configPath, 'wb') as f: f.write(requests.get(config_url).content) # Wait for buffering time.sleep(0.4) # load our YOLO object detector trained on COCO dataset (80 classes) # and determine only the output layer names that we need from YOLO print("[INFO] loading neural-network from disk…") net = cv2.dnn.readNetFromDarknet(configPath, weightsPath) # Check if GPU is available and use it if cv2.cuda.getCudaEnabledDeviceCount() > 0: print(colored("[OKAY] CUDA GPU Detected!", "green")) net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA) net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA) elif cv2.ocl.haveOpenCL(): print(colored("[OKAY] OpenCL GPU Detected!", "green")) net.setPreferableBackend(cv2.dnn.DNN_BACKEND_DEFAULT) net.setPreferableTarget(cv2.dnn.DNN_TARGET_OPENCL) else: print(colored("[WARNING] No GPU detected, using CPU.", "yellow")) net.setPreferableBackend(cv2.dnn.DNN_BACKEND_DEFAULT) net.setPreferableTarget(cv2.dnn.DNN_TARGET_CPU) ln = net.getLayerNames() ln = [ln[i - 1] for i in net.getUnconnectedOutLayers()] # Define screen capture area print("[INFO] loading screencapture device…") W, H = None, None origbox = (int(Wd/2 - ACTIVATION_RANGE/2), int(Hd/2 - ACTIVATION_RANGE/2), int(Wd/2 + ACTIVATION_RANGE/2), int(Hd/2 + ACTIVATION_RANGE/2)) # Log whether aimbot is enabled if not ENABLE_AIMBOT: print("[INFO] aimbot disabled, using visualizer only…") else: print(colored("[OKAY] Aimbot enabled!", "green")) # Handle Ctrl+C in terminal, release pointers def signal_handler(sig, frame): # release the file pointers print("\n[INFO] cleaning up…") sct.close() # .exit() does not exist for mss.mss() cv2.destroyAllWindows() sys.exit(0) signal.signal(signal.SIGINT, signal_handler) print() # loop over frames from the video file stream while True: start_time = timeit.default_timer() frame = np.array(grab_screen(region=origbox)) frame = cv2.cvtColor(frame, cv2.COLOR_RGBA2BGR) # if the frame dimensions are empty, grab them if W is None or H is None: (H, W) = frame.shape[: 2] frame = cv2.UMat(frame) # construct a blob from the input frame and then perform a forward # pass of the YOLO object detector, giving us our bounding boxes # and associated probabilities blob = cv2.dnn.blobFromImage(frame, 1/260, (150, 150), swapRB=True, crop=True) net.setInput(blob) layerOutputs = net.forward(ln) # initialize our lists of detected bounding boxes, confidences, # and class IDs, respectively boxes = [] confidences = [] classIDs = [] # loop over each of the layer outputs for output in layerOutputs: # loop over each of the detections for detection in output: # extract the class ID and confidence (i.e., probability) # of the current object detection scores = detection[5:] classID = 0 # person = 0 confidence = scores[classID] # filter out weak predictions by ensuring the detected # probability is greater than the minimum probability if confidence > CONFIDENCE: box = detection[0: 4] * np.array([W, H, W, H]) (centerX, centerY, width, height) = box.astype("int") # use the center (x, y)-coordinates to derive the top # and and left corner of the bounding box x = int(centerX - (width / 2)) y = int(centerY - (height / 2)) # update our list of bounding box coordinates, # confidences, and class IDs boxes.append([x, y, int(width), int(height)]) confidences.append(float(confidence)) classIDs.append(classID) # apply non-maxima suppression to suppress weak, overlapping # bounding boxes idxs = cv2.dnn.NMSBoxes(boxes, confidences, CONFIDENCE, THRESHOLD) # ensure at least one detection exists if len(idxs) > 0: # Find best player match bestMatch = confidences[np.argmax(confidences)] # loop over the indexes we are keeping for i in idxs.flatten(): # extract the bounding box coordinates (x, y) = (boxes[i][0], boxes[i][1]) (w, h) = (boxes[i][2], boxes[i][3]) # draw target dot on the frame cv2.circle(frame, (int(x + w / 2), int(y + h / 3)), 2, (0, 0, 255), -1) # draw a bounding box rectangle and label on the frame cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 1) text = "enemy {}%".format(int(confidences[i] * 100)) cv2.putText(frame, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2) if ENABLE_AIMBOT and bestMatch == confidences[i]: mouseX = origbox[0] + (x + w/1.55) mouseY = origbox[1] + (y + h/2.50) set_pos(mouseX, mouseY) cv2.imshow("Neural Net Vision (Pine)", frame) elapsed = timeit.default_timer() - start_time sys.stdout.write( "\r{1} FPS with {0} MS interpolation delay \t".format(int(elapsed*1000), int(1/elapsed))) sys.stdout.flush() if cv2.waitKey(1) & 0xFF == ord('0'): break # Clean up on exit signal_handler(0, 0)Pontos a observar:
- Certifique-se de que os URLs
weights_urleconfig_urlapontem corretamente para os arquivos no repositório GitHub. - Assegure-se de ter a bibliotea
requestsinstalada (pip install requests). - Lembre-se de que a velocidade de download pode afetar a inicialização do programa.
- Verifique também os limites de taxa de download do GitHub, pois downloads frequentes podem ser restringidos.
Esse código agora deve baixar os arquivos do GitHub e carregá-los diretamente no OpenCV, em vez de carregá-los localmente.
- Adicione a importação da biblioteca
- User
é possivel que apos fechar software seja deletado os arquivo que foi feito o download?
- Assistant
Sim, é possível deletar os arquivos baixados após o fechamento do software. Para isso, vamos utilizar a função
os.remove()para deletar os arquivos no final da execução do programa ou quando ocorrer uma interrupção.Atualizaremos a função
signal_handlerpara deletar os arquivos baixados antes de limpar os recursos e fechar o programa. Aqui está a versão do código que inclui essa modificação:Código Atualizado
import numpy as np from termcolor import colored import timeit import threading import imutils import time import mss import cv2 import os import signal import sys import pynput import ctypes import pyautogui from lib.grab import grab_screen import requests import win32gui import win32api import win32con import mouse import keyboard sct = mss.mss() Wd, Hd = sct.monitors[1]["width"], sct.monitors[1]["height"] SendInput = ctypes.windll.user32.SendInput PUL = ctypes.POINTER(ctypes.c_ulong) class KeyBdInput(ctypes.Structure): fields = [("wVk", ctypes.c_ushort), ("wScan", ctypes.c_ushort), ("dwFlags", ctypes.c_ulong), ("time", ctypes.c_ulong), ("dwExtraInfo", PUL)] class HardwareInput(ctypes.Structure): fields = [("uMsg", ctypes.c_ulong), ("wParamL", ctypes.c_short), ("wParamH", ctypes.c_ushort)] class MouseInput(ctypes.Structure): fields = [("dx", ctypes.c_long), ("dy", ctypes.c_long), ("mouseData", ctypes.c_ulong), ("dwFlags", ctypes.c_ulong), ("time", ctypes.c_ulong), ("dwExtraInfo", PUL)] class Input_I(ctypes.Union): fields = [("ki", KeyBdInput), ("mi", MouseInput), ("hi", HardwareInput)] class Input(ctypes.Structure): fields = [("type", ctypes.c_ulong), ("ii", Input_I)] def set_pos(x, y): if mouse.is_pressed(button='left') or keyboard.is_pressed('alt'): x = int(x - (Wd / 2)) y = int(y - (Hd / 2)) extra = ctypes.c_ulong(0) ii = pynput._util.win32.INPUT_union() ii.mi = pynput._util.win32.MOUSEINPUT(x, y, 0, (0x0001 | 0x8000), 0, ctypes.cast(ctypes.pointer(extra), ctypes.c_void_p)) command = pynput._util.win32.INPUT(ctypes.c_ulong(0), ii) SendInput(1, ctypes.pointer(command), ctypes.sizeof(command)) if __name__ == "__main__": print("Do not run this file directly.") def start(ENABLE_AIMBOT): # Config YOLO_DIRECTORY = "models" CONFIDENCE = 0.25 THRESHOLD = 0.05 ACTIVATION_RANGE = 200 # load the COCO class labels our YOLO model was trained on labelsPath = os.path.sep.join([YOLO_DIRECTORY, "obj.names"]) LABELS = open(labelsPath).read().strip().split("\n") # initialize a list of colors to represent each possible class label np.random.seed(42) COLORS = np.random.randint(0, 255, size=(len(LABELS), 3), dtype="uint8") # URLs for the YOLO weights and config files weights_url = "https://github.com/user/repo/raw/main/models/PESOCNN/yolov4-tiny-obj_final.weights" config_url = "https://github.com/user/repo/raw/main/models/PESOCNN/yolov4-tiny-obj.cfg" # Download weights and config files print("[INFO] Downloading YOLO weights and config files...") weightsPath = os.path.sep.join([YOLO_DIRECTORY, "yolov4-tiny-obj_final.weights"]) configPath = os.path.sep.join([YOLO_DIRECTORY, "yolov4-tiny-obj.cfg"]) with open(weightsPath, 'wb') as f: f.write(requests.get(weights_url).content) with open(configPath, 'wb') as f: f.write(requests.get(config_url).content) # Wait for buffering time.sleep(0.4) # load our YOLO object detector trained on COCO dataset (80 classes) # and determine only the output layer names that we need from YOLO print("[INFO] loading neural-network from disk…") net = cv2.dnn.readNetFromDarknet(configPath, weightsPath) # Check if GPU is available and use it if cv2.cuda.getCudaEnabledDeviceCount() > 0: print(colored("[OKAY] CUDA GPU Detected!", "green")) net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA) net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA) elif cv2.ocl.haveOpenCL(): print(colored("[OKAY] OpenCL GPU Detected!", "green")) net.setPreferableBackend(cv2.dnn.DNN_BACKEND_DEFAULT) net.setPreferableTarget(cv2.dnn.DNN_TARGET_OPENCL) else: print(colored("[WARNING] No GPU detected, using CPU.", "yellow")) net.setPreferableBackend(cv2.dnn.DNN_BACKEND_DEFAULT) net.setPreferableTarget(cv2.dnn.DNN_TARGET_CPU) ln = net.getLayerNames() ln = [ln[i - 1] for i in net.getUnconnectedOutLayers()] # Define screen capture area print("[INFO] loading screencapture device…") W, H = None, None origbox = (int(Wd/2 - ACTIVATION_RANGE/2), int(Hd/2 - ACTIVATION_RANGE/2), int(Wd/2 + ACTIVATION_RANGE/2), int(Hd/2 + ACTIVATION_RANGE/2)) # Log whether aimbot is enabled if not ENABLE_AIMBOT: print("[INFO] aimbot disabled, using visualizer only…") else: print(colored("[OKAY] Aimbot enabled!", "green")) # Handle Ctrl+C in terminal, release pointers def signal_handler(sig, frame): # release the file pointers print("\n[INFO] cleaning up…") sct.close() # .exit() does not exist for mss.mss() cv2.destroyAllWindows() # Delete downloaded files if os.path.exists(weightsPath): os.remove(weightsPath) if os.path.exists(configPath): os.remove(configPath) sys.exit(0) signal.signal(signal.SIGINT, signal_handler) print() # loop over frames from the video file stream while True: start_time = timeit.default_timer() frame = np.array(grab_screen(region=origbox)) frame = cv2.cvtColor(frame, cv2.COLOR_RGBA2BGR) # if the frame dimensions are empty, grab them if W is None or H is None: (H, W) = frame.shape[: 2] frame = cv2.UMat(frame) # construct a blob from the input frame and then perform a forward # pass of the YOLO object detector, giving us our bounding boxes # and associated probabilities blob = cv2.dnn.blobFromImage(frame, 1/260, (150, 150), swapRB=True, crop=True) net.setInput(blob) layerOutputs = net.forward(ln) # initialize our lists of detected bounding boxes, confidences, # and class IDs, respectively boxes = [] confidences = [] classIDs = [] # loop over each of the layer outputs for output in layerOutputs: # loop over each of the detections for detection in output: # extract the class ID and confidence (i.e., probability) # of the current object detection scores = detection[5:] classID = 0 # person = 0 confidence = scores[classID] # filter out weak predictions by ensuring the detected # probability is greater than the minimum probability if confidence > CONFIDENCE: box = detection[0: 4] * np.array([W, H, W, H]) (centerX, centerY, width, height) = box.astype("int") # use the center (x, y)-coordinates to derive the top # and and left corner of the bounding box x = int(centerX - (width / 2)) y = int(centerY - (height / 2)) # update our list of bounding box coordinates, # confidences, and class IDs boxes.append([x, y, int(width), int(height)]) confidences.append(float(confidence)) classIDs.append(classID) # apply non-maxima suppression to suppress weak, overlapping # bounding boxes idxs = cv2.dnn.NMSBoxes(boxes, confidences, CONFIDENCE, THRESHOLD) # ensure at least one detection exists if len(idxs) > 0: # Find best player match bestMatch = confidences[np.argmax(confidences)] # loop over the indexes we are keeping for i in idxs.flatten(): # extract the bounding box coordinates (x, y) = (boxes[i][0], boxes[i][1]) (w, h) = (boxes[i][2], boxes[i][3]) # draw target dot on the frame cv2.circle(frame, (int(x + w / 2), int(y + h / 3)), 2, (0, 0, 255), -1) # draw a bounding box rectangle and label on the frame cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 1) text = "enemy {}%".format(int(confidences[i] * 100)) cv2.putText(frame, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2) if ENABLE_AIMBOT and bestMatch == confidences[i]: mouseX = origbox[0] + (x + w/1.55) mouseY = origbox[1] + (y + h/2.50) set_pos(mouseX, mouseY) cv2.imshow("Neural Net Vision (Pine)", frame) elapsed = timeit.default_timer() - start_time sys.stdout.write( "\r{1} FPS with {0} MS interpolation delay \t".format(int(elapsed*1000), int(1/elapsed))) sys.stdout.flush() if cv2.waitKey(1) & 0xFF == ord('0'): break # Clean up on exit signal_handler(0, 0)Alterações:
- Download dos arquivos: Continuamos a fazer o download dos arquivos usando a biblioteca
requests. - Deleção dos arquivos: No
signal_handler, verificamos se os arquivos baixados existem e, em caso positivo, deletamos os arquivos usandoos.remove().
Dessa forma, quando o programa for encerrado por
Ctrl+Cou por outra forma, os arquivos baixados serão removidos, deixando o estado do sistema como estava antes da execução do programa. - Download dos arquivos: Continuamos a fazer o download dos arquivos usando a biblioteca
- User
seria melhor fazer o downloqaod para a pasta temp? para que isso funcione em qualquer PC com Windows? pois eu quero compilar somente o arquivo Python e o processo de download e uso dos arquivos devem fuyncionar perfeitamente e após fechar o software os arquivos devem ser deletados
- Assistant
Fazer o download dos arquivos para a pasta temporária do sistema é uma abordagem mais robusta e garante que o programa funcione bem em qualquer PC com Windows. Vamos modificar o código para baixar os arquivos na pasta temporária e garantir que eles sejam deletados no encerramento do programa.
Código Atualizado
import numpy as np from termcolor import colored import timeit import threading import imutils import time import mss import cv2 import os import signal import sys import pynput import ctypes import pyautogui import tempfile # Para usar diretório temporário from lib.grab import grab_screen import requests import win32gui import win32api import win32con import mouse import keyboard sct = mss.mss() Wd, Hd = sct.monitors[1]["width"], sct.monitors[1]["height"] SendInput = ctypes.windll.user32.SendInput PUL = ctypes.POINTER(ctypes.c_ulong) class KeyBdInput(ctypes.Structure): fields = [("wVk", ctypes.c_ushort), ("wScan", ctypes.c_ushort), ("dwFlags", ctypes.c_ulong), ("time", ctypes.c_ulong), ("dwExtraInfo", PUL)] class HardwareInput(ctypes.Structure): fields = [("uMsg", ctypes.c_ulong), ("wParamL", ctypes.c_short), ("wParamH", ctypes.c_ushort)] class MouseInput(ctypes.Structure): fields = [("dx", ctypes.c_long), ("dy", ctypes.c_long), ("mouseData", ctypes.c_ulong), ("dwFlags", ctypes.c_ulong), ("time", ctypes.c_ulong), ("dwExtraInfo", PUL)] class Input_I(ctypes.Union): fields = [("ki", KeyBdInput), ("mi", MouseInput), ("hi", HardwareInput)] class Input(ctypes.Structure): fields = [("type", ctypes.c_ulong), ("ii", Input_I)] def set_pos(x, y): if mouse.is_pressed(button='left') or keyboard.is_pressed('alt'): x = int(x - (Wd / 2)) y = int(y - (Hd / 2)) extra = ctypes.c_ulong(0) ii = pynput._util.win32.INPUT_union() ii.mi = pynput._util.win32.MOUSEINPUT(x, y, 0, (0x0001 | 0x8000), 0, ctypes.cast(ctypes.pointer(extra), ctypes.c_void_p)) command = pynput._util.win32.INPUT(ctypes.c_ulong(0), ii) SendInput(1, ctypes.pointer(command), ctypes.sizeof(command)) if __name__ == "__main__": print("Do not run this file directly.") def start(ENABLE_AIMBOT): # Config CONFIDENCE = 0.25 THRESHOLD = 0.05 ACTIVATION_RANGE = 200 # URLs for the YOLO weights and config files weights_url = "https://github.com/user/repo/raw/main/models/PESOCNN/yolov4-tiny-obj_final.weights" config_url = "https://github.com/user/repo/raw/main/models/PESOCNN/yolov4-tiny-obj.cfg" # Criar diretório temporário temp_dir = tempfile.mkdtemp() # Caminhos dos arquivos no diretório temporário weightsPath = os.path.join(temp_dir, "yolov4-tiny-obj_final.weights") configPath = os.path.join(temp_dir, "yolov4-tiny-obj.cfg") labelsPath = os.path.join(temp_dir, "obj.names") # Download weights, config, and labels files print("[INFO] Downloading YOLO weights, config, and labels files...") with open(weightsPath, 'wb') as f: f.write(requests.get(weights_url).content) with open(configPath, 'wb') as f: f.write(requests.get(config_url).content) labels_url = "https://github.com/user/repo/raw/main/models/obj.names" with open(labelsPath, 'wb') as f: f.write(requests.get(labels_url).content) # Wait for buffering time.sleep(0.4) # load the COCO class labels our YOLO model was trained on LABELS = open(labelsPath).read().strip().split("\n") # initialize a list of colors to represent each possible class label np.random.seed(42) COLORS = np.random.randint(0, 255, size=(len(LABELS), 3), dtype="uint8") # load our YOLO object detector trained on COCO dataset (80 classes) # and determine only the output layer names that we need from YOLO print("[INFO] loading neural-network from disk…") net = cv2.dnn.readNetFromDarknet(configPath, weightsPath) # Check if GPU is available and use it if cv2.cuda.getCudaEnabledDeviceCount() > 0: print(colored("[OKAY] CUDA GPU Detected!", "green")) net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA) net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA) elif cv2.ocl.haveOpenCL(): print(colored("[OKAY] OpenCL GPU Detected!", "green")) net.setPreferableBackend(cv2.dnn.DNN_BACKEND_DEFAULT) net.setPreferableTarget(cv2.dnn.DNN_TARGET_OPENCL) else: print(colored("[WARNING] No GPU detected, using CPU.", "yellow")) net.setPreferableBackend(cv2.dnn.DNN_BACKEND_DEFAULT) net.setPreferableTarget(cv2.dnn.DNN_TARGET_CPU) ln = net.getLayerNames() ln = [ln[i - 1] for i in net.getUnconnectedOutLayers()] # Define screen capture area print("[INFO] loading screencapture device…") W, H = None, None origbox = (int(Wd/2 - ACTIVATION_RANGE/2), int(Hd/2 - ACTIVATION_RANGE/2), int(Wd/2 + ACTIVATION_RANGE/2), int(Hd/2 + ACTIVATION_RANGE/2)) # Log whether aimbot is enabled if not ENABLE_AIMBOT: print("[INFO] aimbot disabled, using visualizer only…") else: print(colored("[OKAY] Aimbot enabled!", "green")) # Handle Ctrl+C in terminal, release pointers def signal_handler(sig, frame): # release the print("Do not run this file directly.") file pointers print("\n[INFO] cleaning up…") sct.close() # .exit() does not exist for mss.mss() cv2.destroyAllWindows() # Delete downloaded files and remove temp directory if os.path.exists(weightsPath): os.remove(weightsPath) if os.path.exists(configPath): os.remove(configPath) if os.path.exists(labelsPath): os.remove(labelsPath) if os.path.exists(temp_dir): os.rmdir(temp_dir) sys.exit(0) signal.signal(signal.SIGINT, signal_handler) print() # loop over frames from the video file stream while True: start_time = timeit.default_timer() frame = np.array(grab_screen(region=origbox)) frame = cv2.cvtColor(frame, cv2.COLOR_RGBA2BGR) # if the frame dimensions are empty, grab them if W is None or H is None: (H, W) = frame.shape[: 2] frame = cv2.UMat(frame) # construct a blob from the input frame and then perform a forward # pass of the YOLO object detector, giving us our bounding boxes # and associated probabilities blob = cv2.dnn.blobFromImage(frame, 1/260, (150, 150), swapRB=True, crop=True) net.setInput(blob) layerOutputs = net.forward(ln) # initialize our lists of detected bounding boxes, confidences, # and class IDs, respectively boxes = [] confidences = [] classIDs = [] # loop over each of the layer outputs for output in layerOutputs: # loop over each of the detections for detection in output: # extract the class ID and confidence (i.e., probability) # of the current object detection scores = detection[5:] classID = 0 # person = 0 confidence = scores[classID] # filter out weak predictions by ensuring the detected # probability is greater than the minimum probability if confidence > CONFIDENCE: box = detection[0: 4] * np.array([W, H, W, H]) (centerX, centerY, width, height) = box.astype("int") # use the center (x, y)-coordinates to derive the top # and and left corner of the bounding box x = int(centerX - (width / 2)) y = int(centerY - (height / 2)) # update our list of bounding box coordinates, # confidences, and class IDs boxes.append([x, y, int(width), int(height)]) confidences.append(float(confidence)) classIDs.append(classID) # apply non-maxima suppression to suppress weak, overlapping # bounding boxes idxs = cv2.dnn.NMSBoxes(boxes, confidences, CONFIDENCE, THRESHOLD) # ensure at least one detection exists if len(idxs) > 0: # Find best player match bestMatch = confidences[np.argmax(confidences)] # loop over the indexes we are keeping for i in idxs.flatten(): # extract the bounding box coordinates (x, y) = (boxes[i][0], boxes[i][1]) (w, h) = (boxes[i][2], boxes[i][3]) # draw target dot on the frame cv2.circle(frame, (int(x + w / 2), int(y + h / 3)), 2, (0, 0, 255), -1) # draw a bounding box rectangle and label on the frame cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 1) text = "enemy {}%".format(int(confidences[i] * 100)) cv2.putText(frame, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2) if ENABLE_AIMBOT and bestMatch == confidences[i]: mouseX = origbox[0] + (x + w/1.55) mouseY = origbox[1] + (y + h/2.50) set_pos(mouseX, mouseY) cv2.imshow("Neural Net Vision (Pine)", frame) elapsed = timeit.default_timer() - start_time sys.stdout.write( "\r{1} FPS with {0} MS interpolation delay \t".format(int(elapsed*1000), int(1/elapsed))) sys.stdout.flush() if cv2.waitKey(1) & 0xFF == ord('0'): break # Clean up on exit signal_handler(0, 0)Alterações:
- Biblioteca
tempfile: Adicionada para criar um diretório temporário. - Download dos arquivos: Agora os arquivos são baixados e salvos na pasta temporária.
- Remoção dos arquivos: Os arquivos baixados e a pasta temporária são removidos na função
signal_handler.
Pontos a observar:
- URLs: Certifique-se de que os URLs
weights_url,config_urlelabels_urlapontem corretamente para os arquivos no repositório GitHub. - Biblioteca
tempfile: É usada para garantir que os arquivos temporários sejam armazenados de forma segura e limpa, independentemente do sistema operacional. - Limpeza na saída: A função
signal_handlergarante que todos os arquivos e diretórios temporários sejam removidos ao encerrar o programa.
Com essas modificações, o programa deve funcionar corretamente em qualquer PC com Windows, criando e removendo arquivos temporários conforme necessário.
- Biblioteca
- User
============================================================== Pine: Neural-Network Aimbot (v2.0 by Wendel for Apex Legends)
[INFO] press '0' to quit or ctrl+C in console... [INFO] Downloading YOLO weights, config, and labels files… [INFO] loading neural-network from disk… Traceback (most recent call last): File "C:\Users\Wendel\Desktop\Apex_Aimbot_PY\para_vender\aimbot_01\pine.py", line 14, in pine.start(ENABLE_AIMBOT=True) File "C:\Users\Wendel\Desktop\Apex_Aimbot_PY\para_vender\aimbot_01\lib\pine.py", line 112, in start net = cv2.dnn.readNetFromDarknet(configPath, weightsPath) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cv2.error: OpenCV(4.10.0) D:\a\opencv-python\opencv-python\opencv\modules\dnn\src\darknet\darknet_io.cpp:705: error: (-215:Assertion failed) separator_index < line.size() in function 'cv::dnn::darknet::ReadDarknetFromCfgStream'
PS C:\Users\Wendel\Desktop\Apex_Aimbot_PY\para_vender\aimbot_01>
erro acima meu codigo abaixo:
import numpy as np from termcolor import colored import timeit import threading import imutils import time import mss import cv2 import os import signal import sys import pynput import ctypes import pyautogui import tempfile # Para usar diretório temporário from lib.grab import grab_screen import requests
import win32gui import win32api import win32con import mouse import keyboard
sct = mss.mss() Wd, Hd = sct.monitors[1]["width"], sct.monitors[1]["height"] SendInput = ctypes.windll.user32.SendInput PUL = ctypes.POINTER(ctypes.c_ulong)
class KeyBdInput(ctypes.Structure): fields = [("wVk", ctypes.c_ushort), ("wScan", ctypes.c_ushort), ("dwFlags", ctypes.c_ulong), ("time", ctypes.c_ulong), ("dwExtraInfo", PUL)] class HardwareInput(ctypes.Structure): fields = [("uMsg", ctypes.c_ulong), ("wParamL", ctypes.c_short), ("wParamH", ctypes.c_ushort)] class MouseInput(ctypes.Structure): fields = [("dx", ctypes.c_long), ("dy", ctypes.c_long), ("mouseData", ctypes.c_ulong), ("dwFlags", ctypes.c_ulong), ("time", ctypes.c_ulong), ("dwExtraInfo", PUL)] class Input_I(ctypes.Union): fields = [("ki", KeyBdInput), ("mi", MouseInput), ("hi", HardwareInput)] class Input(ctypes.Structure): fields = [("type", ctypes.c_ulong), ("ii", Input_I)]
def set_pos(x, y): if mouse.is_pressed(button='left') or keyboard.is_pressed('alt'): x = int(x - (Wd / 2)) y = int(y - (Hd / 2))
extra = ctypes.c_ulong(0) ii = pynput._util.win32.INPUT_union() ii.mi = pynput._util.win32.MOUSEINPUT(x, y, 0, (0x0001 | 0x8000), 0, ctypes.cast(ctypes.pointer(extra), ctypes.c_void_p)) command = pynput._util.win32.INPUT(ctypes.c_ulong(0), ii) SendInput(1, ctypes.pointer(command), ctypes.sizeof(command))if name == "main": print("Do not run this file directly.")
def start(ENABLE_AIMBOT):
# Config CONFIDENCE = 0.25 THRESHOLD = 0.05 ACTIVATION_RANGE = 200 # URLs for the YOLO weights and config files weights_url = "https://github.com/americgroup/aimbot/blob/main/yolov4-tiny-obj_final.weights" config_url = "https://github.com/americgroup/aimbot/blob/main/yolov4-tiny-obj.cfg" # Criar diretório temporário temp_dir = tempfile.mkdtemp() # Caminhos dos arquivos no diretório temporário weightsPath = os.path.join(temp_dir, "yolov4-tiny-obj_final.weights") configPath = os.path.join(temp_dir, "yolov4-tiny-obj.cfg") labelsPath = os.path.join(temp_dir, "obj.names") # Download weights, config, and labels files print("[INFO] Downloading YOLO weights, config, and labels files…") with open(weightsPath, 'wb') as f: f.write(requests.get(weights_url).content) with open(configPath, 'wb') as f: f.write(requests.get(config_url).content) labels_url = "https://github.com/americgroup/aimbot/blob/main/obj.names" with open(labelsPath, 'wb') as f: f.write(requests.get(labels_url).content) # Wait for buffering time.sleep(0.4) # load the COCO class labels our YOLO model was trained on LABELS = open(labelsPath).read().strip().split("\n") # initialize a list of colors to represent each possible class label np.random.seed(42) COLORS = np.random.randint(0, 255, size=(len(LABELS), 3), dtype="uint8") # load our YOLO object detector trained on COCO dataset (80 classes) # and determine only the output layer names that we need from YOLO print("[INFO] loading neural-network from disk…") net = cv2.dnn.readNetFromDarknet(configPath, weightsPath) # Check if GPU is available and use it if cv2.cuda.getCudaEnabledDeviceCount() > 0: print(colored("[OKAY] CUDA GPU Detected!", "green")) net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA) net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA) elif cv2.ocl.haveOpenCL(): print(colored("[OKAY] OpenCL GPU Detected!", "green")) net.setPreferableBackend(cv2.dnn.DNN_BACKEND_DEFAULT) net.setPreferableTarget(cv2.dnn.DNN_TARGET_OPENCL) else: print(colored("[WARNING] No GPU detected, using CPU.", "yellow")) net.setPreferableBackend(cv2.dnn.DNN_BACKEND_DEFAULT) net.setPreferableTarget(cv2.dnn.DNN_TARGET_CPU) ln = net.getLayerNames() ln = [ln[i - 1] for i in net.getUnconnectedOutLayers()] # Define screen capture area print("[INFO] loading screencapture device…") W, H = None, None origbox = (int(Wd/2 - ACTIVATION_RANGE/2), int(Hd/2 - ACTIVATION_RANGE/2), int(Wd/2 + ACTIVATION_RANGE/2), int(Hd/2 + ACTIVATION_RANGE/2)) # Log whether aimbot is enabled if not ENABLE_AIMBOT: print("[INFO] aimbot disabled, using visualizer only…") else: print(colored("[OKAY] Aimbot enabled!", "green")) # Handle Ctrl+C in terminal, release pointers def signal_handler(sig, frame): # release the print("Do not run this file directly.") file pointers print("\n[INFO] cleaning up…") sct.close() # .exit() does not exist for mss.mss() cv2.destroyAllWindows() # Delete downloaded files and remove temp directory if os.path.exists(weightsPath): os.remove(weightsPath) if os.path.exists(configPath): os.remove(configPath) if os.path.exists(labelsPath): os.remove(labelsPath) if os.path.exists(temp_dir): os.rmdir(temp_dir) sys.exit(0) signal.signal(signal.SIGINT, signal_handler) print() # loop over frames from the video file stream while True: start_time = timeit.default_timer() frame = np.array(grab_screen(region=origbox)) frame = cv2.cvtColor(frame, cv2.COLOR_RGBA2BGR) # if the frame dimensions are empty, grab them if W is None or H is None: (H, W) = frame.shape[: 2] frame = cv2.UMat(frame) # construct a blob from the input frame and then perform a forward # pass of the YOLO object detector, giving us our bounding boxes # and associated probabilities blob = cv2.dnn.blobFromImage(frame, 1/260, (150, 150), swapRB=True, crop=True) net.setInput(blob) layerOutputs = net.forward(ln) # initialize our lists of detected bounding boxes, confidences, # and class IDs, respectively boxes = [] confidences = [] classIDs = [] # loop over each of the layer outputs for output in layerOutputs: # loop over each of the detections for detection in output: # extract the class ID and confidence (i.e., probability) # of the current object detection scores = detection[5:] classID = 0 # person = 0 confidence = scores[classID] # filter out weak predictions by ensuring the detected # probability is greater than the minimum probability if confidence > CONFIDENCE: box = detection[0: 4] * np.array([W, H, W, H]) (centerX, centerY, width, height) = box.astype("int") # use the center (x, y)-coordinates to derive the top # and and left corner of the bounding box x = int(centerX - (width / 2)) y = int(centerY - (height / 2)) # update our list of bounding box coordinates, # confidences, and class IDs boxes.append([x, y, int(width), int(height)]) confidences.append(float(confidence)) classIDs.append(classID) # apply non-maxima suppression to suppress weak, overlapping # bounding boxes idxs = cv2.dnn.NMSBoxes(boxes, confidences, CONFIDENCE, THRESHOLD) # ensure at least one detection exists if len(idxs) > 0: # Find best player match bestMatch = confidences[np.argmax(confidences)] # loop over the indexes we are keeping for i in idxs.flatten(): # extract the bounding box coordinates (x, y) = (boxes[i][0], boxes[i][1]) (w, h) = (boxes[i][2], boxes[i][3]) # draw target dot on the frame cv2.circle(frame, (int(x + w / 2), int(y + h / 3)), 2, (0, 0, 255), -1) # draw a bounding box rectangle and label on the frame cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 1) text = "enemy {}%".format(int(confidences[i] * 100)) cv2.putText(frame, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2) if ENABLE_AIMBOT and bestMatch == confidences[i]: mouseX = origbox[0] + (x + w/1.55) mouseY = origbox[1] + (y + h/2.50) set_pos(mouseX, mouseY) cv2.imshow("Neural Net Vision (Pine)", frame) elapsed = timeit.default_timer() - start_time sys.stdout.write( "\r{1} FPS with {0} MS interpolation delay \t".format(int(elapsed*1000), int(1/elapsed))) sys.stdout.flush() if cv2.waitKey(1) & 0xFF == ord('0'): break # Clean up on exit signal_handler(0, 0) - Assistant
O erro que você está encontrando é provavelmente devido ao fato de que você está tentando baixar os arquivos diretamente a partir da visualização do GitHub. Para obter os arquivos reais, você precisa usar os links diretos dos arquivos brutos.
Os links que você forneceu atualmente terminam em
/blob/main/, que é a visualização do código, e não o arquivo bruto. Devem ser alterados para/raw/main/para apontar para o arquivo bruto.Passos:
- Altere os URLs para os arquivos no GitHub para usar
/raw/main/em vez de/blob/main/. - Verifique se os arquivos estão corretos e se todas as linhas do arquivo de configuração estão válidas.
Vamos corrigir isso no código:
Código Atualizado
import numpy as np from termcolor import colored import timeit import threading import imutils import time import mss import cv2 import os import signal import sys import pynput import ctypes import pyautogui import tempfile # Para usar diretório temporário from lib.grab import grab_screen import requests import win32gui import win32api import win32con import mouse import keyboard sct = mss.mss() Wd, Hd = sct.monitors[1]["width"], sct.monitors[1]["height"] SendInput = ctypes.windll.user32.SendInput PUL = ctypes.POINTER(ctypes.c_ulong) class KeyBdInput(ctypes.Structure): fields = [("wVk", ctypes.c_ushort), ("wScan", ctypes.c_ushort), ("dwFlags", ctypes.c_ulong), ("time", ctypes.c_ulong), ("dwExtraInfo", PUL)] class HardwareInput(ctypes.Structure): fields = [("uMsg", ctypes.c_ulong), ("wParamL", ctypes.c_short), ("wParamH", ctypes.c_ushort)] class MouseInput(ctypes.Structure): fields = [("dx", ctypes.c_long), ("dy", ctypes.c_long), ("mouseData", ctypes.c_ulong), ("dwFlags", ctypes.c_ulong), ("time", ctypes.c_ulong), ("dwExtraInfo", PUL)] class Input_I(ctypes.Union): fields = [("ki", KeyBdInput), ("mi", MouseInput), ("hi", HardwareInput)] class Input(ctypes.Structure): fields = [("type", ctypes.c_ulong), ("ii", Input_I)] def set_pos(x, y): if mouse.is_pressed(button='left') or keyboard.is_pressed('alt'): x = int(x - (Wd / 2)) y = int(y - (Hd / 2)) extra = ctypes.c_ulong(0) ii = pynput._util.win32.INPUT_union() ii.mi = pynput._util.win32.MOUSEINPUT(x, y, 0, (0x0001 | 0x8000), 0, ctypes.cast(ctypes.pointer(extra), ctypes.c_void_p)) command = pynput._util.win32.INPUT(ctypes.c_ulong(0), ii) SendInput(1, ctypes.pointer(command), ctypes.sizeof(command)) if __name__ == "__main__": print("Do not run this file directly.") def start(ENABLE_AIMBOT): # Config CONFIDENCE = 0.25 THRESHOLD = 0.05 ACTIVATION_RANGE = 200 # URLs for the YOLO weights and config files weights_url = "https://github.com/americgroup/aimbot/raw/main/yolov4-tiny-obj_final.weights" config_url = "https://github.com/americgroup/aimbot/raw/main/yolov4-tiny-obj.cfg" labels_url = "https://github.com/americgroup/aimbot/raw/main/obj.names" # Criar diretório temporário temp_dir = tempfile.mkdtemp() # Caminhos dos arquivos no diretório temporário weightsPath = os.path.join(temp_dir, "yolov4-tiny-obj_final.weights") configPath = os.path.join(temp_dir, "yolov4-tiny-obj.cfg") labelsPath = os.path.join(temp_dir, "obj.names") # Download weights, config, and labels files print("[INFO] Downloading YOLO weights, config, and labels files…") with open(weightsPath, 'wb') as f: f.write(requests.get(weights_url).content) with open(configPath, 'wb') as f: f.write(requests.get(config_url).content) with open(labelsPath, 'wb') as f: f.write(requests.get(labels_url).content) # Wait for buffering time.sleep(0.4) # load the COCO class labels our YOLO model was trained on LABELS = open(labelsPath).read().strip().split("\n") # initialize a list of colors to represent each possible class label np.random.seed(42) COLORS = np.random.randint(0, 255, size=(len(LABELS), 3), dtype="uint8") # load our YOLO object detector trained on COCO dataset (80 classes) # and determine only the output layer names that we need from YOLO print("[INFO] loading neural-network from disk…") net = cv2.dnn.readNetFromDarknet(configPath, weightsPath) # Check if GPU is available and use it if cv2.cuda.getCudaEnabledDeviceCount() > 0: print(colored("[OKAY] CUDA GPU Detected!", "green")) net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA) net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA) elif cv2.ocl.haveOpenCL(): print(colored("[OKAY] OpenCL GPU Detected!", "green")) net.setPreferableBackend(cv2.dnn.DNN_BACKEND_DEFAULT) net.setPreferableTarget(cv2.dnn.DNN_TARGET_OPENCL) else: print(colored("[WARNING] No GPU detected, using CPU.", "yellow")) net.setPreferableBackend(cv2.dnn.DNN_BACKEND_DEFAULT) net.setPreferableTarget(cv2.dnn.DNN_TARGET_CPU) ln = net.getLayerNames() ln = [ln[i - 1] for i in net.getUnconnectedOutLayers()] # Define screen capture area print("[INFO] loading screencapture device…") W, H = None, None origbox = (int(Wd/2 - ACTIVATION_RANGE/2), int(Hd/2 - ACTIVATION_RANGE/2), int(Wd/2 + ACTIVATION_RANGE/2), int(Hd/2 + ACTIVATION_RANGE/2)) # Log whether aimbot is enabled if not ENABLE_AIMBOT: print("[INFO] aimbot disabled, using visualizer only…") else: print(colored("[OKAY] Aimbot enabled!", "green")) # Handle Ctrl+C in terminal, release pointers def signal_handler(sig, frame): # release the print("Do not run this file directly.") file pointers print("\n[INFO] cleaning up…") sct.close() # .exit() does not exist for mss.mss() cv2.destroyAllWindows() # Delete downloaded files and remove temp directory if os.path.exists(weightsPath): os.remove(weightsPath) if os.path.exists(configPath): os.remove(configPath) if os.path.exists(labelsPath): os.remove(labelsPath) if os.path.exists(temp_dir): os.rmdir(temp_dir) sys.exit(0) signal.signal(signal.SIGINT, signal_handler) print() # loop over frames from the video file stream while True: start_time = timeit.default_timer() frame = np.array(grab_screen(region=origbox)) frame = cv2.cvtColor(frame, cv2.COLOR_RGBA2BGR) # if the frame dimensions are empty, grab them if W is None or H is None: (H, W) = frame.shape[: 2] frame = cv2.UMat(frame) # construct a blob from the input frame and then perform a forward # pass of the YOLO object detector, giving us our bounding boxes # and associated probabilities blob = cv2.dnn.blobFromImage(frame, 1/260, (150, 150), swapRB=True, crop=True) net.setInput(blob) layerOutputs = net.forward(ln) # initialize our lists of detected bounding boxes, confidences, # and class IDs, respectively boxes = [] confidences = [] classIDs = [] # loop over each of the layer outputs for output in layerOutputs: # loop over each of the detections for detection in output: # extract the class ID and confidence (i.e., probability) # of the current object detection scores = detection[5:] classID = 0 # person = 0 confidence = scores[classID] # filter out weak predictions by ensuring the detected # probability is greater than the minimum probability if confidence > CONFIDENCE: box = detection[0: 4] * np.array([W, H, W, H]) (centerX, centerY, width, height) = box.astype("int") # use the center (x, y)-coordinates to derive the top # and and left corner of the bounding box x = int(centerX - (width / 2)) y = int(centerY - (height / 2)) # update our list of bounding box coordinates, # confidences, and class IDs boxes.append([x, y, int(width), int(height)]) confidences.append(float(confidence)) classIDs.append(classID) # apply non-maxima suppression to suppress weak, overlapping # bounding boxes idxs = cv2.dnn.NMSBoxes(boxes, confidences, CONFIDENCE, THRESHOLD) # ensure at least one detection exists if len(idxs) > 0: # Find best player match bestMatch = confidences[np.argmax(confidences)] # loop over the indexes we are keeping for i in idxs.flatten(): # extract the bounding box coordinates (x, y) = (boxes[i][0], boxes[i][1]) (w, h) = (boxes[i][2], boxes[i][3]) # draw target dot on the frame cv2.circle(frame, (int(x + w / 2), int(y + h / 3)), 2, (0, 0, 255), -1) # draw a bounding box rectangle and label on the frame cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 1) text = "enemy {}%".format(int(confidences[i] * 100)) cv2.putText(frame, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2) if ENABLE_AIMBOT and bestMatch == confidences[i]: mouseX = origbox[0] + (x + w/1.55) mouseY = origbox[1] + (y + h/2.50) set_pos(mouseX, mouseY) cv2.imshow("Neural Net Vision (Pine)", frame) elapsed = timeit.default_timer() - start_time sys.stdout.write( "\r{1} FPS with {0} MS interpolation delay \t".format(int(elapsed*1000), int(1/elapsed))) sys.stdout.flush() if cv2.waitKey(1) & 0xFF == ord('0'): break # Clean up on exit signal_handler(0, 0)Pontos a observar:
- Alteração dos URLs: Os URLs foram corrigidos para apontar para os arquivos brutos (
/raw/main/). - Verifique a estrutura dos arquivos: Garanta que os arquivos
.cfge.weightsestejam corretos e que possam ser lidos pelo OpenCV.
Agora, o código deve baixar corretamente os arquivos de configuração e pesos do GitHub e carregá-los no OpenCV. Certifique-se de que o repositório GitHub contenha os arquivos corretos e que os links estejam acessíveis.
- Altere os URLs para os arquivos no GitHub para usar