python - 如何获取位图图像的位深度
问题描述
我有一些图像,我想知道 .bmp 图像的位深度。这在 Windows 中手动操作(属性>详细信息..)非常容易,但谷歌似乎并没有太多关于它的信息,而且我在这里看到的一个答案(对我来说)并没有显示如何做到这一点。
代码
import png as png
import numpy as np
r=png.Reader(filename = r'C:\Users\priper\Desktop\OPW_refac\grayscale.png')
a = r.read()
print(a[3]['bitdepth'])
或者
from PIL import Image
import numpy as np
#Load the BMP file
img = Image.open(r'C:\Users\priper\Desktop\OPW_refac\HSS All As.bmp')
print(img, '\n')
print('bit depth :', img.mode)#this only tells me it is 8 pixels, I don't think it could tell me if it was 4.
#Or as a numpy array
img = np.array(Image.open(r'C:\Users\priper\Desktop\OPW_refac\HSS All As.bmp'))
print(img)
我可以读取 png 的位深度,但不知道哪个库可以轻松地从 bmp 获取类似信息。
解决方案
使用适当的库可能会更好,例如wand
or exiftool
,但是如果您想要轻量级的东西,这可能就足够了-但是我无法在您的图像上对其进行测试,因为您没有共享任何内容:
#!/usr/bin/env python3
import sys
import struct
# Read first 100 bytes
with open('a.bmp','rb') as f:
BMP = f.read(100)
if BMP[0:2] != b'BM':
sys.exit('ERROR: Incorrect BMP signature')
# Get BITMAPINFOHEADER size - https://en.wikipedia.org/wiki/BMP_file_format
BITMAPINFOHEADERSIZE = struct.unpack('<i',BMP[14:18])[0]
okSizes = [40, 52, 56, 108, 124]
if BITMAPINFOHEADERSIZE not in okSizes:
sys.exit(f'ERROR: BITMAPINFOHEADER size was {BITMAPINFOHEADERSIZE}, expected one of {okSizes}')
# Get bits per pixel
bpp = struct.unpack('<H',BMP[28:30])[0]
print(f'bbp: {bpp}')
我使用ImageMagick创建了一个示例 BMP,如下所示:
magick -size 32x32 xc:red -define bmp:subtype=RGB565 a.bmp
然后我运行我的脚本并得到bpp:16
匹配的exiftool
输出:
exiftool a.bmp
ExifTool Version Number : 12.00
File Name : a.bmp
Directory : .
File Size : 2.1 kB
File Modification Date/Time : 2021:02:24 12:01:51+00:00
File Access Date/Time : 2021:02:24 12:01:52+00:00
File Inode Change Date/Time : 2021:02:24 12:01:51+00:00
File Permissions : rw-r--r--
File Type : BMP
File Type Extension : bmp
MIME Type : image/bmp
BMP Version : Windows V5
Image Width : 32
Image Height : 32
Planes : 1
Bit Depth : 16 <--- HERE IT IS
Compression : Bitfields
Image Length : 2048
Pixels Per Meter X : 0
Pixels Per Meter Y : 0
Num Colors : Use BitDepth
Num Important Colors : All
Red Mask : 0x0000f800
Green Mask : 0x000007e0
Blue Mask : 0x0000001f
Alpha Mask : 0x00000000
Color Space : sRGB
Rendering Intent : Picture (LCS_GM_IMAGES)
Image Size : 32x32
Megapixels : 0.001
然后我创建了一个像这样的 24 位 BMP:
magick -size 32x32 xc:red a.bmp
以及我的 Python 和exiftool
报告 24 bpp。
关键词:Python。BMP,图像处理,获取深度,位深度,bpp。
推荐阅读
- security - 防止在 keycloak 中对某些用户进行暴力检测
- javascript - React hooks setter在数组拼接后不会触发重新渲染
- android - ConstraintLayout 中的视图不适合屏幕边界
- php - 对数组进行分类并根据其组及其顺序获取第一个和最后一个值
- spring-integration - 在 Spring Integrration 中,DSL 如何指定订阅已发布频道?
- react-native - React Navigation 底部选项卡不适用于 React Native for Web
- wordpress - 具有动态选项的 Woocommerce 的自定义结帐字段
- java - 在 MultipartUploadRequest 中配置通知
- javascript - 在javascript + php laravel中检查父母时自动检查孩子
- sql - Hive 查询 CASE WHEN 状态