【问题标题】:imresize in PIL/scipy.misc only works for uint8 images? any alternatives?PIL/scipy.misc 中的 imresize 仅适用于 uint8 图像?有什么选择吗?
【发布时间】:2014-11-07 03:30:22
【问题描述】:

似乎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 图像。谢谢。

【问题讨论】:

  • 谢谢@cgohlke。这对我来说效果很好。您介意回答这个问题,以便我接受并结束这个问题吗?谢谢!

标签: python numpy scipy python-imaging-library pillow


【解决方案1】:

感谢 cgohlke 的评论。以下是我发现的两种适用于浮点数图像的替代方案。

  1. 使用scipy.ndimage.interpolation.zoom

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

对于 3 通道图像: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))

这适用于单通道和 3 通道图像。请注意,需要在第二个参数中恢复形状顺序。

【讨论】:

  • cv2.resize 建议很好,因为它允许以像素为单位精确指定高度和宽度。
【解决方案2】:

您也可以在 imresize 函数中使用 mode='F' 选项

imresize(image, factor, mode='F')

【讨论】:

  • 你能解释一下mode as F 的设置吗?
  • 在调整大小之前将 32bit 转换为 8bit。
【解决方案3】:

谈到性能以补充 Ying Xiong 总结并基于数组为 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

【讨论】:

    猜你喜欢
    • 2020-07-22
    • 2019-10-05
    • 2020-01-07
    • 1970-01-01
    • 1970-01-01
    • 2012-02-23
    • 2012-07-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多