使用python将图像转换为像素数据帧到csv文件

2024-09-26 22:51:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含图片的文件夹("C:\Users\Admin\Downloads\mypicture") 这里是它的例子 82

我想把它转换成像这样的像素数据帧

  pixel1 pixel. pixel158 pixel159 pixel160 pixel161 pixel162 pixel163 pixel164 pixel165 pixel166 pixel167 pixel168 pixel169 pixel170 pixel171 pixel172
1      0      …        0      191      250      253       93        0        0        0        0        0        0        0        0        0        0
2      0      …       32        0        0        0        0        0        0        0        0        0        0        0        0        0        0
  pixel173 pixel174 pixel175 pixel176
1        0        0        0        0
2        0        0       16      179

每个图像都表示为一行。每个图像的灰度在[0255]范围内。 我会的

^{pr2}$

但我得到了这个错误

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

如何在csv文件中获得所需的数据帧?在


Tags: 数据图像文件夹admindownloads图片像素users
1条回答
网友
1楼 · 发布于 2024-09-26 22:51:05

您可以使用PIL库将图像转换为像素数据帧,方法是从如下图像中获取像素列表

from PIL import Image
im = Image.open('image.png')

pixels = list(im.getdata())

这将返回一个包含(r,g,b)值的像素列表,因此如果您只想获得每个像素的灰度,只需在每个值的第二个元素中迭代该列表,如下所示

^{pr2}$

输出:

['pixel1', 72], ['pixel2', 50], ['pixel3', 0], ['pixel4', 11], ['pixel5', 30], ['pixel6', 42], ['pixel7', 107], ['pixel8', 123], ['pixel9', 124], ['pixel10', 130]

相关问题 更多 >

    热门问题