PIL/scipy.misc中的imresize仅适用于uint8图像吗?有其他替代方法吗?

5

看起来 PIL/scipy.misc 中实现的 imresize 仅适用于 uint8 图像。

>>> import scipy.misc
>>> im = np.random.rand(100,200)
>>> print im.dtype
float64

>>> im2 = scipy.misc.imresize(im, 0.5)
>>> print im2.dtype
uint8

有什么办法可以解决这个问题吗?我想处理HDR图像,因此需要处理float64float32图像。谢谢。


1
请尝试使用scipy.ndimage.interpolation.zoom函数。 - cgohlke
谢谢@cgohlke。对我来说,那个很有效。您介意回答一下这个问题吗?这样我就可以接受它并关闭问题了。谢谢! - Ying Xiong
3个回答

12

感谢cgohlke的评论。下面是我找到的两个适用于浮点数图像的替代方法。

  1. 使用scipy.ndimage.interpolation.zoom

对于单通道图像:im2 = scipy.ndimage.interpolation.zoom(im, 0.5)

对于三通道图像:im2 = scipy.ndimage.interpolation.zoom(im, (0.5, 0.5, 1.0))

  1. 使用OpenCV。

im2 = cv2.resize(im, (im.shape[1]/2, im.shape[0]/2))

这适用于单通道和三通道图像。请注意,第二个参数需要反转形状顺序。


1
cv2.resize建议很好,因为它允许以像素为单位精确指定高度和宽度。 - Jonathan

1
你可以在imresize函数中使用mode='F'选项。
imresize(image, factor, mode='F')

你能解释一下将 mode 设置为 F 的作用吗? - gokul_uf
在调整大小之前,它将32位转换为8位。 - Dmitry

0

谈到性能,为了补充英雄的总结并基于数组作为Numpy.array,其数据类型为intfloat,OpenCV速度更快

import numpy as np
import cv2
from timeit import Timer
from scipy.ndimage import zoom


def speedtest(cmd, N):
    timer = Timer(cmd, globals=globals())
    times = np.array(timer.repeat(repeat=N, number=1))
    print(f'Over {N} attempts, execution took:\n'
          f'{1e3 * times.min():.2f}ms at min\n'
          f'{1e3 * times.max():.2f}ms at max\n'
          f'{1e3 * times.mean():.2f}ms on average')

# My image is 2000x2000, let's try to resize it to 300x300
image_int = np.array(image, dtype= 'uint8')
image_float = np.array(image, dtype= 'float')

N_attempts = 100  # We run the speed test 100 times
speedtest("zoom(image_int, 300/2000)", N_attempts)
# Over 100 attempts, execution took:
# 120.84ms at min
# 135.09ms at max
# 124.50ms on average
speedtest("zoom(image_float, 300/2000)", N_attempts)
# Over 100 attempts, execution took
# 165.34ms at min
# 180.82ms at max
# 169.77ms on average
speedtest("cv2.resize(image_int, (300, 300))", N_attempts)
# Over 100 attempts, execution took
# 0.11ms at min
# 0.26ms at max
# 0.13ms on average
speedtest("cv2.resize(image_float, (300, 300))", N_attempts)
# Over 100 attempts, execution took
# 0.56ms at min
# 0.86ms at max
# 0.62ms on average

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接