import cv2
import numpy as np

img = cv2.imread(r"C:\Users\Certes\.gemini\antigravity\brain\975cea00-dd68-4689-9ee3-f1a2408b4ee6\raw_super_block.png")
if img is None:
    print("Image not found")
    exit()

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, bin_inv = cv2.threshold(gray, 200, 255, cv2.THRESH_BINARY_INV)

# Staff lines are y=76 to y=152
# A vertical bar line is a vertical strip of black pixels from 76 to 151
# Sum down the columns
col_sums = np.sum(bin_inv[76:152, :], axis=0) / 255.0

# If a column has > 70 black pixels out of the 76 height, it's a solid vertical line
bar_xs = np.where(col_sums > 70)[0]

# Group adjacent pixels into single lines
grouped_bars = []
if len(bar_xs) > 0:
    current_group = [bar_xs[0]]
    for x in bar_xs[1:]:
        if x - current_group[-1] <= 5:
            current_group.append(x)
        else:
            grouped_bars.append(int(np.mean(current_group)))
            current_group = [x]
    grouped_bars.append(int(np.mean(current_group)))

print(f"Found {len(grouped_bars)} vertical barlines:")
print(grouped_bars)

# Draw lines
out = img.copy()
for x in grouped_bars:
    cv2.line(out, (x, 0), (x, out.shape[0]), (0, 0, 255), 2)
cv2.imwrite(r"C:\Users\Certes\.gemini\antigravity\brain\975cea00-dd68-4689-9ee3-f1a2408b4ee6\test_barlines.png", out)
