import cv2
import numpy as np

def find_measure_boundaries(img_bgr, max_width=1280):
    img_gray = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2GRAY)
    _, bin_inv = cv2.threshold(img_gray, 180, 255, cv2.THRESH_BINARY_INV)
    staff_region = bin_inv[50:160, :]
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 40))
    vertical_lines = cv2.morphologyEx(staff_region, cv2.MORPH_OPEN, kernel)
    proj = np.sum(vertical_lines, axis=0) / 255
    peaks = np.where(proj > 30)[0]
    
    valid_peaks = [p for p in peaks if p <= max_width - 15]
    if not valid_peaks: return max_width
    return valid_peaks[-1] + 10

if __name__ == "__main__":
    img = cv2.imread(r'C:\Users\Certes\.gemini\antigravity\brain\975cea00-dd68-4689-9ee3-f1a2408b4ee6\raw_super_block.png')
    for w_cap in [1280, 2000, 2560]:
        cw = min(w_cap, img.shape[1])
        cut_x = find_measure_boundaries(img[:, :cw], cw)
        print(f"Max {cw} => Cut at {cut_x}")
        out = img[:, :cw].copy()
        cv2.line(out, (cut_x, 0), (cut_x, out.shape[0]), (0, 0, 255), 2)
        cv2.imwrite(r'C:\Users\Certes\.gemini\antigravity\brain\975cea00-dd68-4689-9ee3-f1a2408b4ee6\slice_'+str(w_cap)+'.png', out)
