我意识到这是一个老问题,但我自己解决这个问题时发现了这个问题,我想这可能会在将来帮助别人。
实际上很容易将BMP文件读取为二进制数据。当然,这取决于你需要支持的范围有多广,需要支持的角落案例有多少。
下面是一个简单的解析器,它只适用于1920×1080 24位BMP(类似于从MS-Paint保存的)。但它应该很容易扩展。它以python列表的形式输出像素值,比如红色图像的(255, 0, 0, 255, 0, 0, …)。
如果您需要更强大的支持,这里有一些关于如何正确读取这个问题的答案中的头的信息:How to read bmp file header in python?。使用这些信息,您应该能够使用所需的任何特性扩展下面的简单解析器。
如果你需要的话,维基百科上还有更多关于BMP文件格式的信息。def read_rows(path):
image_file = open(path, “rb”)
# Blindly skip the BMP header.
image_file.seek(54)
# We need to read pixels in as rows to later swap the order
# since BMP stores pixels starting at the bottom left.
rows = []
row = []
pixel_index = 0
while True:
if pixel_index == 1920:
pixel_index = 0
rows.insert(0, row)
if len(row) != 1920 * 3:
raise Exception(“Row length is not 1920*3 but ” + str(len(row)) + ” / 3.0 = ” + str(len(row) / 3.0))
row = []
pixel_index += 1
r_string = image_file.read(1)
g_string = image_file.read(1)
b_string = image_file.read(1)
if len(r_string) == 0:
# This is expected to happen when we’ve read everything.
if len(rows) != 1080:
print “Warning!!! Read to the end of the file at the correct sub-pixel (red) but we’ve not read 1080 rows!”
break
if len(g_string) == 0:
print “Warning!!! Got 0 length string for green. Breaking.”
break
if len(b_string) == 0:
print “Warning!!! Got 0 length string for blue. Breaking.”
break
r = ord(r_string)
g = ord(g_string)
b = ord(b_string)
row.append(b)
row.append(g)
row.append(r)
image_file.close()
return rows
def repack_sub_pixels(rows):
print “Repacking pixels…”
sub_pixels = []
for row in rows:
for sub_pixel in row:
sub_pixels.append(sub_pixel)
diff = len(sub_pixels) – 1920 * 1080 * 3
print “Packed”, len(sub_pixels), “sub-pixels.”
if diff != 0:
print “Error! Number of sub-pixels packed does not match 1920*1080: (” + str(len(sub_pixels)) + ” – 1920 * 1080 * 3 = ” + str(diff) +”).”
return sub_pixels
rows = read_rows(“my image.bmp”)
# This list is raw sub-pixel values. A red image is for example (255, 0, 0, 255, 0, 0, …).
sub_pixels = repack_sub_pixels(rows)
今天的文章python读取bmp图片_用Python读取bmp文件分享到此就结束了,感谢您的阅读。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/11913.html