将PIL图像转换为VIPS图像

时间:2017-02-21 16:47:24

标签: python-imaging-library bytesio vips

我正在使用Vips图像库处理一些大的组织学图像。与图像一起,我有一个带坐标的数组。我想制作一个二进制掩码,它掩盖由坐标创建的多边形内的图像部分。我首先尝试使用vips绘制函数来做到这一点,但这是非常低效的并且需要永远(在我的实际代码中,图像大约是100000 x 100000px并且多边形数组非常大)。

然后我尝试使用PIL创建二进制掩码,这很有用。我的问题是将PIL图像转换为vips图像。它们都必须是vips图像才能使用multiply-command。我也想写内存,因为我相信这比写入磁盘更快。

im_PIL.save(memory_area,'TIFF')命令中我必须指定和图像格式,但由于我正在创建一个新图像,我不知道该放在这里。

Vips.Image.new_from_memory(..)命令返回:TypeError: constructor returned NULL

from gi.overrides import Vips
from PIL import Image, ImageDraw
import io

# Load the image into a Vips-image
im_vips = Vips.Image.new_from_file('images/image.tif')

# Coordinates for my mask
polygon_array = [(368, 116), (247, 174), (329, 222), (475, 129), (368, 116)]

# Making a new PIL image of only 1's
im_PIL = Image.new('L', (im_vips.width, im_vips.height), 1)

# Draw polygon to the PIL image filling the polygon area with 0's
ImageDraw.Draw(im_PIL).polygon(polygon_array, outline=1, fill=0)

# Write the PIL image to memory ??
memory_area = io.BytesIO()
im_PIL.save(memory_area,'TIFF')
memory_area.seek(0)

# Read the PIL image from memory into a Vips-image
im_mask_from_memory = Vips.Image.new_from_memory(memory_area.getvalue(), im_vips.width, im_vips.height, im_vips.bands, im_vips.format)

# Close the memory buffer ?
memory_area.close()

# Apply the mask with the image
im_finished = im_vips.multiply(im_mask_from_memory)

# Save image
im_finished.tiffsave('mask.tif')

0 个答案:

没有答案
相关问题