一、使用说明
-
确定已经安装python,且版本3.6以上,可以用下面指令查看python版本:python --version
-
配置环境,第一次使用先配置环境,后面不需要
-
把要转换的图片放到"img"文件夹下
-
转换,结果保存在本目录下的新创建的文件夹中
二、配置环境脚本(.bat)
@echo off
chcp 65001 > nul
REM Check Python version
python -c "import sys; exit(0) if sys.version_info >= (3, 6) else exit(1)"
IF ERRORLEVEL 1 (
echo Your Python version is lower than 3.6. Please upgrade your Python version.
echo Upgrade instructions:
echo 1. Visit https://www.python.org/downloads/ to download the latest version of Python.
echo 2. During installation, make sure to check "Add Python to PATH".
pause
exit /b 1
)
REM Install required packages
pip install -r .\__pycache__\requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple %*
pause
三、转换源码
import os
import sys
import cv2
from datetime import datetime
from tqdm import tqdm
def resize_image(image_path, target_size):
"""Resize the image to the target size."""
image = cv2.imread(image_path)
resized_image = cv2.resize(image, (target_size, target_size))
return resized_image
def process_images_in_directory(directory, target_size):
"""Resize all images in the specified directory to the target size and save them in the output directory."""
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
output_directory = os.path.join(os.getcwd(), f"resized_{target_size}x{target_size}_{timestamp}")
if not os.path.exists(output_directory):
os.makedirs(output_directory)
image_files = [f for f in os.listdir(directory) if f.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.tiff'))]
total_images = len(image_files)
print(f"Processing images from directory: {directory}")
print(f"Total images to process: {total_images}")
for idx, filename in enumerate(tqdm(image_files, desc="Resizing images", unit="image")):
image_path = os.path.join(directory, filename)
resized_image = resize_image(image_path, target_size)
# Save the resized image
resized_image_path = os.path.join(output_directory, filename)
cv2.imwrite(resized_image_path, resized_image)
print(f"Resized images are saved in {output_directory}")
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: python resize_images.py <target_size>")
sys.exit(1)
try:
target_size = int(sys.argv[1])
except ValueError:
print("Target size must be an integer.")
sys.exit(1)
# Get the directory of images, which is in the current directory under 'img'
current_directory = os.getcwd()
image_directory = os.path.join(current_directory, 'img')
if not os.path.exists(image_directory):
print(f"Image directory {image_directory} does not exist.")
sys.exit(1)
process_images_in_directory(image_directory, target_size)
三、转换脚本(.bat)
如果用python原代码运行
@echo off
python .\__pycache__\resize_images.py 512 %*
pause
如果用编译出来的.pyc文件运行
python -m compileall resize_images.py
@echo off
python .\__pycache__\resize_images.pyc 512 %*
pause