Last active
January 20, 2019 10:34
-
-
Save s-yoshiki/467598f1d41f0d0611275eccc898f9c8 to your computer and use it in GitHub Desktop.
Pythonで画像圧縮
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
解説記事
画像サイズを圧縮する OpenCV + Python