1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

OpenCV-pythonでjpeg圧縮

Posted at

指定したフォルダ内について、「.jpg」で終わる全てのファイルを圧縮する。

(読み込み、圧縮エラー時の処理など書いておらず粗いです)

import cv2
import glob
import os

Quality = 10

def img_encode(img):
    encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), Quality]
    result, encimg = cv2.imencode(".jpg", img, encode_param) # (bool値,エンコードしたImageオブジェクト)のタプルが返ってくる
    return cv2.imdecode(encimg, cv2.IMREAD_UNCHANGED)

def output_imgs(): 
    path_list = glob.glob(r"<パス>\*.jpg")
    
    for i, path in enumerate(path_list):
        img = cv2.imread(path)
        compressed_img = img_encode(img)
        cv2.imwrite(r"<パス>" + "python-compressed" + "-rate" + str(Quality) + "-" + str(i+1) + ".jpg", compressed_img)

output_imgs()     

ハマった点

  • パスに日本語が含まれていると、cv2.imreadで正しく動作しない(Noneが返ってくる)
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?