Python 批量裁剪图片

有时候图片太大,想要合适的像素尺寸,需要批量裁剪,可以用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])
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容