Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

commented Jan 20, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.