python如何精确保存读取到的图片像素

我尝试用opencv、PIL、matplotlib.pyplot读取图片像素,将读取到的像素矩阵保存为图片,再读取时发现像素值有出入,如何精确地保存矩阵为图片呢?

​from typing import Counter

import numpy as np

from PIL import Image

cc = Image.open('ccc.jpg') #打开同目录下的ccc.jpg图片
np.array(cc)
print(type(cc))
cc = np.array(cc)
print(type(cc))
print(cc.shape)
print(cc.dtype)
print(Counter(cc.flatten()))
cc = Image.fromarray(cc)
print(type(cc))
cc.save('cccc.jpg')

cc = Image.open('cccc.jpg')
print(type(cc))
cc = np.array(cc)
print(type(cc))
print(cc.shape)
print(cc.dtype)
print(Counter(cc.flatten()))

import matplotlib.pyplot as plt

cc = plt.imread('ccc.jpg')
print(type(cc))
print(cc.shape)
print(Counter(cc.flatten()))
plt.figure(figsize=(30,40),dpi=1)
plt.gca().xaxis.set_major_locator(plt.NullLocator())
plt.gca().yaxis.set_major_locator(plt.NullLocator())
plt.subplots_adjust(top=1,bottom=0,left=0,right=1,hspace =0,wspace =0)
plt.margins(0,0)
plt.imshow(cc)
plt.axis('off')
plt.savefig('cccc.jpg')

cc = plt.imread('cccc.jpg')
print(type(cc))
print(cc.shape)
print(Counter(cc.flatten()))

import cv2
cc = cv2.imread('ccc.jpg')
print(type(cc))
print(cc.shape)
print(Counter(cc.flatten()))

cv2.imwrite('cccc.jpg', cc)
cc = cv2.imread('cccc.jpg')
print(type(cc))
print(cc.shape)
print(Counter(cc.flatten()))​

 

你是说图片占用空间大小变了吧?因为你保存jpg图片会做压缩处理,所以图片的大小会变了。

JPEG做了一件事,就是把这些8x8的小块进行了一个正交变换(离散余弦,DCT变换)。经过变换之后,很多元素会接近0。我们把这些比较小的数值强制设定为0,只保留少量较大的数值,那么需要存储的元素将大大减少。例如原来需要保存64个元素,现在可能只需要保存6个元素,那么文件大小就会显著下降。
这个过程,并没有对图像的分辨率进行处理,所以不会影响图像的分辨率。

建议参考:https://www.zhihu.com/question/25554419/answer/31917806

希望对你有帮助,如有帮助,望采纳,谢谢

您的问题已经有小伙伴解答了,请点击【采纳】按钮,采纳帮您提供解决思路的答案,给回答的人一些鼓励哦~~

ps:开通问答VIP,享受5次/月 有问必答服务,了解详情↓↓↓

【电脑端】戳>>>  https://vip.csdn.net/askvip?utm_source=1146287632
【APP 】  戳>>>  https://mall.csdn.net/item/52471?utm_source=1146287632