【问题标题】:Problem in how to do image processing for some images - Error: AttributeError: type object 'Image' has no attribute 'open如何对某些图像进行图像处理的问题 - 错误:AttributeError:类型对象'Image'没有属性'open
【发布时间】:2020-09-11 16:05:23
【问题描述】:

使用 python 对某些图像执行图像处理时出现错误。错误是:

"AttributeError: type object 'Image' has no attribute 'open'".

如果您能查看下面的代码并帮助我修复此错误,我会很高兴。

#imprint text on image 

from PIL import Image

from PIL import ImageFont

from PIL import ImageDraw

from IPython.display import Image

list2 = ['mydata/marketst670503.jpg','mydata/marketst8407.jpg','mydata/potsdamriot6805.jpg','mydata/rescue671221a.jpg']

outfile = 'sample-text.jpg'


for line in list2:

    print (line)

    img = Image.open(line)

    draw = ImageDraw.Draw(img)

    # font = ImageFont.truetype(<font-file>, <font-size>)

    font = ImageFont.truetype("Colombia.ttf", 200)

    draw.text((0, 0),"Sample Text",(255,0,0),font=font)

    img.save(outfile)

    display(Image(filename=outfile))
    

【问题讨论】:

  • 您正在导入两个具有相同名称的模块“from IPython.display import Image”、“from PIL import Image”,这可能会导致问题。

标签: python image-processing


【解决方案1】:

注意!您在 THE SAME NAME 下有 2 个导入,相互覆盖。 我会做出这样的改变:

#mabe you replace the original import to a more nutral name..
import PIL.Image as Image

from PIL import ImageFont

from PIL import ImageDraw

from IPython.display import Image as DisplayImage # this line fixes your problem

list2 = ['mydata/marketst670503.jpg','mydata/marketst8407.jpg','mydata/potsdamriot6805.jpg','mydata/rescue671221a.jpg']

outfile = 'sample-text.jpg'

for line in list2:

    print (line)

    img = Image.open(line)

    draw = ImageDraw.Draw(img)

    # font = ImageFont.truetype(<font-file>, <font-size>)

    font = ImageFont.truetype("Colombia.ttf", 200)

    draw.text((0, 0),"Sample Text",(255,0,0),font=font)

    img.save(outfile)

    display(Image(filename=outfile))

下一次,不要迷惑自己!选择一个更自然的名称然后图像,并且不会有重复:)

*** 已编辑!***

【讨论】:

  • 运行代码后,我收到此错误“ImportError:无法导入名称“'DisplayImage'”。我试图安装“DisplayImage”包,但它不起作用。你有想知道如何解决这个错误?
  • @Elwakdy 我认为您应该执行“从 IPython.display 导入图像作为 DisplayImage”,然后使用 DisplayImage(filename...) 而不是 display(Image(filename...)))。因为我认为模块没有 DisplayImage 方法。至少我在文档中找不到它
  • 嘿,我犯了一个愚蠢的错误,谢谢!请注意编辑,我希望您导入图像,并使用“as”关键字将其命名为 DisplayImage。现在,每次您想使用来自 Ipython.Display 库的图像时,请使用此名称。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-16
  • 1970-01-01
  • 1970-01-01
  • 2021-05-29
  • 1970-01-01
  • 2020-11-29
  • 1970-01-01
相关资源
最近更新 更多