Shield external portal jumps (keep EXTERNAL_* for later), serve /nav from static build, and proxy /book + /community to vertical Next apps with Caddy notes. Co-authored-by: Cursor <cursoragent@cursor.com>
92 lines
2.6 KiB
Python
92 lines
2.6 KiB
Python
from PIL import Image, ImageOps, ImageFilter
|
|
import os
|
|
|
|
|
|
def load_landscape(path):
|
|
im = ImageOps.exif_transpose(Image.open(path)).convert("RGB")
|
|
if im.size[1] > im.size[0]:
|
|
im = im.rotate(90, expand=True)
|
|
return im
|
|
|
|
|
|
def score_horizontal(gray):
|
|
w, h = gray.size
|
|
px = gray.load()
|
|
score = 0
|
|
step = 3
|
|
for y in range(2, h - 2, step):
|
|
row = 0
|
|
for x in range(2, w - 2, step):
|
|
g = abs(px[x, y + 1] - px[x, y - 1])
|
|
if g > 40:
|
|
row += g
|
|
score += row * row
|
|
return score
|
|
|
|
|
|
def best_deskew(im, span=12.0, step=0.25):
|
|
gray = im.convert("L")
|
|
max_w = 900
|
|
if gray.size[0] > max_w:
|
|
gray = gray.resize(
|
|
(max_w, int(gray.size[1] * max_w / gray.size[0])),
|
|
Image.Resampling.BILINEAR,
|
|
)
|
|
best_a, best_s = 0.0, -1
|
|
a = -span
|
|
while a <= span + 1e-9:
|
|
rot = gray.rotate(a, resample=Image.BILINEAR, fillcolor=255)
|
|
s = score_horizontal(rot)
|
|
if s > best_s:
|
|
best_s, best_a = s, a
|
|
a += step
|
|
return best_a
|
|
|
|
|
|
def export(im, dst):
|
|
w, h = im.size
|
|
if w > 2000:
|
|
im = im.resize((2000, int(h * 2000 / w)), Image.Resampling.LANCZOS)
|
|
# ensure min width/height roughly meet guideline
|
|
if im.size[0] < 1280:
|
|
scale = 1280 / im.size[0]
|
|
im = im.resize(
|
|
(1280, int(im.size[1] * scale)), Image.Resampling.LANCZOS
|
|
)
|
|
im = ImageOps.autocontrast(im, cutoff=0.5)
|
|
im = im.filter(ImageFilter.UnsharpMask(radius=1.0, percent=60, threshold=2))
|
|
q = 88
|
|
for q in range(88, 45, -4):
|
|
im.save(dst, "JPEG", quality=q, optimize=True)
|
|
sz = os.path.getsize(dst)
|
|
if 100_000 <= sz <= 200_000:
|
|
return sz, q
|
|
if sz < 100_000:
|
|
im.save(dst, "JPEG", quality=min(q + 4, 92), optimize=True)
|
|
return os.path.getsize(dst), q
|
|
return os.path.getsize(dst), q
|
|
|
|
|
|
def main():
|
|
for name in ["11", "22"]:
|
|
src = rf"C:\Users\admin\Desktop\{name}.jpg"
|
|
dst = rf"C:\Users\admin\Desktop\{name}_heng.jpg"
|
|
im = load_landscape(src)
|
|
ang = best_deskew(im)
|
|
print(name, "angle", ang)
|
|
if abs(ang) >= 0.2:
|
|
im = im.rotate(
|
|
ang, resample=Image.BICUBIC, expand=True, fillcolor=(255, 255, 255)
|
|
)
|
|
w, h = im.size
|
|
m = int(min(w, h) * 0.01)
|
|
if m > 0:
|
|
im = im.crop((m, m, w - m, h - m))
|
|
sz, q = export(im, dst)
|
|
out = Image.open(dst)
|
|
print(" ", dst, "bytes", sz, "q", q, "WH", out.size)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|