【问题标题】:Load Image using PIL module使用 PIL 模块加载图像
【发布时间】:2020-03-19 07:47:34
【问题描述】:

我正在做一个增强图像对比度的问题。 请看下面这段代码

# this is a test cell
@exit_after(4)
def testContrastSharpening():
    # load an image
    i0 = loadImage('Data/bokehCircular.jpg', 100)

    # run student code
    s0 = contrastSharpen(i0, 3, 0.5)

    # collect test data
    rTest = s0[:, int(i0.shape[1]/2), 0]
    gTest = s0[:, int(i0.shape[1]/4), 1]
    bTest = s0[int(i0.shape[0]/5), :, 2]

    # load and compare to reference result
    l0 = load('Data/t0.npz')

    return allclose(rTest, l0['r']) and allclose(gTest, l0['g']) and allclose(bTest, l0['b'])

try:
    assert(testContrastSharpening())
    print('Contrast sharpening seems to work!')
except:
    raise Exception("Contrast sharpening is not working... please try again...")

i0 = loadImage('Data/bokehCircular.jpg', 100) 这行代码调用预先编写的函数来加载图像,该函数在下面给出

def loadImage(path, scale):
    image = Image.open(path, mode = 'r')
    image = image.resize((int(image.width * scale / 100), int(image.height * scale / 100)), resample=Image.LANCZOS)
    image = array(image.getdata()).reshape(image.size[1], image.size[0], 3)
    image = image.astype(float)
    image = image / max(image)

    return image

当我运行代码时,以下行出现错误 image = image.astype(float) 错误如下所示

KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-8-bf381c328e33> in <module>
     20 try:
---> 21     assert(testContrastSharpening())
     22     print('Contrast sharpening seems to work!')

<ipython-input-1-4c3172e491d3> in inner(*args, **kwargs)
     44             try:
---> 45                 result = fn(*args, **kwargs)
     46             finally:

<ipython-input-8-bf381c328e33> in testContrastSharpening()
      4     # load an image
----> 5     i0 = loadImage('Data/bokehCircular.jpg', 100)
      6 

<ipython-input-3-545d6e0c0f38> in loadImage(path, scale)
      5     image = array(image.getdata()).reshape(image.size[1], image.size[0], 3)
----> 6     image = image.astype(float)
      7     image = image / max(image)

KeyboardInterrupt:

我已经编写了增强图像对比度的代码,我已经通过相同的 LoadImage 函数加载图像来单独测试它,但在上述情况下,LoadImage 函数无法正常工作 请帮忙,如果有人可以,谢谢

【问题讨论】:

  • 错误是KeyboardInterrupt 错误,这意味着您确实故意停止了脚本?
  • 我没有碰任何东西,我没有故意停止脚本,每次都会出现同样的错误
  • 这个装饰器@exit_after(4) 是什么意思?它不会在 4 秒后停止吗?也许尝试提高它?
  • 不幸的是,这是一个测试单元,我无法编辑它,可能我必须创建另一个 ipynb
  • exit after也是一个被调用的函数

标签: python-3.x python-imaging-library loadimage


【解决方案1】:

我认为这是因为你的装饰器@exit_after(4)。实际上,在 4 秒后使用 @exit_after(4),您的测试单元将被 KeyboardInterrupt 错误停止。

来自@exit_after()的源码

def exit_after(s):
   '''
   use as decorator to exit process if 
   function takes longer than s seconds
   '''

有两种解决方案:

  • 修改测试:让您的测试更宽容并提高这个数字?例如@exit_after(10) 看看这是否有效。
  • 修改您的脚本:让您的函数更快,以便它们在 4 秒的限制下工作。您可以先让函数几乎为空,然后检查它是否有效。

【讨论】:

    猜你喜欢
    • 2011-05-05
    • 2016-10-04
    • 2021-02-17
    • 1970-01-01
    • 2012-05-14
    • 2016-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多