python pyinsane脚本失败

Posted

技术标签:

【中文标题】python pyinsane脚本失败【英文标题】:python pyinsane script fails 【发布时间】:2015-09-18 04:40:15 【问题描述】:

我需要一些关于 python 脚本的帮助。该脚本是 Python Pyinsane 模块的示例脚本。 (平桑https://github.com/jflesch/pyinsane) 我想编写自己的扫描仪脚本,但要做到这一点,我应该了解示例代码或输出错误。

示例脚本。

import sys

``from PIL import Image

try:
   import src.abstract as pyinsane
except ImportError:
   import pyinsane.abstract as pyinsane


def set_scanner_opt(scanner, opt, value):
   print("Setting %s to %s" % (opt, str(value)))
   try:
       scanner.options[opt].value = value
   except (KeyError, pyinsane.SaneException) as exc:
       print("Failed to set %s to %s: %s" % (opt, str(value), str(exc)))


if __name__ == "__main__":
   steps = False

   args = sys.argv[1:]
   if len(args) <= 0 or args[0] == "-h" or args[0] == "--help":
       print("Syntax:")
       print("  %s [-s] <output file (JPG)>" % sys.argv[0])
       print("")
       print("Options:")
       print("  -s : Generate intermediate images (may generate a lot of"
             " images !)")
       sys.exit(1)

   for arg in args[:]:
       if arg == "-s":
           steps = True
           args.remove(arg)

   output_file = args[0]
   print("Output file: %s" % output_file)

   print("Looking for scanners ...")
   devices = pyinsane.get_devices()
   if (len(devices) <= 0):
       print("No scanner detected !")
       sys.exit(1)
   print("Devices detected:")
   print("- " + "\n- ".join([str(d) for d in devices]))

   print("")

   device = devices[0]
   print("Will use: %s" % str(device))

   print("")

   source = 'Auto'

   if (device.options['source'].constraint_type
           == pyinsane.SaneConstraintType.STRING_LIST):
       if 'Auto' in device.options['source'].constraint:
           source = 'Auto'
       elif 'FlatBed' in device.options['source'].constraint:
           source = 'FlatBed'
   else:
       print("Warning: Unknown constraint type on the source: %d"
             % device.options['source'].constraint_type)

   set_scanner_opt(device, 'resolution', 300)
   set_scanner_opt(device, 'source', source)
   set_scanner_opt(device, 'mode', 'Color')

   print("")

   print("Scanning ...  ")
   scan_session = device.scan(multiple=False)

   if steps and scan_session.scan.expected_size[1] < 0:
       print("Warning: requested step by step scan images, but"
             " scanner didn't report the expected number of lines"
             " in the final image --> can't do")
       print("Step by step scan images won't be recorded")
       steps = False

   if steps:
       last_line = 0
       expected_size = scan_session.scan.expected_size
       img = Image.new("RGB", expected_size, "#ff00ff")
       sp = output_file.split(".")
       steps_filename = (".".join(sp[:-1]), sp[-1])

   try:
       PROGRESSION_INDICATOR = ['|', '/', '-', '\\']
       i = -1
       while True:
           i += 1
           i %= len(PROGRESSION_INDICATOR)
           sys.stdout.write("\b%s" % PROGRESSION_INDICATOR[i])
           sys.stdout.flush()

           scan_session.scan.read()

           if steps:
               next_line = scan_session.scan.available_lines[1]
               if (next_line > last_line):
                   subimg = scan_session.scan.get_image(last_line, next_line)
                   img.paste(subimg, (0, last_line))
                   img.save("%s-%05d.%s" % (steps_filename[0], last_line,
                                        steps_filename[1]), "JPEG")
               last_line = next_line
   except EOFError:
       pass

   print("\b ")
   print("Writing output file ...")
   img = scan_session.images[0]
   img.save(output_file, "JPEG")
   print("Done")

现在的输出:

sudo python /home/pi/Desktop/scantest.py -s 1
Output file: 1
Looking for scanners ...
Devices detected:
- Scanner 'genesys:libusb:001:006' (Canon, LiDE 110, flatbed scanner)

Will use: Scanner 'genesys:libusb:001:006' (Canon, LiDE 110, flatbed scanner)

Setting resolution to 300
Setting source to Auto
Failed to set source to Auto: <class 'pyinsane.rawapi.SaneStatus'> : Data is       invalid (4)
Setting mode to Color

Scanning ...  
|Traceback (most recent call last):
  File "/home/pi/Desktop/scantest.py", line 107, in <module>
    steps_filename[1]), "JPEG")
  File "/usr/local/lib/python2.7/dist-packages/PIL/Image.py", line 1439, in save
    save_handler(self, fp, filename)
  File "/usr/local/lib/python2.7/dist-packages/PIL/PngImagePlugin.py", line 572, in _save
    ImageFile._save(im, _idat(fp, chunk), [("zip", (0,0)+im.size, 0, rawmode)])
  File "/usr/local/lib/python2.7/dist-packages/PIL/ImageFile.py", line 481, in _save
    e = Image._getencoder(im.mode, e, a, im.encoderconfig)
   File "/usr/local/lib/python2.7/dist-packages/PIL/Image.py", line 399, in  _getencoder
    return apply(encoder, (mode,) + args + extra)
 TypeError: an integer is required

请任何人解释示例代码或帮助我解决输出错误吗?

非常感谢

月桂酸

【问题讨论】:

【参考方案1】:

您的 PIL/Pillow 库编译时是否支持 JPEG? 如果没有,请尝试替换:

img.save("%s-%05d.%s" % (steps_filename[0], last_line,
                                    steps_filename[1]), "JPEG")

通过

img.save("%s-%05d.%s" % (steps_filename[0], last_line,
                                    steps_filename[1]), "PNG")

img.save(output_file, "JPEG")

通过

img.save(output_file, "PNG")

【讨论】:

以上是关于python pyinsane脚本失败的主要内容,如果未能解决你的问题,请参考以下文章

试图在AWS Lambda上运行python脚本,但是如果加载virtualenv目录,Lambda会失败

Xcode Bot 预集成触发期间 Python 脚本失败

当 python 脚本中发生故障时,管道不会失败

jenkins构建python测试脚本失败

导入matplotlib的python脚本成功但脚本的冻结二进制文件失败

当我从 SQL Server 代理运行 Python 脚本时,为啥它会失败?