def scan_cards(): pyinsane2.init() devices = pyinsane2.get_devices() try: device = devices[0] print(f'PyInsane2 initiatied using {device.name}.') # device.options['AutoDocumentSize'] # Specify color scanning pyinsane2.set_scanner_opt(device, 'mode', ['24bit Color[Fast]']) # Set scan resolution pyinsane2.set_scanner_opt(device, 'resolution', [200]) pyinsane2.maximize_scan_area(device) try: pyinsane2.set_scanner_opt( device, 'source', ['Automatic Document Feeder(center aligned,Duplex)']) except pyinsane2.PyinsaneException as e: print('No document feeder found', e) try: scan_session = device.scan(multiple=True) print("Scanning ...") while True: try: scan_session.scan.read() except EOFError: print('scanning page') except StopIteration: im_list = scan_session.images pyinsane2.exit() return im_list except: pyinsane2.exit()
def getImageFromScanner(): try: import pyinsane2 except: print "Scanning feature not supported on this OS. Disabling it..." pyinsane2.init() try: devices = pyinsane2.get_devices() assert (len(devices) > 0) device = devices[0] print("I'm going to use the following scanner: %s" % (str(device))) pyinsane2.set_scanner_opt(device, 'resolution', [75]) # Beware: Some scanners have "Lineart" or "Gray" as default mode # better set the mode everytime # Beware: by default, some scanners only scan part of the area # they could scan. pyinsane2.maximize_scan_area(device) scan_session = device.scan(multiple=False) try: while True: scan_session.scan.read() except EOFError: pass finally: image = scan_session.images[-1] return image finally: pyinsane2.exit() return None
def scan(): devices = pyinsane2.get_devices() if (len(devices) <= 0): wx.MessageBox('Scanner device not found', 'Error', wx.OK | wx.ICON_WARNING) sys.exit(1) device = devices[0] #pyinsane2.set_scanner_opt(device, 'source', ['Auto', 'FlatBed']) pyinsane2.set_scanner_opt(device, 'resolution', [300]) try: pyinsane2.maximize_scan_area(device) except Exception as exc: print("Failed to maximize scan area: {}".format(exc)) pyinsane2.set_scanner_opt(device, 'mode', ['Color']) scan_session = device.scan(multiple=False) try: 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() except EOFError: print("Scan compleated!") FOLDER = os.getcwd() FOLDER_SCAN = os.path.join(FOLDER, '..', 'ui') os.chdir(FOLDER_SCAN) img = scan_session.images[0] img.save("KharkivPy19.jpg", "JPEG") os.chdir(FOLDER)
def run(self): temp_img_name = "1.png" temp_img_path = os.path.join(self.tempdir, temp_img_name) new_list = [] try: devices = pyinsane2.get_devices() if len(devices) <= 0: print("Scanning failed") self.scan_done.emit(None) return device = devices[0] print("Using scanner: %s" % (str(device))) pyinsane2.set_scanner_opt(device, "resolution", [300]) pyinsane2.set_scanner_opt(device, "mode", ["Color"]) pyinsane2.maximize_scan_area(device) # self.statusBar().showMessage("Scanning") scan_session = device.scan(multiple=False) try: while True: scan_session.scan.read() except EOFError: pass image = scan_session.images[-1] image.save(temp_img_path, "PNG") new_list.append(temp_img_path) self.scan_done.emit(new_list) finally: print("exiting")
def main(): device = selectDevice(pyinsane2.get_devices()) pyinsane2.maximize_scan_area(device) options = selectOptions(device.options.values()) applyOptions(device=device, options=options) print("will scan with following options:") for opt in device.options.values(): try: print(opt.name, opt.value) except pyinsane2.PyinsaneException as exc: pass filePath = selectFilePath() nameRoot = selectNameRoot() print("scanning will begin after you press <enter>") scan_count = 0 while True: _input = input("(<enter> or <q+enter>) ") if not _input: fileNumber = str(scan_count) fileNumber = "".join(['0'*(5-len(fileNumber)), fileNumber]) fileName = "".join([nameRoot, fileNumber, ".tif"]) print("Scanning ", fileName) image = scan(device) print("Done. Saving", fileName) saveImage(image, fileName, filePath) scan_count = scan_count + 1 continue if _input == "q": print("Exiting") break
def main(): import pyinsane2 pyinsane2.init() try: devices = pyinsane2.get_devices() assert(len(devices) > 0) device = devices[0] print("I'm going to use the following scanner: %s" % (str(device))) pyinsane2.set_scanner_opt(device, 'resolution', [300]) # Beware: Some scanners have "Lineart" or "Gray" as default mode # better set the mode everytime pyinsane2.set_scanner_opt(device, 'mode', ['Color']) # Beware: by default, some scanners only scan part of the area # they could scan. pyinsane2.maximize_scan_area(device) scan_session = device.scan(multiple=False) try: while True: scan_session.scan.read() except EOFError: pass image = scan_session.images[-1] image.save("output/"+str(datetime.datetime.now())+".png") finally: pyinsane2.exit()
def _get_scanner(config, devid, preferred_sources=None): logger.info("Will scan using %s" % str(devid)) resolution = config['scanner_resolution'].value logger.info("Will scan at a resolution of %d" % resolution) dev = pyinsane2.Scanner(name=devid) config_source = config['scanner_source'].value if 'source' not in dev.options: logger.warning( "Can't set the source on this scanner. Option not found") elif preferred_sources: pyinsane2.set_scanner_opt(dev, 'source', preferred_sources) elif config_source: pyinsane2.set_scanner_opt(dev, 'source', [config_source]) if 'resolution' not in dev.options: logger.warning("Can't set the resolution on this scanner." " Option not found") else: pyinsane2.set_scanner_opt(dev, 'resolution', [resolution]) if 'mode' not in dev.options: logger.warning("Can't set the mode on this scanner. Option not found") else: try: pyinsane2.set_scanner_opt(dev, 'mode', ['Color']) except pyinsane2.PyinsaneException as exc: logger.warning("Failed to set scan mode: {}".format(exc)) pyinsane2.maximize_scan_area(dev) return (dev, resolution)
def main(args): dstdir = args[0] devices = pyinsane2.get_devices() assert (len(devices) > 0) device = devices[0] print("Will use the scanner [%s](%s)" % (str(device), device.name)) pyinsane2.set_scanner_opt(device, "source", ["ADF", "Feeder"]) # Beware: Some scanner have "Lineart" or "Gray" as default mode pyinsane2.set_scanner_opt(device, "mode", ["Color"]) pyinsane2.set_scanner_opt(device, "resolution", [300]) pyinsane2.maximize_scan_area(device) # Note: If there is no page in the feeder, the behavior of device.scan() # is not guaranteed : It may raise StopIteration() immediately # or it may raise it when scan.read() is called try: scan_session = device.scan(multiple=True) print("Scanning ...") while True: try: scan_session.scan.read() except EOFError: print("Got page %d" % (len(scan_session.images))) img = scan_session.images[-1] imgpath = os.path.join(dstdir, "%d.jpg" % (len(scan_session.images))) img.save(imgpath) except StopIteration: print("Got %d pages" % len(scan_session.images))
def main(args): dstdir = args[0] devices = pyinsane2.get_devices() assert(len(devices) > 0) device = devices[0] print("Will use the scanner [%s](%s)" % (str(device), device.name)) pyinsane2.set_scanner_opt(device, "source", ["ADF", "Feeder"]) # Beware: Some scanner have "Lineart" or "Gray" as default mode pyinsane2.set_scanner_opt(device, "mode", ["Color"]) pyinsane2.set_scanner_opt(device, "resolution", [300]) pyinsane2.maximize_scan_area(device) # Note: If there is no page in the feeder, the behavior of device.scan() # is not guaranteed : It may raise StopIteration() immediately # or it may raise it when scan.read() is called try: scan_session = device.scan(multiple=True) print("Scanning ...") while True: try: scan_session.scan.read() except EOFError: print("Got page %d" % (len(scan_session.images))) img = scan_session.images[-1] imgpath = os.path.join(dstdir, "%d.jpg" % (len(scan_session.images))) img.save(imgpath) except StopIteration: print("Got %d pages" % len(scan_session.images))
def scanthread(self): self.countread =0 pyinsane2.init() try: devices = pyinsane2.get_devices() if len(devices) > 0 : assert(len(devices) > 0) device = devices[0] GLib.idle_add(self.showprogressbar) pyinsane2.set_scanner_opt(device, 'resolution', [300]) # Beware: Some scanners have "Lineart" or "Gray" as default mode # better set the mode everytime pyinsane2.set_scanner_opt(device, 'mode', ['Color']) # Beware: by default, some scanners only scan part of the area # they could scan. pyinsane2.maximize_scan_area(device) scan_session = device.scan(multiple=False) try: while True: scan_session.scan.read() GLib.idle_add(self.updatescanprogress) except EOFError: pass scannedimage = scan_session.images[-1] GLib.idle_add(self.closescanprogress) jsonFile = open('conf.json', 'r') conf = json.load(jsonFile) ws_dir = conf["workspace_dir"] filename = ws_dir +"/" + str(datetime.datetime.now()) global imgloc imgloc = filename scannedimage.save(filename,"JPEG") jsonFile.close() textviewinitial = builder.get_object("outputtextview") textviewinitial.get_buffer().set_text('') img = builder.get_object("previmage") img.set_from_file(imgloc) global skewcorrected skewcorrected = 0 global zoomout zoomout = 1 else: GLib.idle_add(self.nodeviceconnected) finally: pyinsane2.exit()
def com_hardware_scanner_scan(self, scanner_device, resolution, file_name): try: pyinsane2.set_scanner_opt( scanner_device, 'resolution', [resolution]) pyinsane2.set_scanner_opt(scanner_device, 'mode', ['Color']) pyinsane2.maximize_scan_area(scanner_device) scan_session = scanner_device.scan(multiple=False) try: while True: scan_session.scan.read() except EOFError: pass image = scan_session.images[-1] common_file.com_file_save_data(file_name, image) finally: pyinsane2.exit()
def _get_scanner(config, devid, preferred_sources=None): logger.info("Will scan using %s" % str(devid)) dev = pyinsane2.Scanner(name=devid) config_source = config['scanner_source'].value if 'source' not in dev.options: logger.warning("Can't set the source on this scanner." " Option not found") elif preferred_sources: pyinsane2.set_scanner_opt(dev, 'source', preferred_sources) elif config_source: pyinsane2.set_scanner_opt(dev, 'source', [config_source]) resolution = int(config['scanner_resolution'].value) logger.info("Will scan at a resolution of %d" % resolution) if 'resolution' not in dev.options: logger.warning("Can't set the resolution on this scanner." " Option not found") else: try: pyinsane2.set_scanner_opt(dev, 'resolution', [resolution]) except pyinsane2.PyinsaneException as exc: resolution = int(dev.options['resolution'].value) logger.warning("Failed to set resolution. Will fall back to the" " current one: {}".format(resolution)) logger.exception(exc) if 'mode' not in dev.options: logger.warning("Can't set the mode on this scanner. Option not found") else: try: pyinsane2.set_scanner_opt(dev, 'mode', ['Color']) except pyinsane2.PyinsaneException as exc: logger.warning("Failed to set scan mode: {}".format(exc)) logger.exception(exc) try: pyinsane2.maximize_scan_area(dev) except pyinsane2.PyinsaneException as exc: logger.warning("Failed to maximize scan area: {}".format(exc)) logger.exception(exc) return (dev, resolution)
def main(): parser = argparse.ArgumentParser() parser.add_argument("-o", "--output_name", default="scansione.jpg", help="string to search into") parser.add_argument("-r", "--resolution", default="150", help="string to search into") args = parser.parse_args() output_name = args.output_name resolution = args.resolution pyinsane2.init() try: devices = pyinsane2.get_devices() assert (len(devices) > 0) device = devices[0] print("I'm going to use the following scanner: %s" % (str(device))) pyinsane2.set_scanner_opt(device, 'resolution', [int(resolution)]) # Beware: Some scanners have "Lineart" or "Gray" as default mode # better set the mode everytime # pyinsane2.set_scanner_opt(device, 'mode', 'Gray') # Beware: by default, some scanners only scan part of the area # they could scan. pyinsane2.maximize_scan_area(device) scan_session = device.scan(multiple=False) try: while True: scan_session.scan.read() except EOFError: pass image = scan_session.images[-1] image.save(output_name, "JPEG") print("Done") finally: pyinsane2.exit()
def main(): import pyinsane2 pyinsane2.init() try: devices = pyinsane2.get_devices() assert (len(devices) > 0) device = devices[0] print("I'm going to use the following scanner: %s" % (str(device))) try: pyinsane2.set_scanner_opt(device, 'source', ['ADF', 'Feeder']) except PyinsaneException: print("No document feeder found") return # Beware: Some scanners have "Lineart" or "Gray" as default mode # better set the mode everytime pyinsane2.set_scanner_opt(device, 'mode', ['Color']) # Beware: by default, some scanners only scan part of the area # they could scan. pyinsane2.maximize_scan_area(device) scan_session = device.scan(multiple=True) try: while True: try: scan_session.scan.read() except EOFError: print("Got a page ! (current number of pages read: %d)" % (len(scan_session.images))) except StopIteration: print("Document feeder is now empty. Got %d pages" % len(scan_session.images)) for idx in range(0, len(scan_session.images)): image = scan_session.images[idx] image.save("output/" + str(datetime.datetime.now()) + ".png") finally: pyinsane2.exit()
def Scan(Device, Param): ''' This function makes use of the Pyinsane2 module and captures an image with the scanner. Input: --------------------- Device (pyinsane2.wia.abstract.Scanner): Selected scanner. Param (Dictionary): {'Brightness': Int, 'Contrast': int, 'Resolution': int} Returns: --------------------- Image **NOTE If you want to use this function by itself, you first must start pyinsane by running: pyinsane2.init() Device = pyinsane2.get_devices() ''' Device.options['brightness'].value = Param['Brightness'] Device.options['contrast'].value = Param['Contrast'] try: pyinsane2.set_scanner_opt(Device, 'resolution', [Param['Resolution']]) pyinsane2.set_scanner_opt(Device, 'mode', ['Color']) pyinsane2.maximize_scan_area(Device) scan_session = Device.scan(multiple=False) try: while True: scan_session.scan.read() except EOFError: pass Image = scan_session.images[-1] finally: pyinsane2.exit() return (Image)
def setup_device(device_name=None, resolution=300, mode="Gray"): pyinsane2.init() if device_name is not None: device = pyinsane2.Scanner(name="brother4:net1;dev0") else: devices = pyinsane2.get_devices() print("Scanners found:") for i, d in enumerate(devices): print(f"[{i}] {d}") device = devices[int(input("Select which one to use: "))] print(f"Will use: {device}") pyinsane2.set_scanner_opt(device, "source", ["Auto", "FlatBed"]) pyinsane2.set_scanner_opt(device, "resolution", [resolution]) try: pyinsane2.maximize_scan_area(device) except Exception as exc: print(f"Failed to maximize scan area: {exc}") pyinsane2.set_scanner_opt(device, "mode", [mode]) return device
def scan_document(self, filename): """ Scan a new document and save it as 'filename' possible resolutions are : 75, 100, 200, 300, 600, 1200 """ pyinsane2.init() try: devices = pyinsane2.get_devices() device = None if devices: device = devices[0] print("I'm going to use the following scanner: %s" % (str(device))) pyinsane2.set_scanner_opt(device, 'resolution', [75]) else: print( "Check if scanner is online, and you have the correct WIFI connection!" ) # Scan in color mode pyinsane2.set_scanner_opt(device, 'mode', ['Color']) pyinsane2.maximize_scan_area(device) scan_session = device.scan(multiple=False) try: print("Initiating Scan operation") while True: scan_session.scan.read() except EOFError: pass image = scan_session.images[-1] print("Saving image") image.save(filename) finally: pyinsane2.exit()
def main(): parser = argparse.ArgumentParser() parser.add_argument("-o", "--output_name", default="scansione.jpg", help="string to search into") parser.add_argument("-r", "--resolution", default="150", help="string to search into") args = parser.parse_args() output_name=args.output_name resolution=args.resolution pyinsane2.init() try: devices = pyinsane2.get_devices() assert(len(devices) > 0) device = devices[0] print("I'm going to use the following scanner: %s" % (str(device))) pyinsane2.set_scanner_opt(device, 'resolution', [int(resolution)]) # Beware: Some scanners have "Lineart" or "Gray" as default mode # better set the mode everytime # pyinsane2.set_scanner_opt(device, 'mode', 'Gray') # Beware: by default, some scanners only scan part of the area # they could scan. pyinsane2.maximize_scan_area(device) scan_session = device.scan(multiple=False) try: while True: scan_session.scan.read() except EOFError: pass image = scan_session.images[-1] image.save(output_name, "JPEG") print("Done") finally: pyinsane2.exit()
def _do(self): # find the best resolution : the default calibration resolution # is not always available resolutions = [x[1] for x in self.__resolutions_store] resolutions.sort() resolution = DEFAULT_CALIBRATION_RESOLUTION for nresolution in resolutions: if nresolution > DEFAULT_CALIBRATION_RESOLUTION: break resolution = nresolution logger.info("Will do the calibration scan with a resolution of %d" % resolution) # scan dev = pyinsane2.Scanner(name=self.__devid) if self.__source: if dev.options['source'].capabilities.is_active(): dev.options['source'].value = self.__source logger.info("Scanner source set to '%s'" % self.__source) try: pyinsane2.set_scanner_opt(dev, 'resolution', [resolution]) except pyinsane2.PyinsaneException as exc: logger.warning( "Unable to set scanner resolution to {}: {}".format( resolution, exc ) ) logger.exception(exc) resolution = int(dev.options['resolution'].value) logger.warning("Falling back to current resolution: {}".format( resolution )) try: pyinsane2.set_scanner_opt(dev, 'mode', ["Color"]) except pyinsane2.PyinsaneException as exc: logger.warning("Unable to set scanner mode !" " May be 'Lineart': {}".format(exc)) logger.exception(exc) try: pyinsane2.maximize_scan_area(dev) except pyinsane2.PyinsaneException as exc: logger.warning("Failed to maximize the scan area." " May only scan part of the image: {}".format(exc)) logger.exception(exc) scan_session = dev.scan(multiple=False) scan_size = scan_session.scan.expected_size self.emit('calibration-scan-info', scan_size[0], scan_size[1]) last_line = 0 try: while self.can_run: scan_session.scan.read() next_line = scan_session.scan.available_lines[1] if (next_line > last_line + 50): chunk = scan_session.scan.get_image(last_line, next_line) self.emit('calibration-scan-chunk', last_line, chunk) last_line = next_line time.sleep(0) # Give some CPU time to PyGtk if not self.can_run: self.emit('calibration-scan-canceled') scan_session.scan.cancel() return except EOFError: pass return (scan_session.images[-1], resolution)
def 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 = pyinsane2.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("") # For the possible resolutions, look at # device.options['resolution'].constraint # It will either be: # - None: unknown # - a tuple: (min resolution, max resolution) # - a list: [75, 150, 300, 600, 1200, ...] pyinsane2.set_scanner_opt(device, 'source', ['Auto', 'FlatBed']) pyinsane2.set_scanner_opt(device, 'resolution', [300]) try: pyinsane2.maximize_scan_area(device) except Exception as exc: print("Failed to maximize scan area: {}".format(exc)) # Beware: Some scanner have "Lineart" or "Gray" as default mode pyinsane2.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 + 100): 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")
if devices: device = devices[0] print("I'm going to use the following scanner: %s" % (str(device))) pyinsane2.set_scanner_opt(device, 'resolution', [300]) else: print( "Check if scanner is online, and you have the correct WIFI connection!" ) # Beware: Some scanners have "Lineart" or "Gray" as default mode # better set the mode everytime pyinsane2.set_scanner_opt(device, 'mode', ['Gray']) # Beware: by default, some scanners only scan part of the area # they could scan. pyinsane2.maximize_scan_area(device) scan_session = device.scan(multiple=False) try: print("Initiating Scan operation") while True: scan_session.scan.read() except EOFError: pass image = scan_session.images[-1] print("Saving image") image.save("test.png") print("Show image?") rep = input() if rep.lower().startswith("y"): image.show("Wazaa")