将图像的坐标导出为 python 中的 excel 格式

export coordinate from an image to excel format in python

我有this image that has been converted to binary, all I need is the coordinate data (x-y) of all the white pixels but in excel format (.xlsx or .xls) like this,如何获取?

以前,我在 Matlab 中尝试使用 bw.boundaries 命令,但我得到的只是边缘坐标(不是整个区域)。现在我想在 python 中完成它,有没有办法做到这一点? 提前谢谢你。

import imageio
from skimage.color import rgb2gray

im = rgb2gray(imageio.imread("img.jpg"))

np.savetxt('img.csv', np.argwhere(img > 0.5), fmt='%d', delimiter=',')

或者如果您的图像存储为 uint8

np.savetxt('img.csv', np.argwhere(img > 127), fmt='%d', delimiter=',')

或者如果您的图像存储为二进制数组

np.savetxt('img.csv', np.argwhere(img != 0), fmt='%d', delimiter=',')

编辑: OP 的一个小例子,希望能更好地理解它是如何工作的

import numpy as np
import imageio

# let's load a sample image
cat = imageio.imread('imageio:chelsea.png')   

# let's turn it into b/w by thresholding the read channel
cat_bw = cat[..., 0] > 127

# now we can get the white pixel coordinates
white_coords = np.argwhere(cat_bw)

# you could save them to csv with
np.savetxt('img.csv', white_coords, fmt='%d', delimiter=',')

你会得到类似

的东西
$ cat img.csv
0,0
0,1
0,2
0,3
0,4
[...]
299,445
299,446
299,447
299,448
299,449
299,450

不确定您将如何在 Excel 中处理它们,这超出了我的专业知识,但假设您想要确保坐标是我们想要的。

让我们绘制我们的 b/w 切尔西 (cat_bw):

现在让我们尝试将原始图像中的坐标转换为另一种颜色,让我们以一种超级愚蠢而不是 numpythonic 的方式将其变成粉红色:

for x, y in white_coords: 
    cat[x, y] = [219, 49, 190]

并绘制它:

所以,在我看来,white_coords 数组和我们保存它们的 csv 文件实际上包含我们的白色像素坐标。