【问题标题】:downsampling images as a function in Python将图像下采样为 Python 中的函数
【发布时间】:2013-05-22 15:26:06
【问题描述】:

我正在尝试将一些 tiff 文件从 2000*2000 重新采样到 500*500。 我创建了一个函数,我尝试了一个文件,它运行良好。现在我想将它应用于我拥有的所有可用文件。

我想编写函数的输出,并且我已经根据我的知识编写了代码,并且在写入 out_file 时收到错误。我已经复制了函数和主代码供您考虑。主要代码只是根据它们的命名读取tif文件并应用函数。如果 sb 能指出我的错误在哪里,我将不胜感激。

#*********function********************
 def ResampleImage(infile):

       fp = open(infile, "rb")
       p = ImageFile.Parser()

       while 1:
           s = fp.read()
           if not s:
               break
           p.feed(s)

      img = p.close()


      basewidth = 500
      wpercent = (basewidth / float(img.size[0]))
      hsize = int((float(img.size[1]) * float(wpercent)))
      outfile=img.resize((basewidth, hsize), PIL.Image.ANTIALIAS)

      return outfile

 #********* main code********

 import os,sys
 import ImageResizeF
 import PIL
 from PIL import Image
 from PIL import Image,ImageFile

 tpath = 'e:/.../resampling_test/all_tiles/'


 tifext = '.tif'
 east_start = 32511616
 north_start = 5400756
 ilist = range (0,14)
 jlist = range (0,11)

 north = north_start
 ee = ',4_'
 en = ',2'


 for i in ilist:              
    east = east_start
    north = north_start + i * 400
    snorth = str (north)

    for j in jlist:
       east = east_start + j * 400
       seast = str (east)      
       infile = tpath + seast + ee + snorth + en + tifext
       output = tpath + seast + ee + snorth + en + '_res'+tifext
       out_file = ImageResizeF.ResampleImage(infile)
       out_file.write (output)
       out_file.close ()   

【问题讨论】:

  • 您还应该发布 ImageResizeF 的代码
  • 你是真正的悬疑大师。您遇到的神秘错误是什么?
  • @elyase : ImageResizeF 文件是第一个函数
  • 错误是:无法写入文件

标签: python image-processing python-imaging-library tiff resampling


【解决方案1】:

您的错误可能与您从ImageResizeF.ResampleImage 返回的内容有关,它是文件句柄吗?否则你做错了,因为你不能 close() 不是文件句柄的东西。您应该在函数内部进行整个文件处理或返回一个图像对象,例如:

def process_image(image):
    "Processes the image"
    image.resize((x, y), Image.ANTIALIAS) # or whatever you are doing to the image
    return image

image = Image.open('infile.tiff')
proc_image = process_image(image)
proc_image.save('outfile.tiff')

【讨论】:

  • 非常感谢您的提示。你的问题是说'.save'。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-23
  • 2011-09-02
  • 1970-01-01
  • 1970-01-01
  • 2022-01-04
  • 2013-09-11
相关资源
最近更新 更多