python-3.x - 创建 32 位图像并保存为 tif
问题描述
这是一个非常基本的问题,但我似乎没有找到一个好的解决方案。我想创建一个尺寸为 244 X 244 的黑色(全零)32 位图像并将其保存为 tif。我尝试了一些像 PIL 这样的模块,但我得到的只是一个单通道 RGB 图像。有什么建议么?有链接吗?如果问题太基本,感谢您的帮助和道歉!
解决方案
希望这会有所帮助:
#!/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)
推荐阅读
- testing - 如何在 Go 中查看或测试优雅重启?
- ios - RxDataSources 和改变模型的能力
- vba - 使用 Excel 宏创建资产列表
- nginx - NginX GeoIP 模块配置 - Conf 的第一行不允许 load_module
- angular - 使用Angular 6单击卡片时如何获取数据?
- c# - 如何剪切字符串的第一部分并存储它
- c# - 如何在 C# 中检测给定文件是否是有效的 .docx 而不仅仅是重命名为 .docx 的 .zip?
- angular - Angular Reactive 表单的 formArrays 未按预期绑定
- python - TypeError: 'module' object is not callable error with driver=webdriver("C:\\Python34\\Lib\\site-packages\\selenium\\webdriver\\chromedriver.exe")
- php - 类 stdClass 的对象无法转换为 int Laravel 5.6