Skip to content

Instantly share code, notes, and snippets.

@CodeArtha
Last active October 21, 2021 08:10
Show Gist options
  • Select an option

  • Save CodeArtha/f29ef790a242f6684fd571b14c954146 to your computer and use it in GitHub Desktop.

Select an option

Save CodeArtha/f29ef790a242f6684fd571b14c954146 to your computer and use it in GitHub Desktop.
Python script to convert raw images (CR2 in this case) to WEBP or other formats if needed. Works on computers where rawkit complains that rawlib is not installed and since I can't install it on my workcomputer I found this workaround. Requires a "input" and "output" folder in the same directory as the script.
from PIL import Image
import rawpy
import imageio
import numpy as np
import os
def main():
paths = os.listdir("input")
for path in paths:
raw = None
path_in = r"input/" + path
path_out = r"output/" + path.replace("CR2", "webp")
with rawpy.imread(path_in) as raw:
buffered_img = np.array(raw.postprocess())
#imageio.imsave(path_out, rgb) # this worked for jpg or png images but webp is not a supported format of imsave. though the rest of the code above and below need to be adapted to make it work again
height, width, _ = buffered_img.shape
try:
#image = Image.frombytes('RGB', (raw.sizes.width, raw.sizes.height), buffered_img)
image = Image.frombytes('RGB', (width, height), buffered_img)
image.save(path_out, "WEBP", quality=90)
print(path_in, "->", path_out)
except Exception as e:
print("Error while handling the file " + path_in +" :") # I've only had one encoding error, not sure how to deal with it, for now I ignored that file and converted it manually, so I just ignore the error and keep the script running
print(e)
finally:
pass
if __name__ == '__main__':
main()
@CodeArtha

Copy link
Copy Markdown
Author

requirements: pip install Pillow numpy rawpy

@CodeArtha

Copy link
Copy Markdown
Author

revision 2 corrects a bug with portrait orientation pictures that weren't sized correctly

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment