Advertisement
Guest User

Python Aimbot with Machine Vision

a guest
May 21st, 2019
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.03 KB | None | 0 0
  1. import ctypes
  2. import cv2
  3. import mss
  4. import numpy
  5. import os
  6. import signal
  7. import sys
  8. import time
  9.  
  10. from libs import Mouse
  11.  
  12. class Point(ctypes.Structure):
  13.     _fields_ = [("x", ctypes.c_long), ("y", ctypes.c_long)]
  14.  
  15. class Yolo:
  16.     def __init__(self, configuration, weights):
  17.         # Control handles.
  18.         self.mouse = Mouse()
  19.  
  20.         # Detection configuration.
  21.         self.activation = 512
  22.         self.confidence = 0.36
  23.         self.threshold = 0.22
  24.  
  25.         # Load YOLO model.
  26.         self.neural_network = cv2.dnn.readNetFromDarknet(configuration, weights)
  27.         self.neural_network.setPreferableBackend(cv2.dnn.DNN_BACKEND_DEFAULT)
  28.         self.neural_network.setPreferableTarget(cv2.dnn.DNN_TARGET_OPENCL)
  29.        
  30.         # Select the required output layer names.
  31.         self.layer_names = self.neural_network.getLayerNames()
  32.         self.layer_names = [self.layer_names[i[0] - 1] for i in self.neural_network.getUnconnectedOutLayers()]
  33.  
  34.         # Capture configuration.
  35.         self.sct = mss.mss()
  36.         self.width, self.height = None, None
  37.         self.screen_width, self.screen_height = ctypes.windll.user32.GetSystemMetrics(0), ctypes.windll.user32.GetSystemMetrics(1)
  38.         self.bounding_box = (int(self.screen_width / 2 - self.activation / 2),
  39.                             int(self.screen_height / 2 - self.activation / 2),
  40.                             int(self.screen_width / 2 + self.activation / 2),
  41.                             int(self.screen_height / 2 + self.activation / 2))
  42.  
  43.         # Enable OpenCL if supported.
  44.         if cv2.ocl.haveOpenCL():
  45.             cv2.ocl.setUseOpenCL(True)
  46.             cv2.ocl.useOpenCL()
  47.             print("Using OpenCL.")
  48.         else:
  49.             print("No GPU acceleration.")
  50.  
  51.     def start(self):
  52.         start_time = time.time()
  53.  
  54.         # YOLO loop.
  55.         while True:
  56.             # Grab frame, resize it, and convert it from RGBA to BGR to work with OpenCV.
  57.             frame = numpy.array(self.sct.grab(self.bounding_box))
  58.             frame = cv2.resize(frame, (self.activation, self.activation))
  59.             frame = cv2.cvtColor(frame, cv2.COLOR_RGBA2BGR)
  60.  
  61.             # Get frame shape if None.
  62.             if self.width is None or self.height is None:
  63.                 (self.height, self.width) = frame.shape[:2]
  64.  
  65.             # Convert frame to matrix object for GPU use.
  66.             frame = cv2.UMat(frame)
  67.  
  68.             # Create a blob for the neural network.
  69.             # Perform a forward pass using YOLO.
  70.             # Recieve bounding boxes and associated probabilities.
  71.             blob = cv2.dnn.blobFromImage(frame, 1 / 260.0, (416, 416), swapRB=False, crop=False)
  72.             self.neural_network.setInput(blob)
  73.             outputs = self.neural_network.forward(self.layer_names)
  74.  
  75.             # Intialise lists for detected bounding boxes, confidences, and class IDs.
  76.             boxes = []
  77.             confidences = []
  78.             class_ids = []
  79.  
  80.             # Loop through the outputs from the neural network and parse detections.
  81.             for output in outputs:
  82.                 for detection in output:
  83.                     # Class ID of 0 is equal to person. Extract this from our current detection.
  84.                     scores = detection[5:]
  85.                     class_id = 0
  86.                     confidence = scores[0]
  87.  
  88.                     if confidence > self.confidence:
  89.                         # Scale the bounding box coordinates to the size of the frame.
  90.                         # YOLO returns the center coordinates followed by width and height.
  91.                         box = detection[0:4] * numpy.array([self.width, self.height, self.width, self.height])
  92.                         (x_center, y_center, w, h) = box.astype("int")
  93.  
  94.                         # Using the bounding box coordinates, derive the top and left corner as y, x respectively.
  95.                         x = int(x_center - (w / 2))
  96.                         y = int(y_center - (h / 2))
  97.  
  98.                         boxes.append([x, y, int(w), int(h)])
  99.                         confidences.append(float(confidence))
  100.                         class_ids.append(class_id)
  101.  
  102.             # Surpress weak, and overlapping bounding boxes using non-maxima surpression.
  103.             found = cv2.dnn.NMSBoxes(boxes, confidences, self.confidence, self.threshold)
  104.  
  105.             if len(found) > 0:
  106.                 best_match = confidences[numpy.argmax(confidences)]
  107.                 skip = False
  108.  
  109.                 # Check is the mouse is already on the target.
  110.                 for i in found.flatten():
  111.                     (x, y) = (boxes[i][0], boxes[i][1])
  112.                     (w, h) = (boxes[i][2], boxes[i][3])
  113.  
  114.                     mouse_x, mouse_y = (self.bounding_box[0] + x + w / 2, self.bounding_box[1] + y + h / 8)
  115.                     current_mouse_x, current_mouse_y = self.mouse.get_position()
  116.  
  117.                     if abs(mouse_x - current_mouse_x) < w * 2 and abs(mouse_y - current_mouse_y) < h * 2:
  118.                         skip = True
  119.  
  120.                         if abs(mouse_x - current_mouse_x) > w * 0.5 or abs(mouse_y - current_mouse_y) > h * 0.5:
  121.                             self.mouse.move_mouse((mouse_x, mouse_y))                  
  122.  
  123.                 # Loop over the indexes we are keeping.
  124.                 if not skip:
  125.                     for i in found.flatten():
  126.                         (x, y) = (boxes[i][0], boxes[i][1])
  127.                         (w, h) = (boxes[i][2], boxes[i][3])
  128.  
  129.                         if best_match == confidences[i]:
  130.                             mouse_x = self.bounding_box[0] + x + w / 2
  131.                             mouse_y = self.bounding_box[1] + y + h / 8
  132.                             self.mouse.move_mouse((mouse_x, mouse_y))
  133.  
  134.             print("FPS: ", 1.0 / (time.time() - start_time))
  135.  
  136.         self.sct.close()
  137.         cv2.destroyAllWindows()
  138.         sys.exit(0)
  139.  
  140. def main():
  141.     aimbot = Yolo(os.path.sep.join(["models", "yolo-v3-tiny.cfg"]), os.path.sep.join(['models', "yolo-v3-tiny.weights"]))
  142.     aimbot.start()
  143.  
  144. if __name__ == "__main__":
  145.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement