从图像中获取RGB数据,并将其写入具有相应像素的CSV文件



我在这段代码中遇到了一些错误,该代码本应将图像中的信息写入csv文件。

目前,我有一段代码,可以将图像的所有像素[确切地说是X、Y坐标]写入csv文件。

import PIL
import numpy as np
img_grey = Image.open('walkingpath_005004.jpg').convert('L')
print(img_grey.size)
# (300, 241)
x = 3
y = 4
#pix = img_grey.load()
#print(pix[x,y])
# Taken from: https://stackoverflow.com/a/60783743/11089932
xy_coords = np.flip(np.column_stack(np.where(np.array(img_grey) >= 0)), axis=1)
# Add pixel numbers in front
pixel_numbers = np.expand_dims(np.arange(1, xy_coords.shape[0] + 1), axis=1)
#get rgb data
pixels = list(img_grey.getdata()) 
width, height = img_grey.size  
pixels = np.asarray(img_grey)
value = np.hstack([pixel_numbers, xy_coords, pixels])
print(value)
# [[    1     0     0]
#  [    2     1     0]
#  [    3     2     0]
#  ...
#  [72298   297   240]
#  [72299   298   240]
#  [72300   299   240]]
# Properly save as CSV
np.savetxt("outputdata.csv", value, delimiter='t', fmt='%4d')

我需要在3个额外的列中的每个像素的RGB数据。因此,格式应为
PixelNumber X Y R G B

当前面临此错误:ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 0, the array at index 0 has size 258063 and the array at index 2 has size 509

我在看这个链接如何在Python中读取给定像素的RGB值
但不确定如何将其合并到现有代码中。

感谢您的帮助!

谢谢!

xy_coords的原始解决方案必须进行调整,因为您现在处理的是三通道图像,而不是单通道图像。而且,要获得每个像素的RGB元组,只需要重塑NumPy数组,就可以了。

from PIL import Image
import numpy as np
img = Image.open('path/to/your/image.png')
print('Inspect a few pixels in the original image:')
for y in np.arange(3):
for x in np.arange(3):
print(x, y, img.getpixel((x, y)))
# Modified for RGB images from: https://stackoverflow.com/a/60783743/11089932
img_np = np.array(img)
xy_coords = np.flip(np.column_stack(np.where(np.all(img_np >= 0, axis=2))), axis=1)
rgb = np.reshape(img_np, (np.prod(img_np.shape[:2]), 3))
# Add pixel numbers in front
pixel_numbers = np.expand_dims(np.arange(1, xy_coords.shape[0] + 1), axis=1)
value = np.hstack([pixel_numbers, xy_coords, rgb])
print('nCompare pixels in result:')
for y in np.arange(3):
for x in np.arange(3):
print(value[(value[:, 1] == x) & (value[:, 2] == y)])
# Properly save as CSV
np.savetxt("outputdata.csv", value, delimiter='t', fmt='%4d')

用于比较的两个输出:

Inspect a few pixels in the original image:
0 0 (63, 124, 239)
1 0 (65, 123, 239)
2 0 (64, 124, 240)
0 1 (74, 128, 238)
1 1 (66, 122, 239)
2 1 (68, 125, 239)
0 2 (173, 200, 244)
1 2 (86, 134, 239)
2 2 (80, 132, 240)
Compare pixels in result:
[[  1   0   0  63 124 239]]
[[  2   1   0  65 123 239]]
[[  3   2   0  64 124 240]]
[[301   0   1  74 128 238]]
[[302   1   1  66 122 239]]
[[303   2   1  68 125 239]]
[[601   0   2 173 200 244]]
[[602   1   2  86 134 239]]
[[603   2   2  80 132 240]]
----------------------------------------
System information
----------------------------------------
Platform:      Windows-10-10.0.19041-SP0
Python:        3.9.1
PyCharm:       2021.1.1
NumPy:         1.19.5
Pillow:        8.2.0
----------------------------------------

我认为你可以尝试使用glob.glob,从代码的角度来看应该会有所帮助

import numpy as np
import glob
import cv2
import csv
image_list = []
for filename in glob.glob(r'C:your path tofile*.png'):    # '*' will count files each by one

#Read
img = cv2.imread(filename)
flattened = img.flatten() 
print(flattened) # recommend to avoid duplicates, see files and so on.
#Save
with open('output2.csv', 'ab') as f: #ab is set 
np.savetxt(f, flattened, delimiter=",")

干杯



此外,找到一种更简单的方法,使快速而不加权图像.csv
image_list = []
with open('train_train_.csv', 'w') as csv_file:
csv_writer = csv.writer(csv_file, delimiter ='-')
for filename in glob.glob(r'C:your path tofile*.png'):
img = cv2.imread(filename)
image_list.append(img)
csv_writer.writerow(img)
print(img)

相关内容

最新更新