【问题标题】:cant save an 4d array int .txt file无法保存 4d 数组 int .txt 文件
【发布时间】:2020-10-08 01:11:35
【问题描述】:

我正在对图像使用滑动窗口技术,并且我正在提取每个窗口的像素的平均值。所以结果是这样的[[[[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)

【问题讨论】:

  • 您需要文本文件是人类可读的还是仅仅存储数组?
  • 先生,我想要一个人类可读的文本文件!非常感谢
  • @chmarios 我提出的解决方案有意义吗?
  • @MaxFeinberg 是的,先生,这绝对有道理!我更喜欢使用 npy 的第二种方法,因为我是新手,所以我更容易理解它!再次非常感谢您
  • @chmarios 你介意接受我的回答吗?

标签: python numpy-ndarray sliding-window


【解决方案1】:

人类可读选项

假设您希望数据是人类可读的,保存数据需要更多的工作。我的搜索显示有this 解决方案可以将 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 格式,描述为here。这以二进制格式存储数据。

您可以通过 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')

【讨论】:

    猜你喜欢
    • 2022-01-23
    • 1970-01-01
    • 2018-12-15
    • 1970-01-01
    • 1970-01-01
    • 2016-04-04
    • 2021-12-18
    • 2012-03-22
    • 2017-04-14
    相关资源
    最近更新 更多