PIL中的P模式、P模式转为L模式

1. 参考链接

  • 🍀图片P模式 PIL 分割(这个博文很棒,下面大部分都是这个博文里面的内容)

  • 利用python PIL库进行图像模式的转换

  • P代表palette,调色板,也就是图片中会包含一个调色表的列表,每一个像素位置放的只是一个index,那么这个像素要展示的颜色就是调色板中第index位置展示的颜色

  • 我用到的图片显示出的palette是768=256*3长度,因为每个颜色需要RGB三个通道,所以768长度也就对应了256种颜色,这种图片最多能展示256种颜色,而传统的RGB最多可以展示256*256*256种颜色。(所以P模式与L模式一样,都是8bit图像


2. code:显示调色板情况

import os
import numpy as np
from PIL import Image
from collections import Counter
from random import shuffle

if __name__ == '__main__':
    root_dir = r"D:\SoftWareInstallMenu\JetBrains\PycharmProjects\tunnel_datadeal\crackop\labels"
    names = os.listdir(root_dir)
    # shuffle(names)  # 打乱数组元素
    for name in names:
        path = os.path.join(root_dir, name)
        image = Image.open(path)
        # 打印图片格式
        print(image.mode)
        if image.mode == 'P':
            # 获取调色板
            palette = image.getpalette()
            # 统计每种颜色出现的频率
            print(Counter(np.array(image).flatten()))

            print(len(palette))  # 打印调色板长度:768 = 256 * 3
            print(image.getpalette())  # 打印调色板

3. 得到该图像的模式以及转换

在PIL中,图像模式大致分为9种,分别为:1,L,P,RGB,RGBA,CMYK,YCbCr,I, F

常见的几种模式

  • 1:二值图像(1bit,非黑即白,但是它的每个像素用8个bit表示,0表示黑,255表示白)(下面的8bit也是这个橘色部分的含义,可结合着理解一下)
  • L:灰度图(8bit, 0~255),在PIL模式中,从模式"RGB"转换到模式"L",有一个计算公式,即: L = R ∗ 299 / 1000 + G ∗ 587 / 1000 + B ∗ 114 / 1000 L = R * 299/1000 + G * 587/1000+ B * 114/1000 L=R299/1000+G587/1000+B114/1000(只取整数部分)。
  • P:调色板模式(8bit)
  • RGB:真彩图像(24bit)

在这里插入图片描述

1. 得到图像的mode

from PIL import Image
image = Image.open(image_path)
mode = image.mode
print(mode)	# P

2. 转换模式(接上),用convert

image_L = image.convert('L')
print(image_L.mode)	# L

4. 其他相关博文

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

孟孟单单

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值