首页 > 解决方案 > 将数据保存在for循环中但不保存在循环中

问题描述

我将图像提取到 NumPy 数组,然后从所有图像中选择第一列,然后从所有图像中附加所有第一列以通过 for 循环保存第一个 CSV 文件。对于第二列,第三列,...是相同的方法,但它最终保存在循环中而不是保存。这是我的代码,请告诉并教我。

def image_2_data_2_GLCM305():
    images = glob.glob("*.jpg")
    for i in range(1, 11):
        print(i)
        data = []
        for image in images:
            img = cv2.imread(image,0)
            img = img[i:i+1]    # 640*480==> (width * high)
            data.append(img)

        data1 = np.array(data)
        new_array = data1.reshape(numpic,-1) # number of image(จำนวนรูป)
        new_array = np.array(new_array)
        np.savetxt("Array.csv", new_array, delimiter=",", fmt='%.0f')
        np.save('outfile', new_array)
        print('*******************************')
        print(new_array.shape)
        print(new_array)
        np.savetxt('Array.csv', new_array, delimiter=",", fmt='%.0f')

print(image_2_data_2_GLCM305())

标签: pythonnumpy

解决方案


只需保存在循环之外。但是您的代码有很多不一致之处。

def image_2_data_2_GLCM305():
    images = glob.glob("*.jpg")
    for i in range(1, 11):
        print(i)
        data = []
        for image in images:
            img = cv2.imread(image,0)
            img = img[i:i+1]    # 640*480==> (width * high) # why are you doing this? Do you just need a single pixel from the sequence of images?
            data.append(img)

    data1 = np.array(data)
    new_array = data1.reshape(numpic,-1) # number of image(จำนวนรูป)
    new_array = np.array(new_array)
    np.savetxt("Array.csv", new_array, delimiter=",", fmt='%.0f')
    np.save('outfile', new_array)
    print('*******************************')
    print(new_array.shape)
    print(new_array)
    np.savetxt('Array.csv', new_array, delimiter=",", fmt='%.0f')

推荐阅读