Open bmp file python

Чтение BMP-файлов в Python

Есть ли способ прочитать в файле bmp в Python, который не предполагает использование PIL? PIL не работает с версией 3, которая у меня есть. Я пытался использовать объект Image из graphics.py, Image(anchorPoint, filename), но это, похоже, работает только с GIF-файлами.

8 ответов

В 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 

Я понимаю, что это старый вопрос, но я нашел его, решая эту проблему сам, и подумал, что это может помочь кому-то еще в будущем.

На самом деле довольно просто прочитать файл BMP как двоичные данные. В зависимости от того, насколько широкая поддержка и сколько угловых случаев вам нужно поддержать, конечно.

Ниже приведен простой синтаксический анализатор, который работает ТОЛЬКО для 24-битных BMP 1920×1080 (например, сохраненных в MS Paint). Это должно быть легко расширить, хотя. Он выплевывает значения пикселей в виде списка Python, как (255, 0, 0, 255, 0, 0, . ) для красного изображения в качестве примера.

Читайте также:  Таблица в центре окна

Если вам нужна более надежная поддержка, есть информация о том, как правильно прочитать заголовок в ответах на этот вопрос: Как прочитать заголовок файла bmp в python?, Используя эту информацию, вы сможете расширить простой парсер, представленный ниже, любыми функциями, которые вам нужны.

Также есть больше информации о формате файла BMP в википедии https://en.wikipedia.org/wiki/BMP_file_format если вам это нужно.

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) 

Источник

Читайте также:  Чем занимаются php программисты

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Python package to read a BMP file’s header and pixel array in binary.

License

dannybritto96/pybmp

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Python package to read a BMP file’s header and pixel array in binary.

from pybmp2 import BMP img = BMP(filename="sample.bmp") print(img.SHAPE) print(img.PIXELARRAY) print(img.RAWIMGSIZE)
from pybmp import BMP import binascii f = open('samp.bmp','rb') content = f.read() content = binascii.hexlify(content) img = BMP(hexdata=hexdata) print(img.SHAPE) print(img.PIXELARRAY) print(img.RAWIMGSIZE)

About

Python package to read a BMP file’s header and pixel array in binary.

Источник

pybmp2 1.0

Python package to read a BMP file’s header and pixel array in binary.

Ссылки проекта

Статистика

Метаданные

Лицензия: MIT License

Сопровождающие

Классификаторы

Описание проекта

Py BMP

Python package to read a BMP file’s header and pixel array in binary.

Install Instructions

Usage

Подробности проекта

Ссылки проекта

Статистика

Метаданные

Лицензия: MIT License

Сопровождающие

Классификаторы

История выпусков Уведомления о выпусках | Лента RSS

Загрузка файлов

Загрузите файл для вашей платформы. Если вы не уверены, какой выбрать, узнайте больше об установке пакетов.

Source Distribution

Uploaded 2 апр. 2022 г. source

Built Distribution

Uploaded 2 апр. 2022 г. py3

Хеши для pybmp2-1.0.tar.gz

Хеши для pybmp2-1.0.tar.gz
Алгоритм Хеш-дайджест
SHA256 30b5aa5c2a608b106b75de0420743d636ec9587a0daf6fb84aeb571e554a87c1 Копировать
MD5 58a4dc4daf683a645e6893b6b930490d Копировать
BLAKE2b-256 4b82b3619feafef6859af766dd10633ad16eb37f9641b8f8329b65dbe3f469aa Копировать

Хеши для pybmp2-1.0-py3-none-any.whl

Хеши для pybmp2-1.0-py3-none-any.whl
Алгоритм Хеш-дайджест
SHA256 a04aaef8cb9d9c18f30bdbbbd0209f865c9e5682074b096c31539734b2c96fb4 Копировать
MD5 8df78741e1c69b0ebe4d30b324c1de34 Копировать
BLAKE2b-256 aafff32cd3399460aa9567f09a636fe2014d3c169fdd10391fa74a6e26f457a3 Копировать

Помощь

О PyPI

Внесение вклада в PyPI

Использование PyPI

Разработано и поддерживается сообществом Python’а для сообщества Python’а.
Пожертвуйте сегодня!

PyPI», «Python Package Index» и логотипы блоков являются зарегистрированными товарными знаками Python Software Foundation.

Источник

Оцените статью