保留原图像尺寸改变像素值(压缩存储大小)

本文介绍如何使用PIL库对图像进行压缩,包括单张图片和批量图片的压缩方法,压缩过程保持图像尺寸不变,仅减少水平垂直像素,有效降低存储需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

借助于PIL库实现对原始图像的压缩,而不改变原图像的尺寸(原尺寸不变,只改变图像水平像素和垂直像素),效果图如下所示:

在这里插入图片描述

1.实现对单张图片的压缩(元图像尺寸宽高不变,水平垂直像素减少,减少单张图片存储)
import cv2
from PIL import Image as ImagePIL
from PIL import Image
import os
#  原图像路径
im = cv2.imread('./picture/6260.jpg')
image = Image.fromarray(cv2.cvtColor(im, cv2.COLOR_BGR2RGB))
#   压缩完图像路径
image.save('2.jpg', quality=10, dpi=(24.0, 24.0))
2.实现对批量图片的压缩,并且压缩后图像的命名与原图像的名称一一对应(元图像尺寸宽高不变,水平垂直像素减少,减少单张图片存储)
import cv2
from PIL import Image as ImagePIL
from PIL import Image
import os
def convert(input_dir, output_dir):
    for filename in os.listdir(input_dir):
        path = input_dir + "/" + filename#获取文件路径
        print("doing... ", path)
        ori_img = cv2.imread(path)#读取图片
        image = Image.fromarray(cv2.cvtColor(ori_img, cv2.COLOR_BGR2RGB))
        image.save(output_dir+'/'+filename, quality=10, dpi=(24.0, 24.0))
        #cv2.imwrite(output_dir+'/'+filename,noise_img)
if __name__ == '__main__':
	#将原图压缩,并另存为别的文件夹下
    #输入图片路径(路径下不要有中文)
    input_dir = "F:\\LYD_total_picture\\zhoucheng_new\\JPEGImages"
    #输出图片保存路径(路径下不要有中文)
    output_dir = "F:\\LYD_total_picture\\zhoucheng_new\\JPEG"
    convert(input_dir, output_dir)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

勇敢牛牛@

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值