python - Pandas - 图像到 DataFrame

标签 python image pandas

我想将 RGB 图像转换为 DataFrame,以便获得每个像素的坐标及其 RGB 值。

         x   y   red  green  blue
0        0   0   154      0     0
1        1   0   149    111     0
2        2   0   153      0     5
3        0   1   154      0     9
4        1   1   154     10    10
5        2   1   154      0     0

我可以很容易地将 RGB 提取到 DataFrame 中

colourImg = Image.open("test.png")
colourPixels = colourImg.convert("RGB")
colourArray = np.array(colourPixels.getdata())

df = pd.DataFrame(colourArray, columns=["red","green","blue"])

但我不知道如何获取其中的 X 和 Y 坐标。我可以编写一个循环,但是在大图像上需要很长时间。

最佳答案

尝试使用np.indices不幸的是它最终得到一个坐标是第一个维度的数组,但你可以做一些np.moveaxis来解决这个问题.

colourImg = Image.open("test.png")
colourPixels = colourImg.convert("RGB")
colourArray = np.array(colourPixels.getdata()).reshape(colourImg.size + (3,))
indicesArray = np.moveaxis(np.indices(colourImg.size), 0, 2)
allArray = np.dstack((indicesArray, colourArray)).reshape((-1, 5))


df = pd.DataFrame(allArray, columns=["y", "x", "red","green","blue"])

这不是最漂亮的,但它似乎有效(编辑:修复了 x,y 的错误方式)。

关于python - Pandas - 图像到 DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49649215/

相关文章:

python - 如何在 Pandas 中组合 3 个复杂的数据框

python - 重采样错误 : cannot reindex a non-unique index with a method or limit

python - 从 Arduino C 到 Raspberry pi python - 线程内的 volatile 变量访问

python - GUI 中的值更新

ios - 将图像编码为 base64,得到无效的 base64 字符串(ios 使用 base64EncodedStringWithOptions)

ios - 如何实现不同分辨率的图像

python - 在 Gephi 中打开之前在 Networkx write_graphml 中添加属性

python - 如何在 python 中模拟 RPi.GPIO

python - tensorflow 在图执行期间添加摘要

android - 显示来自 byteArray 的图像