fragments

Oct 14, 2018

基于OpenCV的图像缩放脚本

Last updated at: Oct 14, 2018

1 OpenCV是什么

摘自维基百科的OpenCV词条

OpenCV (Open Source Computer Vision) is a library of programming functions mainly aimed at real-time computer vision. Originally developed by Intel, it was later supported by Willow Garage then Itseez (which was later acquired by Intel). The library is cross-platform and free for use under the open-source BSD license.

OpenCV具有C++,Python和Java接口,并支持Windows,Linux,macOS,iOS和Android操作系统。由于本博客的一些文章需要放置图片,为了更好的排版,需要对图片进行缩放操作;GIMP等图像处理程序可满足需求,但图片数量较多时,手动操作效率低下,虽然大多数图像处理程序都支持批处理(比如GIMP Batch Mode,但Python+OpenCV的解决方案能产出更多的学习收益;

2 脚本

首先,使用pip3安装opencv-python,执行Bash命令:

pip3 install opencv-python

其次,创建脚本文件,此处以nano作为文本编辑器,您可以使用您喜爱的工具;执行Bash命令:

nano resize

粘贴如下内容:

#!/usr/bin/env python3

import cv2
import argparse


def main():
    # 参数解析器
    parser = argparse.ArgumentParser(description='Image resize tool')
    parser.add_argument('sources', nargs='+', help='path of source image')
    parser.add_argument('--width', type=int,
                        default=400, help='width of target image')
    args = parser.parse_args()
    for source in args.sources:
        # 读取,按原样返回加载的图像(使用Alpha通道,否则会被裁剪)。
        image = cv2.imread(source, cv2.IMREAD_UNCHANGED)
        # 计算缩放比例
        scale = args.width / image.shape[1]
        # 缩放
        output = cv2.resize(image, (0, 0), fx=scale, fy=scale)
        # 保存
        cv2.imwrite(source, output)


if __name__ == '__main__':
    main()

Ctrl + O写出,按回车确认写至文件resize,按Ctrl + X退出;

3 使用

假设您需要缩放./b22dc2b9a85cd92f99123c0b.png宽为600像素,执行如下Bash命令:

➜  resize --width 800 b22dc2b9a85cd92f99123c0b.png

可在执行前后使用file命令查看区别:

➜  file b22dc2b9a85cd92f99123c0b.png 
b22dc2b9a85cd92f99123c0b.png: PNG image data, 2144 x 1396, 8-bit/color RGBA, non-interlaced
➜  resize --width 800 b22dc2b9a85cd92f99123c0b.png                                  
➜  file b22dc2b9a85cd92f99123c0b.png              
b22dc2b9a85cd92f99123c0b.png: PNG image data, 800 x 521, 8-bit/color RGBA, non-interlaced

4 结语

时间有限,本文仅涉及到很基础的OpenCV知识,如果您感兴趣的话,可以抽空学习它,祝您学习愉快~

5 更新

cv2.imread()调用时,若不添加cv2.IMREAD_UNCHANGED,则读取的PNG图像会缺少alpha通道,导致写出的图像也缺少,添加后即可。

6 参考

(190 words)