用python脚本转换图片分辨率

在这里插入图片描述
在这里插入图片描述

一、使用说明

  1. 确定已经安装python,且版本3.6以上,可以用下面指令查看python版本:python --version

  2. 配置环境,第一次使用先配置环境,后面不需要

  3. 把要转换的图片放到"img"文件夹下

  4. 转换,结果保存在本目录下的新创建的文件夹中

二、配置环境脚本(.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

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值