首页 > 解决方案 > 创建 32 位图像并保存为 tif

问题描述

这是一个非常基本的问题,但我似乎没有找到一个好的解决方案。我想创建一个尺寸为 244 X 244 的黑色(全零)32 位图像并将其保存为 tif。我尝试了一些像 PIL 这样的模块,但我得到的只是一个单通道 RGB 图像。有什么建议么?有链接吗?如果问题太基本,感谢您的帮助和道歉!

标签: python-3.xmatplotlibpython-imaging-librarytiff

解决方案


希望这会有所帮助:

#!/usr/local/bin/python3
import numpy as np
from PIL import Image

# Numpy array containing 244x244 solid black image
solidBlackImage=np.zeros([244,244,3],dtype=np.uint8)

img=Image.fromarray(solidBlackImage,mode="RGB")
img.save("result.tif")

我得到的图像可以使用ImageMagick进行如下检查,并且可以看到是 24 位图像:

identify -verbose result.tif | more

输出

Image: result.tif
  Format: TIFF (Tagged Image File Format)
  Mime type: image/tiff
  Class: DirectClass
  Geometry: 244x244+0+0
  Units: PixelsPerInch
  Colorspace: sRGB
  Type: Bilevel
  Base type: TrueColor
  Endianess: LSB
  Depth: 8/1-bit
  Channel depth:
    Red: 1-bit
    Green: 1-bit
    Blue: 1-bit
    ...
    ...

或者,您可以使用以下方法进行验证tiffinfo

tiffinfo result.tif 

输出

TIFF Directory at offset 0x8 (8)
  Image Width: 244 Image Length: 244
  Bits/Sample: 8
  Compression Scheme: None
  Photometric Interpretation: RGB color
  Samples/Pixel: 3
  Rows/Strip: 244
  Planar Configuration: single image plane

另一个选项可能pyvips如下,我也可以指定 LZW 压缩:

#!/usr/local/bin/python3
import numpy as np
import pyvips

width,height,bands=244,244,3

# Numpy array containing 244x244 solid black image
solidBlackImage=np.zeros([height,width,bands],dtype=np.uint8)

# Convert numpy to vips image and save with LZW compression
vi = pyvips.Image.new_from_memory(solidBlackImage.ravel(), width, height, bands,'uchar')
vi.write_to_file('result.tif',compression='lzw')

结果是:

tiffinfo result.tif 

输出

TIFF Directory at offset 0x3ee (1006)
  Image Width: 244 Image Length: 244
  Resolution: 10, 10 pixels/cm
  Bits/Sample: 8
  Sample Format: unsigned integer
  Compression Scheme: LZW
  Photometric Interpretation: RGB color
  Orientation: row 0 top, col 0 lhs
  Samples/Pixel: 3
  Rows/Strip: 128
  Planar Configuration: single image plane
  Predictor: horizontal differencing 2 (0x2)

推荐阅读