首页 > 解决方案 > 无法保存 4d 数组 int .txt 文件

问题描述

我正在对图像使用滑动窗口技术,并且我正在提取每个窗口的像素的平均值。所以结果是这样的[[[[215.015625][123.55036272][111.66057478]]]]。现在的问题是如何将每个窗口的所有这些值保存到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)

标签: pythonnumpy-ndarraysliding-window

解决方案


人类可读选项

假设您希望数据是人类可读的,保存数据需要更多的工作。我的搜索告诉我,有这种将 3D 数据保存到文本文件的解决方案。但是,为您的用例将此示例扩展到 4D 非常简单。此代码取自该帖子并改编自该帖子,感谢 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()允许我们恢复结构。同样,这段代码改编自上一篇文章。

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)

二元期权

假设不需要人类可读性,我建议使用此处描述的内置*.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')


推荐阅读