from PIL import Image

def gamma_correction(image_path, gamma):
    """
    Applies gamma correction to the given image file path.

    Args:
        image_path (str): The file path of the image.
        gamma (float): The gamma value to apply (e.g., <1 to brighten, >1 to darken).

    Returns:
        PIL.Image.Image: The gamma-corrected image.
    """
    # Open the image from the file path
    image = Image.open(image_path)
    
    if gamma <= 0:
        raise ValueError("Gamma value must be greater than 0.")
    
    # Normalize the gamma value
    inv_gamma = 1.0 / gamma
    
    # Check the image mode and create the corresponding LUT (lookup table)
    if image.mode == 'RGB':
        # Create a 3-channel LUT (one for each color channel)
        table = []
        for i in range(256):
            corrected_value = int((i / 255.0) ** inv_gamma * 255)
            table.extend([corrected_value] * 3)  # Add the same corrected value for each channel
    else:
        # For grayscale images, create a single-channel LUT
        table = [int((i / 255.0) ** inv_gamma * 255) for i in range(256)]
    
    # Apply gamma correction using the LUT
    corrected_image = image.point(table)
    
    return corrected_image
