枕头:控制JPEG压缩的TIFF的质量和子采样

2024-05-29 11:35:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我用枕头来制作多页的TIFF。我想用JPEG压缩层,我可以用compression选项:https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html#saving-tiff-images

我还想指定压缩质量和色度子采样模型,这两个模型都可用于JPEG插件:https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html#jpeg

这可以用TIFF writer插件实现吗?在

谢谢。在


Tags: httpsio模型image插件htmlreadthedocsfile
2条回答

我做了一些实验:

from PIL import Image
import numpy as np
import PIL.TiffImagePlugin as tiff

# Turn on debugging for some insights
TiffImagePlugin.DEBUG = True

# Create Numpy random image and make PIL Image from it
randImage= np.random.randint(0,256,(480,640,3), dtype=np.uint8)
i = Image.fromarray(randImage)

# Save with JPEG compression and file is smaller and "tiffdump" agrees it is JPEG encoded
# NOTE: It is "jpeg", not "tiff_jpeg" like the docs say
i.save("result.tif",compression="jpeg")

# Try and modify settings
import PIL.TiffImagePlugin as tiff

# Set some tags and see if they are saved
ifd=tiff.ImageFileDirectory_v2()
ifd[315]="Funky 315"
ifd[316]="Funky 316"

# I tried setting the YCbCrChromaSubSampling here but it makes no difference - maybe I did it wrong!
# It gets reported differently from how I expect when examined with "tiffdump"
# ifd[530]=0x10001

i.save("result.tif",compression="jpeg",tiffinfo=ifd)  

检查tiffdump

^{pr2}$

我还用libvips做了一些实验,并且能够编写质量可控的JPEG压缩tiff,如下所示:

import numpy as np
import pyvips

# Set width, height and number of bands of image
h, w, bands = 480, 640, 3

# Initialise Numpy image and convert to VipsImage
n = np.random.randint(0,256,(h,w,bands), dtype=np.uint8)
linear = n.reshape(h*w*bands)
vi = pyvips.Image.new_from_memory(linear.data, w, h, bands,'uchar')

# Now save without compression, then with JPEG compression quality=60, 80, 90
vi.tiffsave('result-none.tif')
vi.tiffsave('result-60.tif', compression='jpeg', Q=60)
vi.tiffsave('result-80.tif', compression='jpeg', Q=80)
vi.tiffsave('result-90.tif', compression='jpeg', Q=90)

检查尺寸对应:

^{pr2}$

tiffinfo命令也会发现JPEG压缩:

tiffinfo result-60.tif

TIFF Directory at offset 0x237de (145374)
  Image Width: 640 Image Length: 480
  Resolution: 10, 10 pixels/cm
  Bits/Sample: 8
  Sample Format: unsigned integer
  Compression Scheme: JPEG
  Photometric Interpretation: YCbCr
  Orientation: row 0 top, col 0 lhs
  Samples/Pixel: 3
  Rows/Strip: 128
  Planar Configuration: single image plane
  Reference Black/White:
     0:     0   255
     1:   128   255
     2:   128   255
  JPEG Tables: (574 bytes)

您可以看到如何从pyvips转换为numpy,然后再返回{a1}。在

同样,您可以使用以下方法从PIL Image转换为numpy

PILImage = Image.open('image.png')
numpyImage = np.array(PILImage)

numpy图像到{},其中:

PILImage = Image.fromarray(numpyImage)

这意味着你应该能够在PIL/Pillow、Numpy、scikit image、OpenCV和vips之间混合图像打开、关闭、处理。在

相关问题 更多 >

    热门问题