python 批量圖片拆分


掃描儀掃出來的A3的圖片需要處理拆成2個A4的圖片,用這個py處理一下

# -*- encoding: utf-8 -*-
"""
# @Time    : 2020-04-03 11:04
# @Author  : bootloader
# @Site    : 
# @File    : 圖片切割為原寬度2分之1的2張圖片.py
# @Software: PyCharm
"""

import os
import time

import cv2
import numpy as np

# ----------------------------------------------------------------------------------------------------------------
# --腳本所支持的文件擴展名
supExpName = ["jpg", "png"]

countNum = 0  # --處理圖片計數

print("該腳本將腳本所在目錄的所支持的圖片拆分為寬度為原來1/2的兩個圖片")
print("--程序將在5s后自動執行--腳本執行需要使用 cv2庫--")
print("--使用 pip install opencv-python 命令可以安裝該庫--")
print("Loading", end="")
for i in range(10):
    print(".", end='', flush=True)
    time.sleep(0.5)
# ----------------------------------------------------------------------------------------------------------------
# --獲取當前路徑
in_dir = os.path.abspath('.') + "/"
# --設置輸出路徑
out_dir = os.path.abspath('.') + "/out_dir/"

# 判斷輸出文件夾是否存在,若不存在則創建
if not os.path.exists(out_dir):
    os.mkdir("out_dir")
    print("創建輸出目錄")


# ----------------------------------------------------------------------------------------------------------------
# --打開圖片
def cv_imread(in_pash):
    cv_img = cv2.imdecode(np.fromfile(in_pash, dtype=np.uint8), -1)  # -1表示cv2.IMREAD_UNCHANGED
    print(os.path.basename(in_pash) + "\t寬&高", cv_img.shape[1], cv_img.shape[0])
    return cv_img


# --保存圖片
def cv_imwrite(out_path, img_mp):
    cv2.imencode('.png', img_mp)[1].tofile(out_path)


# ----------------------------------------------------------------------------------------------------------------
# --遍歷 in_dir 路徑下所有文件
for file_name in os.listdir(in_dir):
    extName = os.path.splitext(file_name)[-1][1:]  # --分離並截取擴展名
    extName = extName.lower()  # --將取得的擴展名轉為小寫

    # --判斷文件是否為所支持的圖片格式
    if extName in supExpName:
        countNum = countNum + 1;
        print("\n正在處理第 %d 張圖片" % (countNum))
        img = cv_imread(in_dir + file_name)
        h, w, w2 = img.shape[0], img.shape[1], img.shape[1] // 2
        # print(h,w,w2)

        # print(os.getcwd())  #--這個命令可以用來獲取當前腳本所在目錄--
        img_name = file_name.split('.')[0]

        cropped1 = img[0:int(h), 0:int(w2)]
        cropped2 = img[0:int(h), int(w2):int(w)]
        cv_imwrite(out_dir + img_name + "-1" + ".png", cropped1)
        cv_imwrite(out_dir + img_name + "-2" + ".png", cropped2)

print("--complete--")

# ----------------------------------------------------------------------------------------------------------------



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM