import numpy as np from termcolor import colored import timeit import thread import…
- User
import numpy as np from termcolor import colored import timeit import _thread 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 - (1360 / 2)) y = int(y - (768 / 2))
#time.sleep(000000.0000000000000000009)x = 1 + int(x * 65536. / Wd)
y = 1 + int(y * 65536. / Hd)
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 THRESHOLD = 0.01 #THRESHOLD = 0.22 Estava usando esete antes de 0.01 #THRESHOLD_NMS = 0.3 #CONFIDENCE = 0.36 #THRESHOLD = 0.22 # # 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 #Uso pessoal-01 ACTIVATION_RANGE = 100 #Uso pessoal-01 ACTIVATION_RANGE = 116 - Durante Lives #Uso pessoal-01 ACTIVATION_RANGE = 120 #Uso pessoal-01 ACTIVATION_RANGE = 150 - Bom pra Jogar #Uso pessoal-0 2ACTIVATION_RANGE = 185 #TO LIVES ACTIVATION_RANGE = 85 #Original ACTIVATION_RANGE = 250 # 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) net.setPreferableBackend(cv2.dnn.DNN_BACKEND_DEFAULT) net.setPreferableTarget(cv2.dnn.DNN_TARGET_OPENCL) net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA) net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA) ln = net.getLayerNames() #ln = [ln[i[0] - 1] for i in net.getUnconnectedOutLayers()] 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.__exit__() cv2.destroyAllWindows() sys.exit(0) signal.signal(signal.SIGINT, signal_handler) # Test for GPU support build_info = str("".join(cv2.getBuildInformation().split())) if cv2.ocl.haveOpenCL(): cv2.ocl.setUseOpenCL(True) cv2.ocl.useOpenCL() print(colored("[OKAY] OpenCL is working!", "green")) else: print( colored("[WARNING] OpenCL acceleration is disabled!", "yellow")) if "CUDA:YES" in build_info: print(colored("[OKAY] CUDA is working!", "green")) else: print( colored("[WARNING] CUDA acceleration is disabled!", "yellow")) 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), #blob = cv2.dnn.blobFromImage(frame, 1 / 260, (150, 150), swapRB=True, crop=True) #swapRB=False, crop=False) 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:] #scores = detection[5:] # classID = np.argmax(scores) # confidence = scores[classID] 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: # scale the bounding box coordinates back relative to # the size of the image, keeping in mind that YOLO # actually returns the center (x, y)-coordinates of # the bounding box followed by the boxes' width and # height 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) #cv2.circle(frame, (int(x + w / 2), int(y + h / 3)), 2, (0, 0, 255), -1)Corpo no 5 é cabeça # draw a bounding box rectangle and label on the frame # color = [int(c) for c in COLORS[classIDs[i]]] 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)#(y + h/3) corpo (y + h/5)Cabeça #mouseY = origbox[1] + (y + h/2.50) usando antes 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)preciso usar a GPU invez da CPU eu tenho GPU implemente uma forma de detectar a GPU para aumentar a aceleração de FPS
- Assistant
Para garantir que seu código utilize a GPU para acelerar os processos e aumentar o FPS, precisamos ajustar algumas configurações e verificações no código. Já que você mencionou usar OpenCL e CUDA, podemos seguir alguns passos específicos para conferir e aplicar essas tecnologias.
Aqui está uma versão aprimorada do seu código, com a GPU (tanto OpenCL quanto CUDA) tendo preferência para detecção e processamento. Vamos reforçar a verificação e aplicar a configuração correta.
import numpy as np from termcolor import colored import timeit import _thread 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 - (1360 / 2)) y = int(y - (768 / 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 THRESHOLD = 0.01 #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.__exit__() 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)Notas importantes:
- Verificação de GPU: O script primeiro verifica se há dispositivos CUDA disponíveis (
cv2.cuda.getCudaEnabledDeviceCount()). Se não, verifica se há suporte a OpenCL (cv2.ocl.haveOpenCL()). - Configuração de Backend e Target: Dependendo da disponibilidade de CUDA ou OpenCL, o backend e o target são configurados respectivamente. Caso nenhum esteja disponível, o script recorre ao uso da CPU.
- Updates e Debugging: Todos os prints foram atualizados para indicar claramente quais recursos estão sendo utilizados.
Com essas modificações, seu código tentará utilizar a GPU disponível, seja CUDA ou OpenCL, para executar o processamento, potencialmente aumentando o FPS e a eficiência geral do script.
- Verificação de GPU: O script primeiro verifica se há dispositivos CUDA disponíveis (
- User
[INFO] loading screencapture device… [OKAY] Aimbot enabled!
[ WARN:0@2.884] global ocl4dnn_conv_spatial.cpp:1933 cv::dnn::ocl4dnn::OCL4DNNConvSpatial::loadTunedConfig OpenCV(ocl4dnn): consider to specify kernel configuration cache directory through OPENCV_OCL4DNN_CONFIG_PATH parameter. OpenCL program build log: dnn/dummy Status -11: CL_BUILD_PROGRAM_FAILURE -cl-no-subgroup-ifp Error in processing command line: Don't understand command line argument "-cl-no-subgroup-ifp"! 22 FPS with 44 MS interpolation delay Traceback (most recent call last): File "C:\Users\Wendel\Desktop\Apex_Aimbot_PY\teste\pine.py", line 14, in File "C:\Users\Wendel\Desktop\Apex_Aimbot_PY\teste\lib\pine.py", line 230, in start set_pos(mouseX, mouseY) ii = pynput.util.win32.INPUT_union() ^^^^^^^^^^^ AttributeError: module 'pynput' has no attribute 'util'. Did you mean: '_util'?
- Assistant
O erro que você está enfrentando tem duas partes principais:
-
Erro no OpenCL:
OpenCL program build log: dnn/dummy Status -11: CL_BUILD_PROGRAM_FAILURE -cl-no-subgroup-ifp Error in processing command line: Don't understand command line argument "-cl-no-subgroup-ifp"!Esse erro sugere que há um problema na construção do programa OpenCL. Parece que algum argumento da linha de comando fornecido ao compilador OpenCL não está sendo reconhecido. Você pode tentar desativar temporariamente o uso do OpenCL para ver se isso resolve o problema temporariamente.
-
Erro no
pynput:AttributeError: module 'pynput' has no attribute 'util'. Did you mean: '_util'?Esse erro significa que há um erro de digitação no seu uso do módulo
pynput. O nome correto é_util, e nãoutil.
Vamos primeiro corrigir o erro do
pynpute depois alterar o código para desativar temporariamente o OpenCL e garantir que o código pelo menos execute sem esses problemas. Posteriormente, se necessário, vamos ajustar o problema do OpenCL.Corrigindo o
pynputAltere a linha:
ii = pynput.util.win32.INPUT_union()Para:
ii = pynput._util.win32.INPUT_union()Desativando o OpenCL Temporariamente
Você pode comentar as linhas que configuram o OpenCL e usar CUDA ou CPU apenas. Aqui está o código atualizado:
import numpy as np from termcolor import colored import timeit import _thread 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 - (1360 / 2)) y = int(y - (768 / 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 THRESHOLD = 0.01 #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.__exit__() 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)Explicação das Modificações:
- Correção do
pynput: Foi corrigido o uso depynput._util.win32no métodoset_pos. - Desativação Temporária do OpenCL: Comentamos a seção que configura OpenCL para evitar o erro de construção do programa OpenCL. O código agora tentará usar CUDA se disponível; caso contrário, usará a CPU.
Ao executar esse novo código, verifique se está funcionando conforme esperado e depois considere reabilitar o OpenCL e ajustar quaisquer problemas restantes.
-