【发布时间】:2019-04-09 04:39:54
【问题描述】:
我有一个 PostgreSQL 数据库 (v 9.6),其中图像存储为 bytea 数据。我不知道图像编码。 (我没有设置这个数据库,也不清楚我是否可以改变这个设置,虽然我想,因为在 PostgreSQL 数据库中存储大图像不是(IIUC)最佳实践。)
我想将此数据提取到图像中,或者更好的是,直接提取到 NumPy 数组中。
使用 SQLAlchemy,我可以连接和提取数据:
engine = create_engine(postgresql+psycopg2://user:password@server:port/database)
connection = engine.connect()
result = connection.execute('SELECT image FROM database.table LIMIT 1;')
有问题的图像作为memoryview 对象返回;转换为numpy 数组,它看起来像这样(根据Cython: Convert memory view to NumPy array):
[b'\xaa' b'\x04' b'u' b'\x04' b'\x85' b'\x04' b'E' b'\x04' b'\x7f' b'\x04'
b'\xa5' b'\x04' b'K' b'\x04' b'j' b'\x04' b'\x97' b'\x04' b';' b'\x04'
b'w' b'\x04' b'k' b'\x04' b'E' b'\x04' b'b' b'\x04' b's' b'\x04']
我尝试保存为 jpg 或 tiff 文件(根据 Converting BLOB, stored on a database, to an image on an HTML website),但无法使用图像查看器打开生成的文件。
我也试过这个(Open PIL image from byte file),但是得到了这个结果:
OSError: cannot identify image file <_io.BytesIO object at 0x000002299F4DD830>
或者,来自How to convert hex string to color image in python?,我收到此错误:
ValueError: non-hexadecimal number found in fromhex() arg at position 0
那么:如何将 bytea 数据或 memoryview 对象转换为 NumPy 数组?
我可能遗漏了一些简单的东西,或者这可能只是图像不应该存储在 SQL 数据库中的原因之一。
【问题讨论】:
标签: python postgresql numpy opencv matplotlib