|
| 1 | +from os import PathLike |
| 2 | +from pathlib import Path |
| 3 | + |
| 4 | +import cv2 |
| 5 | +from rdflib import XSD |
| 6 | + |
| 7 | +from tamper.vocabularies import TAMPER |
| 8 | + |
| 9 | +from tamper.core import ImageAsset, Operation, MappedProperty |
| 10 | + |
| 11 | + |
| 12 | +_INTERPOLATIONS = { |
| 13 | + "nearest": cv2.INTER_NEAREST, |
| 14 | + "linear": cv2.INTER_LINEAR, |
| 15 | + "cubic": cv2.INTER_CUBIC, |
| 16 | + "area": cv2.INTER_AREA, |
| 17 | + "lanczos4": cv2.INTER_LANCZOS4, |
| 18 | +} |
| 19 | + |
| 20 | + |
| 21 | +class Resize(Operation): |
| 22 | + __rdf_type__ = TAMPER.Resize |
| 23 | + |
| 24 | + width: MappedProperty[int] = MappedProperty(TAMPER.targetWidth, XSD.integer) |
| 25 | + height: MappedProperty[int] = MappedProperty(TAMPER.targetHeight, XSD.integer) |
| 26 | + interpolation: MappedProperty[str] = MappedProperty( |
| 27 | + TAMPER.interpolation, XSD.string |
| 28 | + ) |
| 29 | + |
| 30 | + def mutate(self, out_dir: PathLike[str] | None = None): |
| 31 | + used = self.get_used() |
| 32 | + if len(used) != 1: |
| 33 | + raise ValueError("Operation requires exactly one image asset") |
| 34 | + |
| 35 | + img_asset = ImageAsset(self.graph, used[0]) |
| 36 | + |
| 37 | + img = cv2.imread(img_asset.file_path) |
| 38 | + resized = cv2.resize( |
| 39 | + img, |
| 40 | + (self.width, self.height), |
| 41 | + interpolation=_INTERPOLATIONS[self.interpolation], |
| 42 | + ) |
| 43 | + ext = Path(img_asset.file_path).suffix or ".png" |
| 44 | + ok, buf = cv2.imencode(ext, resized) |
| 45 | + if not ok: |
| 46 | + raise RuntimeError(f"Encoding to {ext} failed") |
| 47 | + |
| 48 | + with self._generates_file(dir=out_dir, suffix=ext) as f: |
| 49 | + Path(f).write_bytes(buf.tobytes()) |
0 commit comments