def process_image_and_get_ratios(image_path):
image = cv2.imread(image_path, cv2.IMREAD_UNCHANGED)
# Ensure the image has an alpha channel
raise ValueError("Image does not have an alpha channel.")
frame_height, frame_width = image.shape[:2]
# Use the alpha channel as the mask
alpha_channel = image[:, :, 3]
# You may need to adjust the threshold if your rectangle is semi-transparent
_, mask = cv2.threshold(alpha_channel, 1, 255, cv2.THRESH_BINARY)
# Find contours in the mask
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Check if any contours were found
# No contours found, the image might be fully transparent
print("No rectangle found in the image.")
return (-1, -1), (0, 0) # No position, no size ratio
# Assuming the rectangle is the largest contour
largest_contour = max(contours, key=cv2.contourArea)
# Get the bounding box of the largest contour
x, y, w, h = cv2.boundingRect(largest_contour)
# Draw a circle at the top-left corner of the rectangle
cv2.circle(image, (x, y), 5, (0, 255, 0), -1)
# Convert image to display if it has an alpha channel
# Convert to BGR format for display
display_image = cv2.cvtColor(image, cv2.COLOR_BGRA2BGR)
cv2.imshow('Processed Image', display_image)
cv2.waitKey(0) # Wait for a key press to close
# Calculate the width and height ratios
width_ratio = w / frame_width
height_ratio = h / frame_height
# Return the top-left corner coordinates and size ratios
return (x, y), (width_ratio, height_ratio)
image_path = 'path_to_your_image_with_alpha_channel.png'
top_left_corner, size_ratios = process_image_and_get_ratios(image_path)
if top_left_corner == (-1, -1):
print("The image is all transparent or no rectangle found.")
print(f"Top-left corner: {top_left_corner}")
print(f"Width ratio: {size_ratios[0]}, Height ratio: {size_ratios[1]}")