Python OpenCV与PIL缩放图片的对比

Openc代码

import cv2
import os
import shutil

srcdir = "jiankangbao/srcpic/"
descdir = "jiankangbao/descpic/"

#清空源和目标文件夹
def cleardir(dirname):
    if os.path.exists(os.path.join(os.getcwd(),descdir)):
        shutil.rmtree(dirname)
    os.makedirs(dirname)
    print("文件夹:{} 已清空".format(dirname))

# cleardir(srcdir) # 清空源文件夹,更换原图片时启动此行一次后关闭,把新图放进去运行就可以了
cleardir(descdir) # 清空目标文件夹
pics = os.listdir(srcdir)
pid = 0

if len(pics):
    for pic in pics:
        srcpic = srcdir + pic
        descpic = descdir + str(pid)+ ".jpg"
        img = cv2.imread(srcpic) # 读取图片
        # cv2.imshow("img", img) # 展示图片到屏幕
        a = int(154.5075) # 把浮点数转换为整数类型,因为cv2.resize(img,(a,b))中a与b不能为浮点数
        b = int(259.875) # 同上
        imgg = cv2.resize(img, (a,b)) # 缩放图片尺寸大小为(a,b),a为宽,b为高
        cv2.imwrite(descpic , imgg, [cv2.IMWRITE_JPEG_QUALITY, 100]) # 缩放后的图片imgg保存到新的文件路径descpic中
        pid+=1

print("图片转换完成,共计 {} 张".format(pid))
# cv2.waitKey()

图片缩放后,失真严重,差强人意,效果如下图:

Python OpenCV与PIL缩放图片的对比_第1张图片

相对而言,PIL缩放处理的图片则胜出一大截代码如下:

PIL代码:

import os
from PIL import Image
import sys


# 获取path目录下的所有文件
def get_imlist(path):
    return [os.path.join(path, f)
            for f in os.listdir(path)]


def change_size(path):
    directorys = get_imlist(path)
    for directory in directorys:
        # 不是图片文件就跳过
        print(directory)
        if not (directory.endswith('.jpg') or directory.endswith('.png') or directory.endswith('.bmp')):
            pass
        else:
            img = Image.open(directory)
            s = "/"
            # 获取文件名(含后缀)
            oimage_name = directory[directory.rfind(s) + 1:]
            (oimage_width, oimage_height) = img.size
            new_width = 154
            new_height = 259
            out = img.resize((new_width, new_height), Image.ANTIALIAS)
            out.save("%s" % oimage_name,quality = 95)  # 直接替换,图片质量控制可调整参数quality,它的值在区间[0,100],值越高,图片质量越高


if __name__ == '__main__':
    change_size("srcpic")

Python OpenCV与PIL缩放图片的对比_第2张图片

你可能感兴趣的:(python,python,opencv)