Skip to content

Instantly share code, notes, and snippets.

@s-yoshiki
Last active January 20, 2019 10:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save s-yoshiki/467598f1d41f0d0611275eccc898f9c8 to your computer and use it in GitHub Desktop.
Save s-yoshiki/467598f1d41f0d0611275eccc898f9c8 to your computer and use it in GitHub Desktop.
Pythonで画像圧縮
#!/usr/local/bin/python3
import cv2
import numpy as np
import argparse
def compress_image(src, quality=50):
"""
param src 画像データ
param quality 画像クオリティ 1~100
return 圧縮された画像
"""
channel = 1
(result, encimg) = cv2.imencode('.jpg', src, [
int(cv2.IMWRITE_JPEG_QUALITY),
quality
])
if result == False:
return (1)
dst = cv2.imdecode(encimg, channel)
return (0, dst)
if __name__ == "__main__" :
parser = argparse.ArgumentParser(description='jpg encoder given images.')
parser.add_argument("input", type=str, help='input file')
parser.add_argument("-q", type=str, default='50', help='quality (0 to 100)')
parser.add_argument("-o", type=str, default='a.jpg', help='output file (default=a.png)')
args = parser.parse_args()
img = cv2.imread(args.input)
(status, img) = compress_image(img, int(args.q))
if status == 0:
cv2.imwrite(args.o, img)
exit(0)
else:
print('could not encode image!')
exit(1)
@s-yoshiki
Copy link
Author

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