文件夾圖像批處理教程

前言

因為經常對圖像要做數據清洗,又很費時間去重新寫一個,我一直在想能不能寫一個通用的腳本或者制作一個可視化的界面對文件夾圖像做批量的修改圖像大小、重命名、劃分數據訓練和驗證集等等。這里我先介紹一下我因為寫過的一些腳本,然后我們對其進行繪總,并制作成一個可視化界面。

腳本

獲取圖像路徑

我們需要一個函數去讀取文件夾下的所有文件,獲取其文件名,而關于這一部分我很早以前就做過了,詳細可以看這里:解決Python讀取圖片路徑存在轉義字符

import osdef get_image_path(path):imgfile = []file_list = os.listdir(path)for i in file_list:new_path = os.path.join(path, i).replace("\\", "/")_, file_ext = os.path.splitext(new_path)if file_ext[1:] in ('bmp', 'dng', 'jpeg', 'jpg', 'mpo', 'png', 'tif', 'tiff', 'webp', 'pfm'):imgfile.append(new_path)return natsorted(imgfile)if __name__=="__main__":images_path = r'E:\PythonProject\img_processing_techniques_main\document\images'images_path_list = get_image_path(images_path)print(images_path_list)

我們在這里進行了重命名,請以此篇為準。

批量修改圖像大小

def modify_images_size(target_path, target_hwsize, save_path=None):"""批量修改圖像大小"""h, w = target_hwsizeimages_paths = get_image_path(target_path)os.makedirs(save_path, exist_ok=True)for i, one_image_path in enumerate(images_paths):try:image = Image.open(one_image_path)resized_image = image.resize((w, h))base_name = os.path.basename(one_image_path)if save_path is not None:new_path = os.path.join(save_path, base_name)else:new_path = one_image_pathresized_image.save(new_path)print(f"Resized {one_image_path} to {new_path}")except Exception as e:print(f"Error resizing {one_image_path}: {e}")

這里的腳本用于圖像的批量修改,如果不給保存路徑,那么就會修改本地的文件,我們是不推薦這里的,最好還是做好備份。

劃分數據集與驗證集

def split_train_val_txt(target_path, train_ratio=.8, val_ratio=.2, onlybasename=False):"""如果 train_ratio + val_ratio = 1 表示只劃分訓練集和驗證集, train_ratio + val_ratio < 1表示將剩余的比例劃分為測試集"""assert train_ratio + val_ratio <= 1test_ratio = 1. - (train_ratio + val_ratio)images_paths = get_image_path(target_path)num_images = len(images_paths)num_train = round(num_images * train_ratio)num_val = num_images - num_train if test_ratio == 0 else math.ceil(num_images * val_ratio)num_test = 0 if test_ratio == 0 else num_images - (num_train + num_val)with open(os.path.join(target_path, 'train.txt'), 'w') as train_file, \open(os.path.join(target_path, 'val.txt'), 'w') as val_file, \open(os.path.join(target_path, 'test.txt'), 'w') as test_file:for i, image_path in enumerate(images_paths):if onlybasename:image_name, _ = os.path.splitext(os.path.basename(image_path))else:image_name = image_pathif i < num_train:train_file.write(f"{image_name}\n")elif i < num_train + num_val:val_file.write(f"{image_name}\n")else:test_file.write(f"{image_name}\n")print(f"Successfully split {num_images} images into {num_train} train, {num_val} val, and {num_test} test.")

我在這里修改了劃分測試集的邏輯,根據劃分比例來評判,以免出現使用向上取整或向下取整導致出現的問題(測試集比例不為0,驗證集比例按照向上取整劃分)。

復制圖像到另外一個文件夾

def copy_images_to_directory(target_path, save_folder, message=True):"""復制整個文件夾(圖像)到另外一個文件夾"""try:os.makedirs(save_folder, exist_ok=True)source_path = get_image_path(target_path)for img_path in source_path:base_file_name = os.path.basename(img_path)destination_path = os.path.join(save_folder, base_file_name)shutil.copy2(img_path, destination_path)if message:print(f"Successfully copied folder: {img_path} to {save_folder}")except Exception as e:print(f"Error copying folder, {e}")

這個本來是一個小功能,但是我想的是有時候如果要做每張圖的匹配,可以修改為將符合條件的路徑復制到目標文件夾中。修改也只需加一個列表的判斷即可。

獲取數據集的均值標準化

def get_dataset_mean_std(train_data):train_loader = DataLoader(train_data, batch_size=1, shuffle=False, num_workers=0,pin_memory=True)mean = torch.zeros(3)std = torch.zeros(3)for im, _ in train_loader:for d in range(3):mean[d] += im[:, d, :, :].mean()std[d] += im[:, d, :, :].std()mean.div_(len(train_data))std.div_(len(train_data))return list(mean.numpy()), list(std.numpy())def get_images_mean_std(target_path):images_paths = get_image_path(target_path)num_images = len(images_paths)mean_sum = np.zeros(3)std_sum = np.zeros(3)for one_image_path in images_paths:pil_image = Image.open(one_image_path).convert("RGB")img_asarray = np.asarray(pil_image) / 255.0individual_mean = np.mean(img_asarray, axis=(0, 1))individual_stdev = np.std(img_asarray, axis=(0, 1))mean_sum += individual_meanstd_sum += individual_stdevmean = mean_sum / num_imagesstd = std_sum / num_imagesreturn mean.astype(np.float32), std.astype(np.float32)

都是相同的方法獲取RGB圖像的均值標準化,我們更建議直接使用第二個。

批量修改圖像后綴名

def modify_images_suffix(target_path, format='png'):"""批量修改圖像文件后綴"""images_paths = get_image_path(target_path)for i, one_image_path in enumerate(images_paths):base_name, ext = os.path.splitext(one_image_path)new_path = base_name + '.' + formatos.rename(one_image_path, new_path)print(f"Converting {one_image_path} to {new_path}")

這里僅僅是修改圖像的后綴,至于這種強力的修改是否會對圖像的格式造成影響我們不做考慮。

批量重命名圖像

def batch_rename_images(target_path,save_path,start_index=None,prefix=None,suffix=None,format=None,num_type=1,
):"""重命名圖像文件夾中的所有圖像文件并保存到指定文件夾:param target_path: 目標文件路徑:param save_path: 文件夾的保存路徑:param start_index: 默認為 1, 從多少號開始:param prefix: 重命名的通用格式前綴, 如 rename001.png, rename002.png...:param suffix: 重命名的通用格式后綴, 如 001rename.png, 002rename.png...:param format (str): 新的后綴名,不需要包含點(.):param num_type: 數字長度, 比如 3 表示 005:param message: 是否打印修改信息"""os.makedirs(save_path, exist_ok=True)images_paths = get_image_path(target_path)current_num = start_index if start_index is not None else 1for i, image_path in enumerate(images_paths):image_name = os.path.basename(image_path)name, ext = os.path.splitext(image_name)if format is None:ext = extelse:ext = f'.{format}'padded_i = str(current_num).zfill(num_type)if prefix and suffix:new_image_name = f"{prefix}{padded_i}{suffix}{ext}"elif prefix:new_image_name = f"{prefix}{padded_i}{ext}"elif suffix:new_image_name = f"{padded_i}{suffix}{ext}"else:new_image_name = f"{padded_i}{ext}"new_path = os.path.join(save_path, new_image_name)current_num += 1print(f"{i + 1} Successfully rename {image_path} to {new_path}")shutil.copy(image_path, new_path)print("Batch renaming and saving of files completed!")

我們在這里添加了重命名的功能,其實發現很多都可以套在這里面來,所以后面我們修改過后會做成ui進行顯示。

完整腳本

下面是我經過測試后的一個腳本,大家可以直接拿去使用。

import os
import math
import torch
import numpy as np
from PIL import Image
import shutil
from torch.utils.data import DataLoader
from natsort import natsorteddef get_image_path(path):imgfile = []file_list = os.listdir(path)for i in file_list:new_path = os.path.join(path, i).replace("\\", "/")_, file_ext = os.path.splitext(new_path)if file_ext[1:] in ('bmp', 'dng', 'jpeg', 'jpg', 'mpo', 'png', 'tif', 'tiff', 'webp', 'pfm'):imgfile.append(new_path)return natsorted(imgfile)def modify_images_size(target_path, target_hwsize, save_path=None):"""批量修改圖像大小"""h, w = target_hwsizeimages_paths = get_image_path(target_path)os.makedirs(save_path, exist_ok=True)for i, one_image_path in enumerate(images_paths):try:image = Image.open(one_image_path)resized_image = image.resize((w, h))base_name = os.path.basename(one_image_path)if save_path is not None:new_path = os.path.join(save_path, base_name)else:new_path = one_image_pathresized_image.save(new_path)print(f"Resized {one_image_path} to {new_path}")except Exception as e:print(f"Error resizing {one_image_path}: {e}")def split_train_val_txt(target_path, train_ratio=.8, val_ratio=.2, onlybasename=False):"""如果 train_ratio + val_ratio = 1 表示只劃分訓練集和驗證集, train_ratio + val_ratio < 1表示將剩余的比例劃分為測試集"""assert train_ratio + val_ratio <= 1test_ratio = 1. - (train_ratio + val_ratio)images_paths = get_image_path(target_path)num_images = len(images_paths)num_train = round(num_images * train_ratio)num_val = num_images - num_train if test_ratio == 0 else math.ceil(num_images * val_ratio)num_test = 0 if test_ratio == 0 else num_images - (num_train + num_val)with open(os.path.join(target_path, 'train.txt'), 'w') as train_file, \open(os.path.join(target_path, 'val.txt'), 'w') as val_file, \open(os.path.join(target_path, 'test.txt'), 'w') as test_file:for i, image_path in enumerate(images_paths):if onlybasename:image_name, _ = os.path.splitext(os.path.basename(image_path))else:image_name = image_pathif i < num_train:train_file.write(f"{image_name}\n")elif i < num_train + num_val:val_file.write(f"{image_name}\n")else:test_file.write(f"{image_name}\n")print(f"Successfully split {num_images} images into {num_train} train, {num_val} val, and {num_test} test.")def copy_images_to_directory(target_path, save_folder):"""復制整個文件夾(圖像)到另外一個文件夾"""try:os.makedirs(save_folder, exist_ok=True)source_path = get_image_path(target_path)for img_path in source_path:base_file_name = os.path.basename(img_path)destination_path = os.path.join(save_folder, base_file_name)shutil.copy2(img_path, destination_path)print(f"Successfully copied folder: {img_path} to {save_folder}")except Exception as e:print(f"Error copying folder, {e}")def get_dataset_mean_std(train_data):train_loader = DataLoader(train_data, batch_size=1, shuffle=False, num_workers=0,pin_memory=True)mean = torch.zeros(3)std = torch.zeros(3)for im, _ in train_loader:for d in range(3):mean[d] += im[:, d, :, :].mean()std[d] += im[:, d, :, :].std()mean.div_(len(train_data))std.div_(len(train_data))return list(mean.numpy()), list(std.numpy())def get_images_mean_std(target_path):images_paths = get_image_path(target_path)num_images = len(images_paths)mean_sum = np.zeros(3)std_sum = np.zeros(3)for one_image_path in images_paths:pil_image = Image.open(one_image_path).convert("RGB")img_asarray = np.asarray(pil_image) / 255.0individual_mean = np.mean(img_asarray, axis=(0, 1))individual_stdev = np.std(img_asarray, axis=(0, 1))mean_sum += individual_meanstd_sum += individual_stdevmean = mean_sum / num_imagesstd = std_sum / num_imagesreturn mean.astype(np.float32), std.astype(np.float32)def modify_images_suffix(target_path, format='png'):"""批量修改圖像文件后綴"""images_paths = get_image_path(target_path)for i, one_image_path in enumerate(images_paths):base_name, ext = os.path.splitext(one_image_path)new_path = base_name + '.' + formatos.rename(one_image_path, new_path)print(f"Converting {one_image_path} to {new_path}")def batch_rename_images(target_path,save_path,start_index=None,prefix=None,suffix=None,format=None,num_type=1,
):"""重命名圖像文件夾中的所有圖像文件并保存到指定文件夾:param target_path: 目標文件路徑:param save_path: 文件夾的保存路徑:param start_index: 默認為 1, 從多少號開始:param prefix: 重命名的通用格式前綴, 如 rename001.png, rename002.png...:param suffix: 重命名的通用格式后綴, 如 001rename.png, 002rename.png...:param format (str): 新的后綴名,不需要包含點(.):param num_type: 數字長度, 比如 3 表示 005:param message: 是否打印修改信息"""os.makedirs(save_path, exist_ok=True)images_paths = get_image_path(target_path)current_num = start_index if start_index is not None else 1for i, image_path in enumerate(images_paths):image_name = os.path.basename(image_path)name, ext = os.path.splitext(image_name)if format is None:ext = extelse:ext = f'.{format}'padded_i = str(current_num).zfill(num_type)if prefix and suffix:new_image_name = f"{prefix}{padded_i}{suffix}{ext}"elif prefix:new_image_name = f"{prefix}{padded_i}{ext}"elif suffix:new_image_name = f"{padded_i}{suffix}{ext}"else:new_image_name = f"{padded_i}{ext}"new_path = os.path.join(save_path, new_image_name)current_num += 1print(f"{i + 1} Successfully rename {image_path} to {new_path}")shutil.copy(image_path, new_path)print("Batch renaming and saving of files completed!")
if __name__=="__main__":images_path = r'E:\PythonProject\img_processing_techniques_main\document\images'images_path_list = get_image_path(images_path)save_path =r'./save_path'# modify_images_size(images_path, (512, 512), save_path)# print(images_path_list)# split_train_val_txt(images_path, .8, .2)# copy_images_to_directory(images_path, save_folder='./save_path2')# mean, std = get_images_mean_std(images_path)# print(mean, std)# modify_images_suffix('./save_path2')

BatchVision的可視化設計

我將前面的一些腳本制作成了一個批量文件處理系統 BatchVision,可實現批量修改圖像大小,劃分訓練集和驗證集,以及批量重命名,其他的一些小功能例如灰度化處理和計算均值標準化。

完整項目請看此處:UI-Design-System-Based-on-PyQt5

這里通過網盤鏈接分享的離線使用文件exe,無需安裝環境:?BatchVision

我們設計的可視化界面如下圖所示:

其中的一些設定我都是經過嚴格的判斷,如果還有問題可以聯系我修改。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/bicheng/82323.shtml
繁體地址,請注明出處:http://hk.pswp.cn/bicheng/82323.shtml
英文地址,請注明出處:http://en.pswp.cn/bicheng/82323.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

【Unity實戰筆記】第二十四 · 使用 SMB+Animator 實現基礎戰斗系統

轉載請注明出處&#xff1a;&#x1f517;https://blog.csdn.net/weixin_44013533/article/details/146409453 作者&#xff1a;CSDN|Ringleader| 1 結構 1.1 狀態機 1.2 SMB 2 代碼實現 2.1 核心控制 Player_Base_SMB 繼承 StateMachineBehaviour &#xff0c;控制變量初始…

Python虛擬環境再PyCharm中自由切換使用方法

Python開發中的環境隔離是必不可少的步驟,通過使用虛擬環境可以有效地管理不同項目間的依賴,避免包沖突和環境污染。虛擬環境是Python官方提供的一種獨立運行環境,每個項目可以擁有自己單獨的環境,不同項目之間的環境互不影響。在日常開發中,結合PyCharm這樣強大的IDE進行…

大模型智能體入門掃盲——基于camel的概述

前言 本篇博客想帶讀者進行一個智能體入門掃盲&#xff0c;了解基礎知識&#xff0c;為什么用camel呢&#xff0c;因為小洛發現它們文檔對這種智能體的基本組件介紹得很全面深入。 基礎概念 agent 一個典型的agent智能體包含三個核心部分&#xff1a; 感知模塊&#xff1…

目標檢測 RT-DETR(2023)詳細解讀

文章目錄 主干網絡&#xff1a;Encoder&#xff1a;不確定性最小Query選擇Decoder網絡&#xff1a; 將DETR擴展到實時場景&#xff0c;提高了模型的檢測速度。網絡架構分為三部分組成&#xff1a;主干網絡、混合編碼器、帶有輔助預測頭的變換器編碼器。具體來說&#xff0c;先利…

DeepSeek 賦能數字農業:從智慧種植到產業升級的全鏈條革新

目錄 一、數字農業的現狀與挑戰二、DeepSeek 技術解析2.1 DeepSeek 的技術原理與優勢2.2 DeepSeek 在人工智能領域的地位與影響力 三、DeepSeek 在數字農業中的應用場景3.1 精準種植決策3.2 病蟲害監測與防治3.3 智能灌溉與施肥管理3.4 農產品質量追溯與品牌建設 四、DeepSeek …

<uniapp><vuex><狀態管理>在uniapp中,如何使用vuex實現數據共享與傳遞?

前言 本專欄是基于uniapp實現手機端各種小功能的程序&#xff0c;并且基于各種通訊協議如http、websocekt等&#xff0c;實現手機端作為客戶端&#xff08;或者是手持機、PDA等&#xff09;&#xff0c;與服務端進行數據通訊的實例開發。 發文平臺 CSDN 環境配置 系統&…

高速串行差分信號仿真分析及技術發展挑戰續

7.3 3.125Gbps 差分串行信號設計實例仿真分析 7.3.1 設計用例說明 介紹完 Cadence 系統本身所具有的高速差分信號的仿真分析功能之后&#xff0c;我們以一個實例來說明 3.125Gbps 以下的高速差分系統的仿真分析方法。 在網上下載的設計文件“Booksi_Demo_Allegro160_Finishe…

【Golang】部分語法格式和規則

1、時間字符串和時間戳的相互轉換 func main() {t1 : int64(1546926630) // 外部傳入的時間戳&#xff08;秒為單位&#xff09;&#xff0c;必須為int64類型t2 : "2019-01-08 13:50:30" // 外部傳入的時間字符串//時間轉換的模板&#xff0c;golang里面只能是 &quo…

第十六章:數據治理之數據架構:數據模型和數據流轉關系

本章我們說一下數據架構&#xff0c;說到數據架構&#xff0c;就很自然的想到企業架構、業務架構、軟件架構&#xff0c;因為個人并沒有對這些內容進行深入了解&#xff0c;所以這里不做比對是否有相似或者共通的地方&#xff0c;僅僅來說一下我理解的數據架構。 1、什么是架構…

Day126 | 靈神 | 二叉樹 | 層數最深的葉子結點的和

Day126 | 靈神 | 二叉樹 | 層數最深的葉子結點的和 1302.層數最深的葉子結點的和 1302. 層數最深葉子節點的和 - 力扣&#xff08;LeetCode&#xff09; 思路&#xff1a; 這道題用層序遍歷的思路比較好想&#xff0c;就把每層的都算一下&#xff0c;然后返回最后一層的和就…

PCIE 4.0 vs PCIE 5.0固態硬盤——區別、科普與選購場景全解析

隨著數字內容和高性能計算需求的爆發&#xff0c;固態硬盤&#xff08;SSD&#xff09;已成為PC、游戲主機和工作站不可或缺的核心硬件。面對市面上層出不窮的新一代SSD產品&#xff0c;大家最常見的一個疑惑&#xff1a;**PCIe 4.0和PCIe 5.0固態硬盤&#xff0c;到底有啥區別…

vue pinia 獨立維護,倉庫統一導出

它允許您跨組件/頁面共享狀態 持久化 安裝依賴pnpm i pinia-plugin-persistedstate 將插件添加到 pinia 實例上 pinia獨立維護 統一導出 import { createPinia } from pinia import piniaPluginPersistedstate from pinia-plugin-persistedstateconst pinia creat…

Dify源碼學習

文章目錄 1 大模型基本原理1.1 model_context_tokens、max_tokens和prompt_tokens1.1.1 三者之間的關系1.1.2 總結對比 2 Dify源代碼2.0 前后端代碼跑起來【0】準備開發環境【1】下載代碼【2】運行后端&#xff08;1&#xff09;Start the docker-compose stack&#xff08;2&a…

連接表、視圖和存儲過程

1. 視圖 1.1. 視圖的概念 視圖&#xff08;View&#xff09;&#xff1a;虛擬表&#xff0c;本身不存儲數據&#xff0c;而是封裝了一個 SQL 查詢的結果集。 用途&#xff1a; 只顯示部分數據&#xff0c;提高數據訪問的安全性。簡化復雜查詢&#xff0c;提高復用性和可維護…

微信小程序中,解決lottie動畫在真機不顯示的問題

api部分 export function getRainInfo() {return onlineRequest({url: /ball/recruit/getRainInfo,method: get}); }data存儲json數據 data&#xff1a;{rainJson:{} }onLoad方法獲取json數據 onLoad(options) {let that thisgetRainInfo().then((res)>{that.setData({r…

從加密到信任|密碼重塑車路云一體化安全生態

目錄 一、密碼技術的核心支撐 二、典型應用案例 三、未來發展方向 總結 車路云系統涉及海量實時數據交互&#xff0c;包括車輛位置、傳感器信息、用戶身份等敏感數據。其安全風險呈現三大特征&#xff1a; 開放環境威脅&#xff1a;V2X&#xff08;車與萬物互聯&#xff0…

光譜相機在地質勘測中的應用

一、?礦物識別與蝕變帶分析? ?光譜特征捕捉? 通過可見光至近紅外&#xff08;400-1000nm&#xff09;的高光譜分辨率&#xff08;可達3.5nm&#xff09;&#xff0c;精確識別礦物的“光譜指紋”。例如&#xff1a; ?銅礦?&#xff1a;在400-500nm波段反射率顯著低于圍…

理論篇三:如何編寫自定義的Webpack Loader或Plugin插件

在 Webpack 中,自定義 Loader 和 Plugin 是擴展構建能力的關鍵方式。以下是它們的實現方法和核心邏輯,通過代碼示例和步驟拆解幫助你快速掌握。 一、自定義 Loader 1. Loader 的本質 作用:將非 JS 文件轉換為 Webpack 能處理的模塊。特點:純函數,接收源文件內容,返回處理…

【算法】力扣體系分類

第一章 算法基礎題型 1.1 排序算法題 1.1.1 冒泡排序相關題 冒泡排序是一種簡單的排序算法&#xff0c;它重復地走訪過要排序的數列&#xff0c;一次比較兩個元素&#xff0c;如果它們的順序錯誤就把它們交換過來。走訪數列的工作是重復地進行直到沒有再需要交換&#xff0c…

C11 日期時間處理案例

文章目錄 顯示當前日期時間得到當前日期時間的17位數字形式(YYYYmmddHHMMSSsss)從日期時間字符串得到time_t 類型時間戳從時期時間字符串得到毫秒單位的時間戳得到當前日期時間以毫秒為單位的時間戳一個綜合案例 所有例子在VS2019上編譯運行通過 顯示當前日期時間 #include &…