有没有一种不必使用PIL就能在Python中读取bmp文件的方法?我使用的是版本3,而PIL与此版本不兼容。我尝试过使用graphics.py中的Image对象(Image(anchorPoint, filename)),但它似乎只适用于gif文件。
有没有一种不必使用PIL就能在Python中读取bmp文件的方法?我使用的是版本3,而PIL与此版本不兼容。我尝试过使用graphics.py中的Image对象(Image(anchorPoint, filename)),但它似乎只适用于gif文件。
在Python中,它可以简单地被读取为:
import os
from scipy import misc
path = 'your_file_path'
image= misc.imread(os.path.join(path,'image.bmp'), flatten= 0)
## flatten=0 if image is required as it is
## flatten=1 to flatten the color layers into a single gray-scale layer
imread
(等函数)已被弃用,并将在1.2版中移除。SciPy 1.2 将使用 imageio.imread
。 - uhoh(255, 0, 0, 255, 0, 0, …)
。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)
from PIL import Image
然后您可以加载BMP文件
img = Image.open('path_to_file\file.bmp')
np.array
。img = np.array(Image.open('path_to_file\file.bmp'))
reshape()
将其调整为正确的形状。例如:np.array(Image.open('path_to_file\file.bmp')).reshape(512,512,3)
import matplotlib.pyplot as plt
im = plt.imread('image.bmp')
我曾经需要使用Python读取BMP文件的项目,这个过程非常有趣。实际上,最好的方法是先了解BMP文件格式(https://en.wikipedia.org/wiki/BMP_file_format),然后将其作为二进制文件读取以提取数据。
你需要使用Python的struct库进行数据提取。
你可以使用这个教程了解具体操作:https://youtu.be/0Kwqdkhgbfw
这取决于您想要实现什么以及在哪个平台上?
无论如何,使用C库来加载BMP可能会起作用,例如http://code.google.com/p/libbmp/或http://freeimage.sourceforge.net/,并且可以轻松地从Python中调用C库,例如使用ctypes或将其包装为Python模块。
或者您可以编译此版本的PIL https://github.com/sloonz/pil-py3k
如果您正在使用Windows操作系统,此网站应该可以帮助您在大多数Python版本中安装PIL(以及许多其他流行的软件包):Python扩展包的非官方Windows二进制文件
def load_Philips30XL_BMP(fname):
"""
Experimental loading of BMPs from Philips30XL microscopes (they have an atypical format which cannot be loaded by imageio)
See https://ide.kaitai.io/ for more information on BMP header.
"""
with open(fname, mode='rb') as file: # first analyze the header
fileContent = file.read()
ofs, w, h, bpp, compr = [int.from_bytes(fileContent[s:e], byteorder='little', signed=False) for s,e in
((0x0a,0x0e),(0x12,0x16),(0x16,0x1a),(0x1c,0x1e),(0x1e,0x22))]
assert bpp == 8, f'monochrome/LUT image assumed (8 bit per pixel); {fname} has {bpp}bpp'
assert compr == 0, 'no decompression algorithm implemented'
return np.fromfile(fname, dtype=np.uint8)[ofs:ofs+w*h].reshape(h,w)[::-1,:] # BMP is "upside down" - flip vertically