opencv implements image batch compression

#When making a data set, compress high-resolution images#


import cv2
import os

def compress_folder(folder):
    for filename in os.listdir(images_folder):
        if filename.endswith('.jpg') or filename.endswith('.jpeg') or filename.endswith('.png'):
            img_path = os.path.join(images_folder, filename)
            img = cv2.imread(img_path)
            new_path = os.path.join(images_folder, "compressed_" + filename)
            cv2.imwrite(new_path, img, [int(cv2.IMWRITE_JPEG_QUALITY), 50])
            print(f"Compressed {img_path} to {new_path}")

compress_folder(r"文件夹路径")

Traverse and read pictures in a folder

for filename in os.listdir(images_folder):
#循环读取文件夹中的文件名称
   if filename.endswith('.jpg') or filename.endswith('.jpeg') or filename.endswith('.png'):
   #识别文件夹中的图片文件
            img_path = os.path.join(images_folder, filename)
            #使用os函数对文件夹路径以及图片文件的名称进行拼接
            img = cv2.imread(img_path)
            #生成的图片路径进行读取
new_path = os.path.join(images_folder, "compressed_" + filename)
#对要压缩的图片进行重命名,依然是os函数进行拼接

Compress Pictures

cv2.imwrite(new_path, img, [int(cv2.IMWRITE_JPEG_QUALITY), 50])
#保存图片,设置保存图片的JPEG质量为五十

JPEG quality is between 0 and 100. The 50 here can be changed. 0 is the lowest quality and 100 is the highest quality (lossless compression). I used 50, which is exactly half. The result is as follows

You can see that the result is roughly one-tenth of the original, and the compression size when using 100 quality is roughly one-half of the original.

Run the program, the compressed pictures will be saved in the original folder, and the original pictures will be retained.

The following is the code saved in another folder, the principle is the same

import cv2
import os

def compress_folder(images_folder,new_folder):
    for filename in os.listdir(images_folder):
        if filename.endswith('.jpg') or filename.endswith('.jpeg') or filename.endswith('.png'):
            img_path = os.path.join(images_folder, filename)
            img = cv2.imread(img_path)
            new_path = os.path.join(new_folder, "compressed_" + filename)
            cv2.imwrite(new_path, img, [int(cv2.IMWRITE_JPEG_QUALITY), 100])
            print(f"Compressed {img_path} to {new_path}")
images_folder = r'读取路径'
new_folder = r'保存路径'
compress_folder(images_folder,new_folder)

If you find it useful, please give it a like, thank you friends

Guess you like

Origin blog.csdn.net/weixin_74258524/article/details/134629002