【问题标题】:Python reading Large png files degrades, reduces qualityPython读取大png文件会降级,降低质量
【发布时间】:2016-07-04 15:41:07
【问题描述】:

我在 python 中尝试了很多方法来读取、打开和保存 PNG 文件以复制原始数组数据以进行进一步的图像处理,其中一些大小为 40 mb。但是在图像的读取过程中,图像本身会退化,在此过程中会降低质量和尺寸。所以我不能再使用该数据数组进行进一步操作[例如。过滤]和进一步收集数据[例如。 psnr, entropy] 因为读取的不再是原始图像。

使用 Pil。

from PIL import Image 

i = Image.open('shoes.png') 
i.show()

Original Image| note I saved it in jpeg but the quality looks like it. 40 mb in png format

Opened image from "i.show", 18.1 mb in png format

与 python CV 相同

import cv2
img = cv2.imread('shoes.png' ) 

它会产生蓝色的图像。

所以我不明白。这些库是否对需要多大的图像有限制?因为我尝试使用 PNG 格式来确保不损失图像质量,但是在读取图像的过程中,它会降低过程中的质量。

您能否回答有关此问题的问题,或者您能否提出一种更好的方法来获取 numpy 数组、大型原始图像或 PNG 图像的数据,而不会在读取文件和保存文件期间降低图像质量。

注意:另外,当我尝试在较小的图像文件上使用 PIL 代码时,它根本不会降低图像质量。

【问题讨论】:

  • "...在读取图像的过程中,图像本身会退化,在此过程中会降低质量和尺寸。" 您能否向我们展示这方面的证据?图像在什么时候退化了?
  • 当你使用PIL代码i = Image.open('shoes.png')时,i.modei.size是什么?
  • @WarrenWeckesser。 imgSize = (4608, 3072) imgmode= RGB。但正如你可以看到我在上面发布的图片。图像的对比度下降。文件大小从 40mb 到 18mb
  • 您链接到的图像是 JPEG 文件,因此它们不会告诉我们有关原始 PNG 文件质量的任何信息。 (JPEG 是“有损的”——它的压缩算法会丢失细节。)

标签: python image opencv numpy png


【解决方案1】:

我认为问题不在于处理大型 PNG 文件。这是一个脚本,它生成一个与图像大小相同的数组,将其保存为 PNG 文件,然后使用PIL/Pillow 将其读回。输出显示在脚本之后。结果是从文件中读取的数据和原来的数组是一样的。

要将 numpy 数组写入文件,我使用了我编写的名为 numpngw 的库。除了numpngw,你也可以使用PIL/Pillow 或PyPNG

from __future__ import print_function

import numpy as np
from numpngw import write_png
from PIL import Image


# For reproducibility...
np.random.seed(123)

# Generate random data to use for the image.
data = np.random.randint(0, 255, size=(3072, 4608, 3)).astype(np.uint8)
# Put a small white block in the corner
data[:3, :3, :] = 255

# Take a look at the red channel of a small subset of the image.
print(data[:4, :12, 0])

# Write the array to a PNG file.  I use numpngw.write_png; PIL and PyPNG
# are alternatives that could be used.
write_png("foo.png", data)

# Open the file using PIL (actually Pillow) and create a numpy
# array containing the image.
img = Image.open("foo.png")
a = np.array(img)

# Take a look at the red channel of a small subset of array.  It should
# be the same as the previous output.
print()
print(a[:4, :12, 0])

compare_str = "equal" if np.all(data == a) else "not equal"
print("\nRound-trip result: the arrays are %s." % compare_str)

输出:

[[255 255 255 106 214 113  73 224  83 164  68 195]
 [255 255 255 130  99  75  35 158 126 153 133 135]
 [255 255 255 152  79  15   7 101 175  68  45  71]
 [106 254  55  97 238  15  85 243  81 249  77  86]]

[[255 255 255 106 214 113  73 224  83 164  68 195]
 [255 255 255 130  99  75  35 158 126 153 133 135]
 [255 255 255 152  79  15   7 101 175  68  45  71]
 [106 254  55  97 238  15  85 243  81 249  77  86]]

Round-trip result: the arrays are equal.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-23
    • 2017-08-03
    • 1970-01-01
    相关资源
    最近更新 更多