无法保存 4d 数组 int .txt 文件

cant save an 4d array int .txt file

我正在对图像使用滑动 window 技术,并且正在提取每个图像的像素的平均值 window。所以结果有点像这样 [[[[215.015625][123.55036272][111.66057478]]]]。现在的问题是我如何将每个 window 的所有这些值保存到 txt 文件或 CSV 文件中因为我想用它们来进一步比较相似之处?无论我尝试什么,错误都是一样的……它是一个 4D 数组而不是 1D 或 2D。我真的很感激任何帮助。!提前谢谢你

import cv2
import matplotlib.pyplot as plt
import numpy as np


# read the image and define the stepSize and window size
# (width,height)
image2 = cv2.imread("bird.jpg")# your image path

image = cv2.resize(image2, (224, 224))
tmp = image  # for drawing a rectangle
stepSize = 10
(w_width, w_height) = (60, 60 )  # window size
for x in range(0, image.shape[1] - w_width, stepSize):
    for y in range(0, image.shape[0] - w_height, stepSize):
        window = image[x:x + w_width, y:y + w_height, :]

        # classify content of the window with your classifier and
        # determine if the window includes an object (cell) or not
        # draw window on image
        cv2.rectangle(tmp, (x, y), (x + w_width, y + w_height), (255, 0, 0), 2)  # draw rectangle on image
        plt.imshow(np.array(tmp).astype('uint8'))
        # show all windows
        plt.show()
        mean_values=[]
        mean_val, std_dev = cv2.meanStdDev(image)
        mean_val = mean_val[:3]
        mean_values.append([mean_val])
        mean_values = np.asarray(mean_values)
        print(mean_values)

人类可读选项

假设您希望数据是人类可读的,保存数据需要更多的工作。我的搜索显示有 this 将 3D 数据保存到文本文件的解决方案。但是,针对您的用例将此示例扩展到 4D 非常简单。此代码取自并改编自 post,谢谢 Joe Kington 和 David Cheung。

import numpy as np
data = np.arange(2*3*4*5).reshape((2,3,4,5))
with open('test.csv', 'w') as outfile:
    # We write this header for readable, the pound symbol
    # will cause numpy to ignore it
    outfile.write('# Array shape: {0}\n'.format(data.shape))

    # Iterating through a ndimensional array produces slices along
    # the last axis. This is equivalent to data[i,:,:] in this case.
    # Because we are dealing with 4D data instead of 3D data,
    # we need to add another for loop that's nested inside of the
    # previous one.
    for threeD_data_slice in data:
        for twoD_data_slice in threeD_data_slice:
            # The formatting string indicates that I'm writing out
            # the values in left-justified columns 7 characters in width
            # with 2 decimal places. 
            np.savetxt(outfile, twoD_data_slice, fmt='%-7.2f')
            # Writing out a break to indicate different slices...
            outfile.write('# New slice\n')

然后一旦数据被保存,你需要做的就是加载它并重塑它(np.load())将默认以二维数组的形式读取数据,但 np.reshape() 将允许我们恢复结构。同样,此代码改编自之前的 post.

new_data = np.loadtxt('test.csv')
# Note that this returned a 2D array!
print(new_data.shape)

# However, going back to 3D is easy if we know the 
# original shape of the array
new_data = new_data.reshape((2,3,4,5))

# Just to check that they're the same...
assert np.all(new_data == data)

二元期权

假设不需要人类可读性,我建议使用 here 描述的内置 *.npy 格式。这以二进制格式存储数据。

您可以通过 np.save('NAME_OF_ARRAY.npy', ARRAY_TO_BE_SAVED) 保存数组,然后使用 SAVED_ARRAY = np.load('NAME_OF_ARRAY.npy') 加载它。

您还可以使用 np.savez() 函数将多个 numpy 数组保存在一个 zip 文件中,例如 np.savez('MANY_ARRAYS.npz', ARRAY_ONE, ARRAY_TWO)。然后以类似的方式加载压缩数组 SEVERAL_ARRAYS = np.load('MANY_ARRAYS.npz').