python - Pillow :使用 Draw.rectangle 的奇怪行为

标签 python python-2.7 python-imaging-library pillow

我正在使用 Pillow 在 for 循环中绘制矩形。这在我的台式电脑上有效,但在我的笔记本电脑上抛出了一个奇怪的异常。

这是代码(缩写):

from PIL import Image, ImageDraw
(...)
img = Image.open(sys.argv[1])
rimg = img.copy()
rimg_draw = ImageDraw.Draw(rimg)
(...)
(for-loop)
    rimg_draw.rectangle((x1, y1, x2, y2), fill=None, outline=(255, 0, 0))

这会引发以下异常:

rimg_draw.rectangle((x1, y1, x2, y2), fill=None, outline=(255, 0, 0))
  File "/home/daniel/tensorflow2.7/lib/python2.7/site-packages/PIL/ImageDraw.py", line 203, in rectangle
    ink, fill = self._getink(outline, fill)
  File "/home/daniel/tensorflow2.7/lib/python2.7/site-packages/PIL/ImageDraw.py", line 124, in _getink
    ink = self.draw.draw_ink(ink, self.mode)
TypeError: function takes exactly 1 argument (3 given)

我不明白,为什么这段代码会失败:在 Pillow's very own documentation PIL.ImageDraw.Draw.rectangle 使用这些参数定义:rectangle(xy, fill=None, outline=None)

既然文档明确列出了可选参数 filloutline,为什么 Pillow 提示它只需要 1 个参数?

pip freeze 表示 Pillows 版本为 3.3.1

最佳答案

如果您读取一张灰度图像并尝试在其上绘制一个彩色矩形,您将收到错误消息:TypeError: function takes exactly 1参数(给定 3)

您需要提供像 outline=(255) 这样的颜色,而不是像 outline=(255, 0, 0) 这样的 RGB 颜色。否则你会得到错误,因为你给出了 3 个颜色参数,而不是一个。如果您确实想在灰度图像上绘制颜色,您可以先将图像转换为 RGB:img = img.convert('RGB')

编辑:由于许多其他人也遇到了这个问题,我向 Pillow 提交了一个错误,他们立即 made a fix .所以这个问题和答案有望很快过时。

关于python - Pillow :使用 Draw.rectangle 的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39080087/

相关文章:

python - 根据列表过滤文件夹中的特定文件

python - pandas如何忽略无法转换为日期时间以计算时间增量的列单元格

python - 用 numpy 连接数组的元素?

python-2.7 - Pandas:将 'crop' 作为大型数据帧仅存储到前 1000 天的最佳方法是什么?

django - 如何在django中创建views.py的下载为excel选项

python-3.4 - pip 无法在 Windows 7 上安装 Image 或 Pillow 库

python - 使用更新的 Python 2.6.2 在 Snow Leopard 上安装 Python Imaging Library (PIL)

python - 来自守护进程 : OCI runtime create failed: container_linux. 的错误响应 go:380:启动容器进程导致:exec: "python":

mysql - 使用python从excel表将数据插入mysql表时出错

python - PIL Image.open 和 cv2.imdecode 的区别