将图像保存为文件中的 numpy 数组,并使用 Python 从文件中将其作为图像加载回来

我正在尝试将图像转换为 numpy 数组并将其另存为文本/csv 文件。然后我尝试将 text/csv 文件的内容加载回图像中。

在整个过程中,维度、数据类型的像素值不能改变,以便准确地重建原始图像(不失真)。

到目前为止我所拥有的-

testim = cv2.imread('img.jpg') #reading the input image

numpyimg = np.array(testim) # Saving as a numpy array

# Checking the shape and image
cv2_imshow(numpyimg)
print(numpyimg.shape)

# Trying to save in csv
for i in numpyimg:
  np.savetxt(fname="image_array.csv",delimiter=",",X=i)

# Check generated csv file after loading it

image_array = np.loadtxt(
    fname="image_array.csv","
)

print("NumPy array: \n",image_array)
print("Shape: ",image_array.shape)
print("Data Type: ",image_array.dtype.name)

当我打印保存文件的内容时,我看到了什么 -

NumPy array that I could saved in a file: 
 [[ 70. 176. 153.]
 [ 63. 170. 144.]
 [ 57. 167. 139.]
 ...
 [ 69. 118.  80.]
 [ 67. 117.  77.]
 [ 64. 114.  74.]]
Shape:  (1040,3)

原图的数组虽然-

array([[[ 78,120,165],[ 63,105,150],[ 48,91,134],...,[ 22,80,51],[ 35,62],[ 49,76]],[[ 77,122,160],[ 62,109,147],[ 50,95,132],[ 24,84,54],[ 29,87,58],[ 38,96,67]],[[ 73,124,[ 66,143],116,137],[ 28,90,60],[ 26,86,56],[ 27,57]],[ 69,118,80],[ 67,117,77],[ 64,114,74]]],dtype=uint8)
shape: (780,1040,3)

这些看起来不太一样,我不明白出了什么问题。

有没有更简单、更准确的方法来解决这个问题?

我已经坚持了很长时间。任何帮助表示赞赏!

iCMS 回答:将图像保存为文件中的 numpy 数组,并使用 Python 从文件中将其作为图像加载回来

这些看起来不太一样,我不明白出了什么问题。

表示彩色图像 OpenCV 使用三维数组。要访问单个值,您必须提供 3:Y 坐标、X 坐标、哪个颜色通道(0 表示 Blue1 表示 Green >,2 表示 Red,如果我没记错 OpenCV 约定的话。

text/csv 非常适合表示 2D 数据(想想电子表格),但如果您希望有更多维度,则需要在写入之前和读取之后进行特殊处理。 RFC4180 不提供与列内容类型相关的任何功能。

,

Have you focused on the size of both arrays?

这是 CSV 文件的大小 = (1040,3)。

原始图片的大小 = (780,1040,3).

尝试在任何操作之前将图像从 RGB 转换为灰度:

 cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
,

经过多次反复试验,我找到了解决方案。这就是帮助我解决问题的原因-

from PIL import Image

# Create an empty text file before this step
with open('image_array.txt','w') as outfile:
    for slice_2d in numpyimg:
        np.savetxt(outfile,slice_2d)

new_data = np.loadtxt('image_array.txt')

new_data=new_data.reshape((780,3))

img = Image.fromarray(new_data.astype(np.uint8),'RGB')
img.save('try.jpg')
img.show()

本文链接:https://www.f2er.com/170568.html

大家都在问