folio-spread-bench / split_pages.py
foliokestrel's picture
Release 212 reviewed cBAD spreads, archive-held-out gutter evaluation, reproducible baselines and a reviewed PNG splitter.
6a484d2 verified
Raw History Blame Contribute Delete
2.59 kB
"""Export two PNGs along a user-reviewed line on a single-frame scan."""
import argparse
import math
from pathlib import Path
import tempfile
from PIL import Image, ImageDraw, ImageOps
def split_pages(image, top_x, bottom_x):
"""Split an upright raster at normalized endpoints with no resampling."""
if any(not math.isfinite(x) or not 0 < x < 1 for x in (top_x,bottom_x)):
raise ValueError('Both endpoint fractions must lie strictly between 0 and 1')
if image.mode not in ('L','LA','RGB','RGBA'):
raise ValueError(f'Expected an 8-bit grayscale or RGB scan; received {image.mode}')
w,h=image.size
cuts=[math.floor(w*(top_x+(bottom_x-top_x)*(y+.5)/h)+.5) for y in range(h)]
low,high=min(cuts),max(cuts)
if low<1 or high>=w:
raise ValueError('The line would leave an empty page on at least one row')
left=image.crop((0,0,high,h))
right=image.crop((low,0,w,h))
if low!=high:
fill={'L':255,'LA':(255,0),'RGB':(255,255,255),'RGBA':(255,255,255,0)}[image.mode]
left_pen,right_pen=ImageDraw.Draw(left),ImageDraw.Draw(right)
for y,cut in enumerate(cuts):
if cut<high:
left_pen.line((cut,y,high-1,y),fill=fill)
if cut>low:
right_pen.line((0,y,cut-low-1,y),fill=fill)
return left,right
def main():
p=argparse.ArgumentParser(description=__doc__)
p.add_argument('image',type=Path)
p.add_argument('output_folder',type=Path,help='New directory for left.png and right.png')
p.add_argument('--top',required=True,type=float,help='Top endpoint as a fraction of width')
p.add_argument('--bottom',required=True,type=float,help='Bottom endpoint as a fraction of width')
args=p.parse_args()
if args.output_folder.exists():
p.error('Choose a new output directory')
with Image.open(args.image) as source:
if getattr(source,'n_frames',1)!=1:
p.error('Choose a single-frame scan')
image=ImageOps.exif_transpose(source)
if 'transparency' in image.info and image.mode in ('L','RGB'):
image=image.convert('RGBA')
left,right=split_pages(image,args.top,args.bottom)
options={k:image.info[k] for k in ('icc_profile','dpi') if k in image.info}
with tempfile.TemporaryDirectory(dir=args.output_folder.parent) as scratch:
pair=Path(scratch)/'pages'
pair.mkdir()
for name,page in [('left',left),('right',right)]:
page.save(pair/(name+'.png'),**options)
pair.rename(args.output_folder)
if __name__=='__main__':
main()