Skip to content

Instantly share code, notes, and snippets.

@priancho
Created June 4, 2021 16:06
Show Gist options
  • Save priancho/4496fa2b8507f0d2776b2e9a621a92eb to your computer and use it in GitHub Desktop.
Save priancho/4496fa2b8507f0d2776b2e9a621a92eb to your computer and use it in GitHub Desktop.
Convert image format from jp2k to jpeg
""" Convert jp2k image to jpeg.
# Install JPEG2k decoder first
sudo yum install -y libjpeg-devel
"""
import os
import argparse
from pathlib import Path
import cv2
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--input-file', required=True, help='Input image')
parser.add_argument('--output-root', required=True, help='Output root directory')
args = parser.parse_args()
return args
def main():
args = parse_args()
# open image
img = cv2.imread(args.input_file)
h, w, c = img.shape
# resize image
max_length = 1920 # book domain default max length
if w >= h:
new_w = max_length
new_h = int(h * (max_length / w))
else:
new_w = int(w * (max_length / h))
new_h = max_length
new_img = cv2.resize(img, dsize=(new_w, new_h), interpolation=cv2.INTER_AREA)
# save image
output_filepath = Path(args.output_root) / Path(args.input_file).with_suffix('.jpg')
print(output_filepath)
output_dir = output_filepath.parents[0]
os.makedirs(output_dir, exist_ok=True)
cv2.imwrite(output_filepath.as_posix(), new_img)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment