这是一个非常基本的问题,但我似乎没有找到一个好的解决方案。我想创建一个尺寸为244 X 244的黑色(全零)32位图像并将其保存为tif。我尝试了像PIL这样的模块,但我得到的只是单通道RGB图像。有什么建议?有链接吗? 如果问题太基础,感谢您的帮助和道歉!
答案 0 :(得分:2)
希望这会有所帮助:
#!/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)