如何在python中保存从图像转换的数组?

时间:2018-03-09 22:24:43

标签: python arrays image

任务是从图像中读取并提取数据以获得25 x 25像素的网格。我使用此代码来提取它,我得到了数据。但我怎么能把它保存在文本文件中以查看整个25 x 25阵列?

我刚刚将图像转换为如下数组:

>>> img=cv2.imread("1670.png",0)
>>> img=cv2.imread("1670.png",0)

>>> img
array([[14, 15, 15, ..., 92, 91, 92],
[14, 15, 15, ..., 93, 93, 91],
[15, 15, 16, ..., 94, 93, 91],
...,
[69, 71, 76, ..., 73, 70, 68],
[69, 75, 81, ..., 76, 72, 69],
[69, 76, 81, ..., 80, 75, 71]], type=uint8)

我想将其保存为25 x 25数组的文本文件。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

用一些不同的文件转换写了一个小脚本:

# -*- coding: utf-8 -*-
"""
Created on Fri Mar 09 15:53:54 2018
@author: soyab
"""

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.misc import imread, imsave, imresize

#%%
## Read photo ; view photo
img = imread('new_photo.jpg')
plt.imshow(img)

#%%
## Treat as a Numpy array
np.shape(img)
newimg = img[:25,:25,:][:,:,0] ## Take a 25x25 slice from a 
np.shape(newimg)               ##  three 'layer' photo
plt.imshow(newimg)

#%%
## Save as a jpeg ; visual check
imsave('modify_new_photo.jpg',newimg)
nextimg = imread('modify_new_photo.jpg')
plt.imshow(nextimg)

#%%
## Using a Pandas Dataframe ; like a Kung Fu Panda
### Save as .txt or .csv ; reload as a pd.DataFrame
#### Review again as an image
nextimg = pd.DataFrame(nextimg)
nextimg.to_csv('modify_nextimg.txt',header=False,index=False)
fimg = pd.read_csv('modify_nextimg.txt')
plt.imshow(fimg)