栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python图片位深转换

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python图片位深转换

洒家几次需要4位转8位图,用Ps实在不便
记录下python脚本

import os
from PIL import Image # pip install Pillow 
import numpy as np    # pip install numpy
from pathlib import Path

old_file = input("要转换的图片:")
new_file="new_"+old_file
print("可选的格式为,注意大小写:n
    1:1位像素,表示黑和白,但是存储的时候每个像素存储为8bit。二值化图 n
    L:8位像素,表示黑和白。 灰度图 n
    P:8位像素,使用调色板映射到其他模式。n
    RGB:3x8位像素,为真彩色。n
    RGBA:4x8位像素,有透明通道的真彩色。n
    CMYK:4x8位像素,颜色分离。n
    YCbCr:3x8位像素,彩色视频格式。n
    I:32位整型像素。n
    F:32位浮点型像素。")
new_format = input("要转换的格式为:")

file_checker = Path(old_file)
if file_checker.exists():
    print("目前格式为"+str(Image.open(old_file).getbands()))
    if new_format == "1" or new_format == "L" or new_format == "P" or new_format == "RGB" or 
            new_format == "RGBA" or new_format == "CMYK" or new_format == "YCbCr" or 
            new_format == "I" or new_format == "F":
        img = Image.open(old_file).convert(new_format)
        print("新格式为:"+str(img.getbands())) 
        img.save(new_file) 
        print("转换成功,新文件为:"+new_file)
    else:
        print("格式错误,请按大小写")
else:
    print("文件不存在")

解析
其实就下面这两句就转换了

        img = Image.open(old_file).convert(new_format)
        print("新格式为:"+str(img.getbands())) 
        img.save(new_file) 

python真的天下第一 。。。(=。=)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/341865.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号