[Python] How to improve this class to have reduced memory usage and better performance?

Discussão em 'Python' iniciado por Stack, Outubro 5, 2024.

  1. Stack

    Stack Membro Participativo

    I'm trying to increase my FPS of my program, but this class is using too much memory which slows down performance. How can I improve this class so my program can take screenshots faster and perform better.

    import cv2
    import numpy as np

    # Work on this to cut down memory and boost performance
    class ObjectDetection:

    def __init__(self):
    self.avg_y_obstacle = None
    self.avg_x_obstacle = None
    self.avg_y_jump = None
    self.avg_x_jump = None

    # Preload templates for obstacle detection to optimize performance
    self.templates = {
    'template1': cv2.imread('template1.png', 0),
    'template2': cv2.imread('template2.png', 0),
    'template3': cv2.imread('template3.png', 0),
    'template4': cv2.imread('template4.png', 0),
    'template5': cv2.imread('template5.png', 0),
    'template6': cv2.imread('template6.png', 0),
    'template7': cv2.imread('template7.png', 0),
    'template8': cv2.imread('template8.png', 0)
    }
    # Check if all templates loaded properly
    for name, template in self.templates.items():
    if template is None:
    raise ValueError(f"Error loading template: {name}")

    def ObstacleDetect(self, imageInput=None, threshold=0.8):
    if imageInput is None:
    raise ValueError("Input image is required")

    # Convert input image to grayscale
    image_gray = cv2.cvtColor(imageInput, cv2.COLOR_BGR2GRAY)

    coordinates = []

    # Iterate over each preloaded template
    for name, template in self.templates.items():
    h, w = template.shape[:2] # Get template dimensions

    # Perform template matching
    result = cv2.matchTemplate(image_gray, template, cv2.TM_CCOEFF_NORMED)
    loc = np.where(result >= threshold)

    # Collect coordinates for detected objects and draw bounding boxes
    for pt in zip(*loc[::-1]):
    coordinates.append((pt[0], pt[1], pt[0] + w, pt[1] + h))
    # cv2.rectangle(imageInput, (pt[0], pt[1]), (pt[0] + w, pt[1] + h), (0, 255, 0), 2)
    # cv2.putText(imageInput, name, (pt[0], pt[1] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1)

    # Calculate avg_x_obstacle and avg_y_obstacle if coordinates are found
    if coordinates:
    coordinates = np.array(coordinates)
    self.avg_y_obstacle = np.mean(coordinates[:, 1]) # Average y-coordinate of top-left
    self.avg_x_obstacle = np.mean(coordinates[:, 0]) # Average x-coordinate of top-left
    else:
    print("No obstacles detected.")
    self.avg_y_obstacle = None
    self.avg_x_obstacle = None

    return imageInput

    def findJumpArea(self, image=None, threshold=0.8):
    # Load the jump template once
    template = cv2.imread('jump_template.png', 0)
    if image is None or template is None:
    raise ValueError("Error: Could not load input image or template image.")

    # Convert image to grayscale
    image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    h, w = template.shape[:2]

    # Perform template matching
    result = cv2.matchTemplate(image_gray, template, cv2.TM_CCOEFF_NORMED)
    loc = np.where(result >= threshold)

    coordinates = []

    # Collect detected jump area coordinates and draw lines
    for pt in zip(*loc[::-1]):
    coordinates.append((pt[0], pt[1]))
    # line_length = 50
    # cv2.line(image, (pt[0], pt[1]), (pt[0] + line_length, pt[1]), (0, 255, 0), 2)

    # Calculate avg_x_jump and avg_y_jump if coordinates are found
    if coordinates:
    coordinates = np.array(coordinates)
    self.avg_y_jump = np.mean(coordinates[:, 1]) # Average y-coordinate of the top-left point
    self.avg_x_jump = np.mean(coordinates[:, 0]) # Average x-coordinate of the top-left point
    else:
    print("No jump area detected.")
    self.avg_y_jump = None
    self.avg_x_jump = None

    return image

    # Getters for average coordinates
    def getObstacleAvgY(self):
    return self.avg_y_obstacle

    def getObstacleAvgX(self):
    return self.avg_x_obstacle

    def getJumpAvgY(self):
    return self.avg_y_jump

    def getJumpAvgX(self):
    return self.avg_x_jump



    I tried preloading the templates and commented out some cv visual stuff, it slightly improved performance. However, that was all I could come up with.

    Continue reading...

Compartilhe esta Página