美文网首页
Python 批量裁剪图片

Python 批量裁剪图片

作者: 火卫控 | 来源:发表于2023-08-11 21:15 被阅读0次

    有时候图片太大,想要合适的像素尺寸,需要批量裁剪,可以用Python的 Opencv2库 处理

    安装时使用opencv_python,导入时使用cv2
    cut 为输入文件夹
    out 为输出文件夹
    结果如下:


    image.png

    运行时
    先安装opencv-python库
    在WSL中输入命令pip install -i https://pypi.tuna.tsinghua.edu.cn/simple opencv-python

    (base) root@DESKTOP-727JVLV:/mnt/g/显微镜-细胞房C6/8/8.10/Riba-A549-38M# pip install -i https://pypi.tuna.tsinghua.edu.cn/simple opencv-python
    Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple
    Collecting opencv-python
      Downloading https://pypi.tuna.tsinghua.edu.cn/packages/f5/d0/2e455d894ec0d6527e662ad55e70c04f421ad83a6fd0a54c3dd73c411282/opencv_python-4.8.0.76-cp37-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (61.7 MB)
         ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 61.7/61.7 MB 5.7 MB/s eta 0:00:00
    Requirement already satisfied: numpy>=1.21.2 in /root/miniconda3/lib/python3.11/site-packages (from opencv-python) (1.25.0)
    Installing collected packages: opencv-python
    Successfully installed opencv-python-4.8.0.76
    WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv
    

    再运行Python代码
    在WSL中输入命令python cut_img.py

    (base) root@DESKTOP-727JVLV:/mnt/g/显微镜-细胞房C6/8/8.10/Riba-A549-38M# python cut_img.py
    (3648, 5440, 3)
    (3648, 5440, 3)
    (3648, 5440, 3)
    (3648, 5440, 3)
    (3648, 5440, 3)
    (3648, 5440, 3)
    (3648, 5440, 3)
    (3648, 5440, 3)
    (3648, 5440, 3)
    (3648, 5440, 3)
    (3648, 5440, 3)
    (3648, 5440, 3)
    (3648, 5440, 3)
    (3648, 5440, 3)
    (3648, 5440, 3)
    (3648, 5440, 3)
    (3648, 5440, 3)
    (3648, 5440, 3)
    (3648, 5440, 3)
    (3648, 5440, 3)
    (3648, 5440, 3)
    (3648, 5440, 3)
    (3648, 5440, 3)
    (3648, 5440, 3)
    (3648, 5440, 3)
    (3648, 5440, 3)
    (3648, 5440, 3)
    (3648, 5440, 3)
    (3648, 5440, 3)
    (3648, 5440, 3)
    (3648, 5440, 3)
    (3648, 5440, 3)
    (3648, 5440, 3)
    (3648, 5440, 3)
    (3648, 5440, 3)
    (3648, 5440, 3)
    

    cut_img.py 文件 代码如下:

    import numpy as np
    import cv2
    import os
     
    def update(input_img_path, output_img_path):
     
        image = cv2.imread(input_img_path)
        print(image.shape)
        cropped = image[0:2400, 0:3000] # 裁剪坐标为[y0:y1, x0:x1]
        cv2.imwrite(output_img_path, cropped)
     
    dataset_dir = 'cut'
    output_dir = 'out'
     
     
    # 获得需要转化的图片路径并生成目标路径
    image_filenames = [(os.path.join(dataset_dir, x), os.path.join(output_dir, x))
                        for x in os.listdir(dataset_dir)]
    # 转化所有图片
    for path in image_filenames:
        update(path[0], path[1])
    

    相关文章

      网友评论

          本文标题:Python 批量裁剪图片

          本文链接:https://www.haomeiwen.com/subject/kkgtmdtx.html