from PIL import Image

def clamp_alpha(image_path, output_path, direction, level):
    try:
        # Open the image
        img = Image.open(image_path).convert("RGBA")  # Ensure image has an alpha channel
        width, height = img.size

        # Create a new image to store the result
        new_img = Image.new("RGBA", (width, height))

        # Iterate through all pixels
        if direction == "up":
            for y in range(height):
                for x in range(width):
                    r, g, b, a = img.getpixel((x, y))
                    # Clamp alpha to 0 or 255
                    a = 255 if a > 0 else 0
                    new_img.putpixel((x, y), (r, g, b, a))
        elif direction == "down":
            for y in range(height):
                for x in range(width):
                    r, g, b, a = img.getpixel((x, y))
                    # Clamp alpha to 0 or 255
                    a = 0 if a < 255 else 255
                    new_img.putpixel((x, y), (r, g, b, a))
        elif direction == "level":
            if not (0 <= level <= 1):
                raise ValueError("Level must be between 0 and 1.")
            a_lim= int(level * 255)  # Convert level to a value between 0 and 255
            for y in range(height):
                for x in range(width):
                    r, g, b, a = img.getpixel((x, y))
                    # Clamp alpha down only if it is less than the level
                    if a < a_lim:
                        a = 0
                    else:
                        a = 255
                    new_img.putpixel((x, y), (r, g, b, a))
        else:
            raise ValueError("Invalid direction. Use 'up', 'down', or 'level'.")
        # Print statistics
        # Save the resulting image
        new_img.save(output_path)
        print(f"Alpha clamped image saved to {output_path}")
    except Exception as e:
        print(f"Error: {e}")
import argparse
parser = argparse.ArgumentParser(description="Clamp alpha channel of an image. Use 'up' to set alpha > 0 to 255, 'down' to set alpha < 255 to 0, or 'level' to set alpha < level to 0 and >= level to 255 (0.0<=level<=1.0).")
parser.add_argument("image_path", type=str, help="Path to the input image file.")
parser.add_argument("direction", type=str, choices=["up", "down","level"], default="up",
                    help="Direction to clamp alpha channel: 'up' for 255, 'down' for 0.")
parser.add_argument("--level", type=float, default=0.5,
                    help="Level to clamp alpha channel, used only if direction is 'level'.")
args = parser.parse_args()
image_path = args.image_path
direction = args.direction
level = args.level
if level < 0 or level > 1:
    raise ValueError("Level must be between 0 and 1.")

# Example usage
# image_path = "shijima.png"  # Replace with your input image file path
output_path = "clamp.png"  # Replace with your desired output file path
clamp_alpha(image_path, output_path, direction=direction, level=level)