Python 批量裁剪圖片

有時(shí)候圖片太大,想要合適的像素尺寸,需要批量裁剪,可以用Python的 Opencv2庫(kù) 處理

安裝時(shí)使用opencv_python,導(dǎo)入時(shí)使用cv2
cut 為輸入文件夾
out 為輸出文件夾
結(jié)果如下:


image.png

運(yùn)行時(shí)
先安裝opencv-python庫(kù)
在WSL中輸入命令pip install -i https://pypi.tuna.tsinghua.edu.cn/simple opencv-python

(base) root@DESKTOP-727JVLV:/mnt/g/顯微鏡-細(xì)胞房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

再運(yùn)行Python代碼
在WSL中輸入命令python cut_img.py

(base) root@DESKTOP-727JVLV:/mnt/g/顯微鏡-細(xì)胞房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] # 裁剪坐標(biāo)為[y0:y1, x0:x1]
    cv2.imwrite(output_img_path, cropped)
 
dataset_dir = 'cut'
output_dir = 'out'
 
 
# 獲得需要轉(zhuǎn)化的圖片路徑并生成目標(biāo)路徑
image_filenames = [(os.path.join(dataset_dir, x), os.path.join(output_dir, x))
                    for x in os.listdir(dataset_dir)]
# 轉(zhuǎn)化所有圖片
for path in image_filenames:
    update(path[0], path[1])
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容