opencv-python 将图片批量压缩为指定的尺寸

起因

某天遇到一个任务,有一个高清的logo,需要导出成各种尺寸的logo。

解决方法

主要在于缩放图片的代码,最开始我选的是Pillow

from PIL import Image

img = Image.open(frompath)
out = img.resize(size)
out.save(outpath)

但是实际使用发现效果比PS缩放效果差很多,后来发现opencv可以选择插值方式,效果会很好多。逐一测试,似乎AREA(使用像素区域关系进行重采样)在缩小这个任务上跟PS效果是最接近的。

import cv2

img = Image.open(frompath)
out = cv2.resize(img, size, interpolation=cv2.INTER_AREA)
cv2.imwrite(outpath, out)

其他几种缩放的插值方法,可以参考这篇文章:
Python-OpenCV之图片缩放(cv2.resize)

代码

# from PIL import Image
import cv2

def read_img(frompath):
    # return Image.open(frompath)
    return cv2.imread(frompath)

def resize_one(img, size, outpath):
    # out = img.resize(size)
    # out.save(outpath)
    out = cv2.resize(img, size, interpolation=cv2.INTER_AREA)
    cv2.imwrite(outpath, out)

def resize_all(img, tasks):
    for (size, outpath) in tasks:
        resize_one(img, size, outpath)

def build_tasks(prefix, sizes):
    t = []
    for (x, y) in sizes:
        t.append(((x, y), prefix + '_' + str(x) + '_' + str(y) + '.png'))
    return t

def square_tasks(widths):
    t = []
    for w in widths:
        t.append((w, w))
    return t

def main():
    s = [72, 48, 96, 144, 192, 40, 60, 29, 58, 87, 80, 120, 57, 114, 120, 180, 1024]
    p = 'logo'
    i = './logo_1280.png'
    t = build_tasks(p, square_tasks(s))
    img = read_img(i)
    resize_all(img, t)

if __name__ == '__main__':
    main()

你可能感兴趣的:(经验)