import cv2
import numpy as np

def image_for_mathias(name="1.jpg"):
    # Load and resize
    image = cv2.imread(name)
    height, width = image.shape[:2]
    image = cv2.resize(image, (int(width * 0.2), int(height * 0.2)))

    # Grayscale + blur
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    blurred = cv2.GaussianBlur(gray, (5, 5), 0)

    # Threshold to isolate object
    _, thresh = cv2.threshold(blurred, 50, 255, cv2.THRESH_BINARY_INV)

    # Find contours
    contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    c = max(contours, key=cv2.contourArea)

    # --- Step 1: Create mask ---
    mask = np.zeros_like(gray)
    cv2.drawContours(mask, [c], -1, 255, -1)

    # Add alpha channel
    b, g, r = cv2.split(image)
    rgba = cv2.merge([b, g, r, mask])

    # --- Step 2: Crop tightly with padding ---
    x, y, w, h = cv2.boundingRect(c)
    padding = 10
    x, y = max(0, x-padding), max(0, y-padding)
    w, h = min(rgba.shape[1]-x, w+2*padding), min(rgba.shape[0]-y, h+2*padding)
    cropped = rgba[y:y+h, x:x+w]

    # --- Step 3: Perspective transform ---
    rect = cv2.minAreaRect(c)
    box = cv2.boxPoints(rect)   # 4 corner points
    box = np.array(box, dtype="float32")

    # Order the points
    def order_points(pts):
        rect = np.zeros((4, 2), dtype="float32")
        s = pts.sum(axis=1)
        rect[0] = pts[np.argmin(s)]  # top-left
        rect[2] = pts[np.argmax(s)]  # bottom-right
        diff = np.diff(pts, axis=1)
        rect[1] = pts[np.argmin(diff)]  # top-right
        rect[3] = pts[np.argmax(diff)]  # bottom-left
        return rect

    src_pts = order_points(box)

    # Desired output size (tune for your code dimensions)
    W, H = 600, 200
    dst_pts = np.array([
        [0, 0],
        [W-1, 0],
        [W-1, H-1],
        [0, H-1]
    ], dtype="float32")

    # Warp with perspective correction
    M = cv2.getPerspectiveTransform(src_pts, dst_pts)
    warped = cv2.warpPerspective(rgba, M, (W, H), borderMode=cv2.BORDER_CONSTANT, borderValue=(0,0,0,0))

    # Save transparent deskewed image
    cv2.imwrite("spotify_code_deskewed.jpg", warped)

    # Show result
    cv2.imshow("Spotify Code Deskewed", warped)
    cv2.waitKey(0)
    cv2.destroyAllWindows()


l = ["1.jpg", "2.jpg", "3.jpg", "4.jpg"]
for name in l:
    image_for_mathias(name)