Ejemplo n.º 1
0
def obtainScanners():
    sane.init()
    try:
        devices = sane.get_devices()
        return devices
    except (RuntimeError, sane._sane.error) as msgerr:
        return None
Ejemplo n.º 2
0
Archivo: app.py Proyecto: Rouji/webscan
def scan():
    sane.init()
    devices = sane.get_devices(True)
    if not devices:
        sane.exit()
        return jsonify({'success': False, 'error': 'No scanner found.'}), 404
    try:
        dev = sane.open(devices[0][0])
        #param = dev.get_parameters()
        dev.mode = config.SCANNER_MODE
        dev.resolution = config.SCANNER_DPI
        dev.depth = config.SCANNER_BPP
        dev.start()
        im = dev.snap()
        dev.close()
    except Exception as ex:
        sane.exit()
        return jsonify({'success': False, 'error': 'Scanning failed. Scanner might not be ready or turned off.'}), 500
    if 'crop' in request.values:
        im = auto_crop(im)
    thumb = im.copy()
    thumb.thumbnail((config.THUMB_SIZE, config.THUMB_SIZE), Image.ANTIALIAS)
    id = rnd(20)
    scanned_images[id] = (
        pil_to_jpeg(im, config.JPEG_QUALITY),
        pil_to_jpeg(thumb, config.THUMB_QUALITY)
    )
    sane.exit()
    return jsonify({'success': True, 'id': id})
 def threadInitialize(self):
     print 'threadInitialize'
     self.currentscanner = ''
     sane.init()
     self.scannerlist = sane.get_devices()
     print self.scannerlist, len(self.scannerlist)
     self.emit(QtCore.SIGNAL('scannerlist(list)'),self.scannerlist)
Ejemplo n.º 4
0
 def on_actionChangeDevice_triggered(self):
     ##SANE
     message = ''
     try:
         import sane
     except ImportError:
         # sane found no scanner - disable scanning;
         message = self.tr("Sane not found! Scanning is disabled.")
     else:
         from .scannerselect import ScannerSelect
         sane.init()
         sane_list = sane.get_devices()
         saved_device = settings.get('scanner:device')
         if saved_device in [x[0] for x in sane_list]:
             message = self.tr("Sane found configured device...")
             self.scannerSelected()
         elif not sane_list:
             message = self.tr("Sane dit not find any device! "
                               "Scanning is disabled.")
         else:
             # there is not configured device => run configuration
             ss = ScannerSelect(sane_list, parent=self)
             ss.accepted.connect(self.scannerSelected)
             ss.show()
     self.statusBar().showMessage(message, 2000)
Ejemplo n.º 5
0
    def __init__(self):
        import sane

        sane.init()
        self.backup = False
        """ 
        When set to a fullpath, scans will be saved immediately to the path
        specified after scanning 
        """
        
        self.device = sane.get_devices()[0][0]
        self.sane = sane.open(self.device)
        self.sane.mode = 'Color'
        self.sane.source = 'ADF Duplex'
        self.sane.resolution = 300
        self.multi = self.sane.multi_scan()
        
        self.dd = time.strftime('%Y-%m-%d')
        """ Directory named after current date, used for self.backup """

        self.dt = time.strftime('%H-%M-%S')
        """ Directory named after current time, used for self.backup """ 

        self.cnt = 0
        """ Count used for files saved on backup """ 

	self.tmp = tempfile.mkdtemp()
	""" Temp directory used for scans """ 
Ejemplo n.º 6
0
 def __init__(self, duplex, height_in_mm, resolution):
     sane.init()
     s = sane.open(sane.get_devices()[0][0])
     if duplex:
         s.source = 'ADF Duplex'
     else:
         s.source = 'ADF Front'
     s.endorser = True
     s.endorser_string = '%08ud'
     s.page_height = height_in_mm
     s.br_y = height_in_mm
     s.mode = 'Color'
     s.resolution = resolution
     s.y_resolution = resolution
     # be ready to remove this if it does not properly set reported dpi
     s.swdeskew = 0  # software deskew might cause problems with our line recog
     # Gray at 140 took 3.1 sec
     # at 150 took 3.2 sec
     # at 200 took 4.0
     # at 220 took 5.1
     # at 240 took 3.2 sec
     # at 270 will not process properly
     # at 249 will not process properly
     self.s = s
     self.duplex = duplex
Ejemplo n.º 7
0
	def get_available_devices():
		sane.init()
		list = []
		for device in sane.get_devices():
			if "scanner" in device[3]:
				list.append(device)
		return list			
def getDevices():

	#Initialize SANE
	sane.init()

	#Get list of devices & let user know the list of devices has been selected
	devices = sane.get_devices()
	scanners_found.pack()

	#Insert options into the listbox. Certain Linux distributions sometimes have issues with
	#obtaining a list of devices from SANE, so users may need to press "Find Scanners" twice.
	#(When "Find Scanners" is pressed the first time, sometimes the list of devices returned is
	#empty.) The purpose of this "if" statement is to check if the device list is empty or not.	
	if (len(devices) != 0):
		count = 1
		for device in devices:
			device_name = device[1] + " " + device[2]
			devices_listbox.insert(count,device_name)
			count += 1
	

		#Disable "Get Devices" button
		getDevices_button.config(state='disabled')

		#Now display a button to let the user select the scanner
		Select_button.pack()
		scanners_found.pack_forget()
	else:
		Select_button.pack_forget()
		scanners_found.pack()
Ejemplo n.º 9
0
 def reset(self):
     self.device.close()
     sane.exit()
     sane.init()
     devices = sane.get_devices()
     self.device = sane.open(devices[0][0])
     self.initialize()
Ejemplo n.º 10
0
 def get_available_devices():
     sane.init()
     list = []
     for device in sane.get_devices():
         if "scanner" in device[3]:
             list.append(device)
     return list
Ejemplo n.º 11
0
 def __init__(self, duplex, height_in_mm, resolution):
     sane.init()
     errstring = ""
     s = sane.open(sane.get_devices()[0][0])
     if duplex:
         s.source = 'ADF Duplex'
     else:
         s.source = 'ADF Front'
     s.endorser = True
     s.endorser_string = '%08ud'
     s.page_height = height_in_mm
     s.br_y = height_in_mm
     s.mode = 'Color'
     s.resolution = resolution
     s.y_resolution = resolution
     # be ready to remove this if it does not properly set reported dpi
     s.swdeskew = 0 # software deskew might cause problems with our line recog
     # Gray at 140 took 3.1 sec
     # at 150 took 3.2 sec
     # at 200 took 4.0
     # at 220 took 5.1
     # at 240 took 3.2 sec
     # at 270 will not process properly
     # at 249 will not process properly
     self.s = s
     self.duplex = duplex
Ejemplo n.º 12
0
def quick_scan(settings={}, test=False):
    """Make scan using first scanning device found by SANE driver.
    """
    # init and find devices
    sane.init()
    devices = sane.get_devices(localOnly=True)

    if test:
        devices = [("test", "SANE", "SANE", "SANE")]
        settings["source"] = "Flatbed"
        settings["test_picture"] = "Color pattern"
        settings["mode"] = "Color"
        settings["resolution"] = 75
        settings["depth"] = 8

    if not len(devices):
        return None
    dev_name = devices[0][0]

    # open scanner
    scanner = sane.open(dev_name)

    # set options
    if "mode" in settings:
        scanner.mode = settings["mode"]
    for (key, value) in settings.items():
        setattr(scanner, key, value)

    img = scanner.arr_scan()
    scanner.close()
    sane.exit()
    return img
Ejemplo n.º 13
0
def obtainScanners():
    sane.init()
    try:
        devices = sane.get_devices()
        return devices
    except (RuntimeError, sane._sane.error), msgerr:
        return None
Ejemplo n.º 14
0
 def on_actionChangeDevice_triggered(self):
     ##SANE
     message = ''
     try:
         import sane
     except ImportError:
         # sane found no scanner - disable scanning;
         message = self.tr("Sane not found! Scanning is disabled.")
     else:
         from .scannerselect import ScannerSelect
         sane.init()
         sane_list = sane.get_devices()
         saved_device = settings.get('scanner:device')
         if saved_device in [x[0] for x in sane_list]:
             message = self.tr("Sane found configured device...")
             self.scannerSelected()
         elif not sane_list:
             message = self.tr("Sane dit not find any device! "
                               "Scanning is disabled.")
         else:
             # there is not configured device => run configuration
             ss = ScannerSelect(sane_list, parent=self)
             ss.accepted.connect(self.scannerSelected)
             ss.show()
     self.statusBar().showMessage(message, 2000)
Ejemplo n.º 15
0
    def scan(self, dpi=200):
        sane.init()
        scanner = sane.open(self._device)
        image = scanner.scan()
        scanner.close()
        sane.exit()

        return image
Ejemplo n.º 16
0
 def __init__(self,imageContainer,dataReadyCallback=None):
     self.imageContainer = imageContainer
     self.dataReadyCallback = dataReadyCallback
     #self.tmpFileName=tempfile.NamedTemporaryFile().name
     sane.init()
     self.selected = None
     self.sourceData = None
     self.devices=None
Ejemplo n.º 17
0
 def run(self):
     # Initialize SANE
     try:
         with ScanError.sanitize():
             sane.init()
     except Exception, e:
         self._error_callback("Couldn't initialize SANE: %s" % e)
         return
Ejemplo n.º 18
0
    def scan(self, dpi=200):
        sane.init()
        scanner = sane.open(self._device)
        image = scanner.scan()
        scanner.close()
        sane.exit()

        return image
Ejemplo n.º 19
0
 def __init__(self):
     super(Scanner, self).__init__()
     self.handle=None
     sane.init()
     self.get_device('FUJITSU')
     logging.debug('got scanning device')
     atexit.register(self.cleanup)
     self.output_dir = "" if len(sys.argv) < 2 else sys.argv[1]
     os.makedirs(self.output_dir,exist_ok=True)
Ejemplo n.º 20
0
 def getScanners(self):
     """Get available scanner from sane module
     """
     sane.init()
     devices = sane.get_devices()[0]
     if len(devices) > 0:
         return devices
     else:
         return None
Ejemplo n.º 21
0
 def getScanners(self):
     """
     Get available scanner from sane module
     """
     sane.init()
     devices = sane.get_devices()[0]
     if len(devices) > 0:
         return devices
     else:
         return None
def runScan(device,source,paper,dest):
    #print 'runScan',device,source,paper,dest
    sane.init()
    #print sane.get_devices()
    #print 'try to open scanner',device
    scandev = sane.open(device)
#   except:
#       'open scanner failed'
#       return -1

    #print 'set source', source
    if source == 'ADF':
        #print 'setting batch_scan'
        scandev.source = source
        scandev.batch_scan = 1
        scancount = 50
    else:
        scandev.source = source
        scandev.batch_scan = 0
        scancount = 1

    #set dpi to 200
    scandev.resolution = 200

    #calculate size and set x,y
    sizes = paperlist.paperlist[paper]
    #print 'setPaper',paper,sizes
#        print self.scandev.opt
    scandev.tl_x = 0
    scandev.tl_y = 0
    scandev.br_x = sizes[0]
    scandev.br_y = sizes[1]
    #print 'about to start scan'
#    s = raw_input()
    while scancount > 0:
        #print 'run',scancount
        try:
                scandev.start()
                scancount -= 1
        except:
                #traceback.print_exc()
                scancount = 0
                break

        #print 'scanning'
        img = scandev.snap()
        img = crop.autoCrop(img)
        filename = str(dest)+'/'+str(timeStamp())+'.png'
        img.save(filename,"PNG")
        #print 'closing scanner device'
        print filename
        #flush()

    scandev.close()
    return 0
Ejemplo n.º 23
0
 def __init__(self):
     self.imgs = []
     self.settings = {}
     sane.init()
     self.settings['status'] = "NO SCANNER"
     print self.settings['status']
     self.status = "NO SCAN YET"
     self.scanner = None
     self.scanner_device = 'dummy'
     self.settings['scanner'] = 'dummy'
     return None
Ejemplo n.º 24
0
def do_scanning(device_name, settings_dict):
    sane.init()
    scanner = sane.open(device_name)
    if "mode" in settings_dict:
        scanner.mode = settings_dict["mode"]
    for (key, value) in settings_dict.iteritems():
        setattr(scanner, key, value)
    imgarray = scanner.arr_scan()
    scanner.close()
    sane.exit()
    return imgarray
Ejemplo n.º 25
0
 def __init__(self):
     self.imgs = []
     self.settings = {}
     sane.init()
     try:
         for device in sane.get_devices():
             if device[3] == 'scanner':
                 self.scanner_device = sane.get_devices()[0][0]
         self.scanner = sane.open(self.scanner_device)
     except:
         self.settings['status'] = "NO SCANNER"
         print self.settings['status']
         self.scanner = None
         return None
     self.threadlock = thread.allocate_lock()
     self.settings['dpi'] = 100
     self.settings['scanner'] = self.scanner_device
     self.settings['page_height'] = int(25.4 * 11.0)
     self.settings['br_y'] = int(25.4 * 11.0)
     self.settings['page_width'] = int(25.4 * 8.5)
     self.settings['br_x'] = int(25.4 * 8.5)
     self.settings['duplex'] = True
     self.settings['imprinter'] = False
     self.settings['note'] = "No note."
     self.settings['status'] = "OK"
     self.settings['last'] = 0
     self.settings['last_processed'] = -1
     self.settings['status'] = "OK"
     self.scanner.resolution = self.settings['dpi']
     self.scanner.mode = 'color'
     if self.settings['duplex']:
         self.scanner.source = 'ADF Duplex'
     else:
         self.scanner.source = 'ADF Front'
     logging.info("Scanner is %s resolution %s mode %s source %s" %
                  (self.scanner_device, self.scanner.resolution,
                   self.scanner.mode, self.scanner.source))
     print "Scanner is %s resolution %s mode %s source %s" % (
         self.scanner_device, self.scanner.resolution, self.scanner.mode,
         self.scanner.source)
     self.scanner.endorser = True
     print "Set scanner endorser to True"
     #self.scanner.endorser_step = 1
     #print "Set scanner endorser_step to 1"
     #self.scanner.endorser_val = 11
     #print "Set scanner endorser_val to 11"
     for s in self.get_settings_splitbytype():
         print s
         print "---"
     return None
Ejemplo n.º 26
0
def main(model, results):
    sane.init()
    print("Loading scanner devices...")
    devices = sane.get_devices()
    if len(devices) == 0:
        print("No devices available.")
        return
    print(" Id Vendor                         Product")
    print("-" * 80)
    for idx, device in enumerate(devices):
        print(
            str(idx).rjust(3) + " " + device[1].ljust(30)[:30] + " " +
            device[2].ljust(46)[:46])
    while True:
        try:
            dev_id = int(input("Device ID: "))
            if not 0 <= dev_id < len(devices):
                print("Device id must be number between 0 and {}.".format(
                    len(devices) - 1))
            else:
                break
        except ValueError:
            print("Device id must be number between 0 and {}.".format(
                len(devices) - 1))
    try:
        device = sane.open(devices[dev_id][0])

        device.depth = 8
        device.mode = 'gray'
        device.resolution = 200

        # scan a page and to things...
        while True:
            while True:
                do_scan = input("Scan next page? [Y/n]  ")
                do_scan = do_scan.upper()
                if do_scan == 'Y' or do_scan == 'N' or do_scan == '':
                    break
            if do_scan == 'N':
                break

            device.start()
            im = device.snap()
            im.save('scanned.png')
            scan_page(im, model, results)
    finally:
        device.close()
    return
Ejemplo n.º 27
0
def _init_sane(dialog):
    global s
    s = None
    start = time.time()
    version = sane.init()
    print('{} SANE version: {}, scanning devices...'.format(
        time.time() - start, version))

    available = sane.get_devices()
    print('{} Available devices = {}'.format(time.time() - start, available))

    if not available:
        print("NO DEVICES FOUND.")
        s = None
        dialog.statusLabel.config(
            text='Idle (no sane devices found) {:.1f} s'.format(time.time() -
                                                                start))
    else:
        if len(available) > 1:
            DeviceDialog(dialog, [row[0] for row in available],
                         start_time=start)
            return

        print('{} Opening first device: {}'.format(time.time() - start,
                                                   available[0]))
        open_start = time.time()
        s = sane.open(available[0][0])
        print('{} Device opened in {:.1f} s'.format(time.time() - start,
                                                    time.time() - open_start))
        dialog.statusLabel.config(
            text='Idle (sane loaded in {:.1f} s)'.format(time.time() - start))
Ejemplo n.º 28
0
 def __enter__(self):
     if self.savinr:
         fourcc_r = cv2.VideoWriter_fourcc(*'XVID')
         self.out_r = cv2.VideoWriter(self.saveraw,fourcc_r, 0.2, self.scanres)
     if self.savinm:
         fourcc_m = cv2.VideoWriter_fourcc(*'XVID')
         self.out_m = cv2.VideoWriter(self.savemod,fourcc_m, 0.2, self.scanres)
     self.zsejninita = sane.init()
     listaprzyp = {jest[0] for jest in sane.get_devices() if jest[1:]==self.scnr3tupl}
     if len(listaprzyp)==0: raise ScannerNotFound
     elif len(listaprzyp)==1: totenjest=listaprzyp[0]
     else:
         wybrano = False
         ktorytoje = list(totenjest)
         while not wybrano:
             try:
                 totenjest=ktorytoje[1+int(raw_input(''.join([
                     'Wybierz skaner: \n',
                     ''.join([''.join(['\t',str(nje),'. ',ktorytoje[nje],' \n']) for nje in range(len(ktorytoje))]),
                     'Podaj numer z listy: '])))]
                 wybrano = True
             except ValueError: pass
             except IndexError: pass
     self.skaner = sane.open(totenjest)
     self.skaner.mode = 'Gray'
     self.skaner.resolution = scanq
     return self
Ejemplo n.º 29
0
def executeScan(fileName):
    #
    # Change these for 16bit / grayscale scans
    #
    depth = 8
    mode = 'color'

    #
    # Initialize sane
    #
    ver = sane.init()
    print('SANE version:', ver)

    #
    # Get devices
    #
    devices = sane.get_devices()
    print('Available devices:', devices)

    #
    # Open first device
    #
    dev = sane.open(devices[0][0])

    #
    # Set some options
    #
    params = dev.get_parameters()
    print("device params", params)
    try:
        dev.depth = depth
    except:
        print('Cannot set depth, defaulting to %d' % params[3])

    try:
        dev.mode = mode
    except:
        print('Cannot set mode, defaulting to %s' % params[0])

    try:
        dev.br_x = 320.
        dev.br_y = 240.
    except:
        print('Cannot set scan area, using default')

    params = dev.get_parameters()
    print('Device parameters:', params)

    #
    # Start a scan and get and PIL.Image object
    #
    dev.start()
    im = dev.snap()
    im.save(fileName + '.png')

    #
    # Close the device
    #
    dev.close()
Ejemplo n.º 30
0
def init_scanner(config):
    sane.init()
    logger.debug(sane.get_devices())
    scanners = [i[0] for i in sane.get_devices()  if i[2] == config.get("scanner", "model")]
    if not scanners:
        logger.error("Not able to find any scanner !")
        exit(1)
    scanner = sane.open(scanners[0])
    scanner.mode = config.get("scanner","mode")
    scanner.resolution = int(config.get("scanner", "resolution"))
    scanner.source = config.get("scanner", "source")
    if [True for i in config.items("input")  if i[0] == "type"]:
        logger.debug("Specifying format")
        scanner.br_x = float(config.get("input","size_x"))
        scanner.br_y = float(config.get("input","size_y"))
    scanner.swcrop = 1
    return scanner
Ejemplo n.º 31
0
 def getScannerList(self):
     scanOption = {}
     sane.init()
     scanners = sane.get_devices()
     for scanner in scanners:
         scan_open = sane.open(scanner[0])
         options = scan_open.get_options()
         scan_open.close()
         scanOption[scanner[0]] = {}
         for option in options:
             if option[1] == "mode":
                 scanOption[scanner[0]]["mode"] = option[8]
             elif option[1] == "source":
                 scanOption[scanner[0]]["source"] = option[8]
             elif option[1] == "resolution":
                 scanOption[scanner[0]]["resolution"] = {"min": option[8][0], "max": option[8][1], "step": option[8][2]}
     return scanOption
Ejemplo n.º 32
0
    def init(self):
        """
        Initialization.
        """
        self.sane_ver = sane.init()
        self.devices = sane.get_devices()

        # Задублированные опции сканирования
        self.options = dict()
Ejemplo n.º 33
0
    def _refresh(self):
        self._devices = []

        sane.init()
        devices = sane.get_devices()
        for dev in devices:
            # Check if sane is able to open this device, if not just skip
            try:
                scanner = sane.open(dev[0])
                scanner.close()
            except:
                continue

            scanner_id = 'sane-%s' % len(self._devices)
            scanner = Scanner(scanner_id, dev[0], dev[1], dev[2], dev[3])
            self._devices.append(scanner)

        sane.exit()
Ejemplo n.º 34
0
    def init(self):
        """
        Инициализация.
        """
        self.sane_ver = sane.init()
        self.devices = sane.get_devices()

        # Задублированные опции сканирования
        self.options = dict()
Ejemplo n.º 35
0
    def _refresh(self):
        self._devices = []
        
        sane.init()
        devices = sane.get_devices()    
        for dev in devices:
            # Check if sane is able to open this device, if not just skip
            try:
                scanner = sane.open(dev[0])
                scanner.close()
            except:
                continue 
                                
            scanner_id = 'sane-%s' % len(self._devices)
            scanner = Scanner(scanner_id, dev[0], dev[1], dev[2], dev[3])
            self._devices.append(scanner)

        sane.exit()
Ejemplo n.º 36
0
    def __init__(self,scanner=0,dpi=600,mode='Gray',depth=8):
        """ Scanner class with default parameters """
        sane.init()
        devices = sane.get_devices()
        try:
            device = devices[scanner]
        except IndexError:
            print 'No scanner found'
            self.scanner = False
            return
        
        #We just get the first one
        self.scanner = sane.open(device[0])
        #improve dpi
        self.scanner.resolution = dpi

        #there's other options to change 
        self.scanner.mode = mode
        self.scanner.depth = depth
Ejemplo n.º 37
0
    def __init__(self,
                 duplex,
                 height_in_mm,
                 resolution,
                 image_loc_fmt_string,
                 endorser=False):
        self.duplex = duplex
        self.height_in_mm = int(height_in_mm)
        self.resolution = int(resolution)
        self.image_loc_fmt_string = image_loc_fmt_string
        if endorser.startswith("T"):
            self.endorser = True
        else:
            self.endorser = False

        sane.init()
        print "Init"
        sys.stdout.flush()
        devlist = sane.get_devices()
        if len(devlist) < 1:
            print "No scanner found."
            sys.stdout.flush()
            sys.exit(0)
        self.s = sane.open(devlist[0][0])
        print "Devices"
        sys.stdout.flush()

        self.duplex = duplex
        if duplex.startswith("T"):
            self.s.source = 'ADF Duplex'
        else:
            self.s.source = 'ADF Front'
        try:
            self.s.endorser = self.endorser
            if self.s.endorser:
                self.s.endorser_string = '%08ud'
                try:
                    self.s.endorser_bits = 24
                except Exception, e:
                    print e
                    sys.stdout.flush()
        except AttributeError, e:
            print e
Ejemplo n.º 38
0
 def __init__(self):
     self.imgs = []
     self.settings = {}
     sane.init()
     try:
         for device in sane.get_devices():
             if device[3] == 'scanner':
                 self.scanner_device = sane.get_devices()[0][0]
         self.scanner = sane.open(self.scanner_device)
     except:
         self.settings['status'] = "NO SCANNER"
         print self.settings['status']
         self.scanner = None
         return None
     self.settings['dpi'] = 100
     self.settings['scanner'] = self.scanner_device
     self.settings['page_height'] = int(25.4 * 11.0)
     self.settings['br_y'] = int(25.4 * 11.0)
     self.settings['page_width'] = int(25.4 * 8.5)
     self.settings['br_x'] = int(25.4 * 8.5)
     self.settings['duplex'] = True
     self.settings['imprinter'] = False
     self.settings['note'] = "No note."
     self.settings['status'] = "OK"
     self.settings['last'] = 0
     self.settings['last_processed'] = -1
     self.settings['status'] = "OK"
     self.scanner.resolution = self.settings['dpi']
     self.scanner.mode = 'Color'
     if self.settings['duplex']:
         self.scanner.source = 'ADF Duplex'
     else:
         self.scanner.source = 'ADF Front'
     logging.info("Scanner is %s resolution %s mode %s source %s" %
                  (self.scanner_device, self.scanner.resolution,
                   self.scanner.mode, self.scanner.source))
     print "Scanner is %s resolution %s mode %s source %s" % (
         self.scanner_device, self.scanner.resolution, self.scanner.mode,
         self.scanner.source)
     return None
Ejemplo n.º 39
0
    def __init__(self, 
                 duplex, 
                 height_in_mm, 
                 resolution, 
                 image_loc_fmt_string,
                 endorser=False):
        self.duplex = duplex
        self.height_in_mm = int(height_in_mm)
        self.resolution = int(resolution)
        self.image_loc_fmt_string = image_loc_fmt_string
        if endorser.startswith("T"):
            self.endorser = True
        else:
            self.endorser = False

        sane.init()
        print "Init"
        sys.stdout.flush()
        devlist = sane.get_devices()
        if len(devlist)<1:
            print "No scanner found."
            sys.stdout.flush()
            sys.exit(0)
        self.s = sane.open(devlist[0][0])
        print "Devices"
        sys.stdout.flush()

        self.duplex = duplex
        if duplex.startswith("T"):
            self.s.source = 'ADF Duplex'
        else:
            self.s.source = 'ADF Front'
        self.s.endorser = self.endorser
        if self.s.endorser:
            self.s.endorser_string = '%08ud'
            try:
                self.s.endorser_bits = 24
            except Exception, e:
                print e
                sys.stdout.flush()
Ejemplo n.º 40
0
def init(**kwargs):
	global scanner
	
	sane.init()
	
	devices = {}
	i = 0
	
	print "Available devices:"
	
	for device in sane.get_devices():
		devices[i] = device[0]
		print "%d. [%s] %s %s" % (i, device[3], device[1], device[2])
		i += 1
	
	choice = int(raw_input("[?] What device would you like to use?  "))
	
	try:
		scanner = sane.open(devices[choice])
	except KeyError, e:
		print "You did not input a valid device ID."
		exit(1)
Ejemplo n.º 41
0
Archivo: scan.py Proyecto: Virako/fpinn
def select_scan():
    sane.init()
    devices = sane.get_devices()

    if not len(devices):
        print "No existen dispositivos. "
        return 0
    elif len(devices) > 1:
        print "Seleccione el dispositivo deseado: " # TODO
        n = -1
        while n != -1:
            num = 0
            for d in devices:
                print num, ": ", d
                num += 1
            try:
                n = int(raw_input("Seleccione dispositivo para usar: "))
            except:
                n = -1
        return devices[n][0]
    elif len(devices) == 1:
        return devices[0][0]
Ejemplo n.º 42
0
    def getScanners(self):
        """Get available scanner from sane module
        """
        sane.init()
        devices = sane.get_devices()[0]

        scannerList = []
        for index, scannerName in enumerate(device):
            try:
                # Checking whether scanner is connected
                # Other would be working if first on is fine
                if index == 0:
                    scanner = sane.open(scannerName)
                    scanner.close()
                scannerList.append(scannerName)
            except Exception as e:
                # Scanner not connected but driver installed
                self.info = "Driver Installed but scanner not connected try restarting"

        if scannerList:
            return scannerList
        else:
            return None
Ejemplo n.º 43
0
def scanDoc():
    var = sane.init()

    devices = var.get_devices()
    print("Devices: " + devices)

    # Open first device
    dev = sane.open(devices[0][0])

    # Start a scan and get and PIL.Image object
    dev.start()
    im = dev.snap()
    im.save(FILE_NAME)
    dev.close()
Ejemplo n.º 44
0
    def __init__(self,*args,**kwargs):
        super(ScanWindow,self).__init__(*args, **kwargs)

        self.scannerSettings = {}
        self.images = []
        
        self.sane_version = sane.init()
        self.sane_devices = sane.get_devices()
        self.scanner = sane.open(self.sane_devices[0][0])
        self.initialiseScannerOptions(self.scanner)
        self.countLabel = None
        self.Bind(wx.EVT_CLOSE,self.OnClose)

        self.InitUI()
        self.Show(True)
Ejemplo n.º 45
0
 def __init__(self, id = 0, properties = { "mode": "color"}):
     global _SANE_INIT
     import sane
     if not _SANE_INIT:
         try:
             sane.init()
             _SANE_INIT = True
         except:
             warn("Initializing pysane failed, do you have pysane installed?")
             return
 
     devices = sane.get_devices()
     if not len(devices):
         warn("Did not find a sane-compatable device")
         return
     
     self.usbid, self.manufacturer, self.model, self.kind = devices[id]
     
     self.device = sane.open(self.usbid)
     self.max_x = self.device.br_x
     self.max_y = self.device.br_y #save our extents for later
     
     for k, v in properties.items():
         setattr(self.device, k, v)
Ejemplo n.º 46
0
	def __init__(self):
		
		self.config.read("scanner.cfg")
		self.previewres=string.atof(self.config.get('general','previewres'))
		print "Reading config file done"

		t=time()
		print 'Initializing scanner ', sane.init(),
		print time()-t,'seconds'

		t=time()
		devs=sane.get_devices()
		print 'Fetching available devices took ',time()-t,'seconds'
			
		self.scannerdev=devs[string.atoi(self.config.get('general','devicenumber'))][0]
			
		self.reset_settings()
Ejemplo n.º 47
0
	def write_info(self,towriteto):
		towriteto.write( '\n\nSANE version:\n'+str(sane.init()))
		devs = sane.get_devices()
		towriteto.write( '\n\nAvailable devices:\n'+str(devs))
		scanner = sane.open(devs[string.atoi(self.config.get('general','devicenumber'))][0])
		towriteto.write( '\n\nParameters of specified device:\n'+str(scanner.get_parameters()) )
		towriteto.write( '\n\nOptlist:\n')
		towriteto.write( str(scanner.optlist) )
		opts=scanner.get_options()
		towriteto.write( '\n\nActive options:\n')
		for x in opts:
			if self.option_is_active(x[1]):
				towriteto.write( str(x)+'\n' )
		towriteto.write( '\n\nInactive options:\n')
		for x in opts:
			if not self.option_is_active(x[1]):
				towriteto.write( str(x)+'\n' )
Ejemplo n.º 48
0
	def get_scanner(self):
		if (None == self.scanner) :
			t=time()
			print 'Initializing scanner ', sane.init(),
			print time()-t,'seconds'

			t=time()
			
			devs=sane.get_devices()
			print 'Fetching available devices took ',time()-t,'seconds'

			t=time()
			self.scanner=sane.open(devs[0][0])
			print 'Opening the first available device took ', time()-t,'seconds'

			return self.scanner
		else :
			return self.scanner
Ejemplo n.º 49
0
    def __init__(self,
                 device,
                 scanner_mode_switching,
                 resolution=300,
                 brightness=40,
                 scan_area=0):
        sane_version = sane.init()
        self.device_name = device[2]
        try:
            self.scanner = sane.open(device[0])
        except:
            print("####sane error!")
        else:
            #Brightness and Threshold
            self.light_parameter_state = False
            options = self.get_scanner_option('brightness')
            if options:
                self.light_parameter_state = True
                self.light_parameter = "brightness"
                try:
                    self.min = options[-1][0]
                    self.max = options[-1][1]
                except:
                    self.min = -100
                    self.max = 100

            options = self.get_scanner_option('threshold')
            if options:
                self.light_parameter_state = True
                self.light_parameter = "threshold"
                try:
                    self.min = options[-1][0]
                    self.max = options[-1][1]
                except:
                    self.min = 0
                    self.max = 255

            #Calling super constructor for inetialising brightness resolution and scan area
            super(DriverSane, self).__init__(scanner_mode_switching,device,resolution,\
            brightness,scan_area)
            if (not scanner_mode_switching):
                self.set_scan_mode("Color")
            self.brightness_multiplier = (self.max - self.min) / 100
            self.brightness_offset = self.min
Ejemplo n.º 50
0
	def __init__(self,device,scanner_mode_switching,resolution=300,brightness=40,scan_area=0):
		sane_version = sane.init()
		self.device_name = device[2];
		try:
			self.scanner = sane.open(device[0])
		except:
			print("####sane error!")
		else:
			#Brightness and Threshold
			self.light_parameter_state = False 
			options = self.get_scanner_option ('brightness')
			if options:
				self.light_parameter_state = True
				self.light_parameter = "brightness"
				try:
					self.min =  options[-1][0]
					self.max = options[-1][1]
				except:
					self.min = -100
					self.max = 100

			options = self.get_scanner_option ('threshold')
			if options:
				self.light_parameter_state = True
				self.light_parameter = "threshold"
				try:
					self.min =  options[-1][0]
					self.max = options[-1][1]
				except:
					self.min = 0
					self.max = 255
			
			#Calling super constructor for inetialising brightness resolution and scan area
			super(DriverSane, self).__init__(scanner_mode_switching,device,resolution,\
			brightness,scan_area)
			if(not scanner_mode_switching):
				self.set_scan_mode("Color")
			self.brightness_multiplier = (self.max - self.min)/100
			self.brightness_offset = self.min
Ejemplo n.º 51
0
	def do_GET(self):
		if self.path == '/favicon.ico': #reroute annoying favicon requests so we don't have to send 404s
			self.path = '/style/images/tmp.ico'
	
		try:	
			#If the path contains a ? then we should parse it and scan and stuff --> http://www.faqts.com/knowledge_base/view.phtml/aid/4373		
			if self.path.find('?')!=-1:
				pathlist, values = self.urlParse(self.path)
				
				#Handle a refresh of the preview
				if values['button'] == 'snap':
					self.update_preview()
					self.path=extbase+'/demo.html'
				#Handle a scan
				elif values['button'] == 'scan':
					self.send_response(200)
					self.send_header('Content-type','image/png')
					self.end_headers()
					
					scanner=self.get_scanner()
					
					
					if values['imgtype'] == 'BW':
						scanner.mode='Lineart'
					elif values['imgtype'] == 'GRAY':
						scanner.mode='Gray'
					else:
						scanner.mode='Color'
					
					if values['resolution'] == 'OTHER':
						scanner.resolution=string.atof(values['custom_resolution'])
					else:
						scanner.resolution=string.atof(values['resolution'])
					
					#Translate the pixel locations in to realworld coordinates (in to mm)
					scanner.tl_x=string.atof(values['left']) * inchinmm / previewres 
					scanner.tl_y=string.atof(values['top']) * inchinmm / previewres
					scanner.br_x=scanner.tl_x + string.atoi(values['width']) * inchinmm / previewres 
					scanner.br_y=scanner.tl_y + string.atoi(values['height']) * inchinmm / previewres
					
					self.scan_and_save(self.wfile, values['filetype'])
					return
				#Error, print some debugging info
				else:
					self.send_response(200)
					self.send_header('Content-type','text/html')
					self.end_headers()
					self.wfile.write("<html><head/><body>Error. Form has no button value. ",str(values),"</body></html>")
					return

			#Snap a preview image and send it directly to the browser
			if self.path==extbase+'/snap':
				self.send_response(200)
				self.send_header('Content-type','image/png')
				self.end_headers()

				scanner=self.get_scanner()

				scanner.preview=True
				scanner.quality_cal=False
				scanner.depth=4
				scanner.resolution=previewres

				self.scan_and_save(self.wfile, 'PNG')

			#Do a scan and return the image directly to the browser
			elif self.path==extbase+'/scan':
				self.send_response(200)
				self.send_header('Content-type','image/png')
				self.end_headers()
				
				scanner=self.get_scanner()
				
				scanner.resolution=300.0
				
				self.scan_and_save(self.wfile, 'PNG')
				
			#FIXME!
#			elif self.path.endswith('.xhtml'):
#				f=open(basepath+self.path)
#				self.send_response(200)
#				self.send_header('Content-type','text/html')
#				self.end_headers()
#				
#				reader = Sax2.Reader()
#				doc=reader.fromStream(f)
#				PrettyPrint(doc,self.wfile)
#				
#				f.close()
#			
			#Used for debugging. Displays info about scanner.
			elif self.path==extbase+'/info':
				self.send_response(200)
				self.send_header('Conent-type','text/plain')
				self.end_headers()
				self.wfile.write( '\n\nSANE version:\n'+ str(sane.init()))
				devs = sane.get_devices()
				self.wfile.write( '\n\nAvailable devices:\n'+str(devs))
				scanner = sane.open(devs[0][0])
				self.wfile.write( '\n\nParameters of first device:\n'+str(scanner.get_parameters()) )
				self.wfile.write( '\n\nOptions:\n'+str(scanner.get_options()) )
			
			#We replace chair.jpg with the preview file.
			elif self.path==extbase+'/chair.jpg':
				f=open(previewfile)
				self.send_response(200)
				self.send_header('Content-type','image/png')
				self.end_headers()
				self.wfile.write(f.read())
				f.close()
			#If nothing special was aksed, just serve the file of the specified name
			else:
				print basepath+self.path
				f=open(basepath+self.path)
				self.send_response(200)
				
				if self.getContentType() == None:
					#Let's not serve unknown stuff
					self.send_header('Content-type','text/plain')
					self.end_headers()
					f.close()
					return
				else:
					self.send_header('Content-type',self.getContentType())
					
				self.end_headers()
				self.wfile.write(f.read())
				f.close()
		#If we cant open the file (=can't find the file) we send a 404
		except IOError:
			self.send_error(404, 'IOError')
Ejemplo n.º 52
0
    def scanDocument(self, singleDMS, dicUser):
        ##       misc = cuon.Misc.misc.misc()
        
##        sc = dicUser['prefDMS']['scan_program']
##        sc = sc + ' --mode ' + dicUser['prefDMS']['scan_mode']
##        sc = sc + ' --resolution ' + dicUser['prefDMS']['scan_resolution']
        
##        print sc
##        self.scanfile = dicUser['prefPath']['tmp'] +  misc.getRandomFilename('_scan.tmp')
##        print self.scanfile
##        sc = sc + ' >> ' + self.scanfile

##        print sc
##        ok = os.system(sc)
##        print ok
        # SANE for scan images
        
        print 'SANE version:', sane.init()
        print 'Available devices=', sane.get_devices()
        
    
        scanner=sane.open(dicUser['prefDMS']['scan_device'])
        print 'SaneDev object=', scanner
        print 'Device parameters:', scanner.get_parameters()
        
        # Set scan parameters
        scanner.mode = dicUser['prefDMS']['scan_mode']
        scanner.contrast=dicUser['prefDMS']['scan_contrast']
        scanner.brightness=dicUser['prefDMS']['scan_brightness']
        #scanner.white_level=dicUser['prefDMS']['scan_white_level']
        scanner.depth=dicUser['prefDMS']['scan_depth']
        scanner.br_x=dicUser['prefDMS']['scan_r']['x']
        scanner.br_y=dicUser['prefDMS']['scan_r']['y']
        scanner.resolution = dicUser['prefDMS']['scan_resolution']
        
        print 'Device parameters after setting:', scanner.get_parameters()
        #print scanner.contrast
        #print scanner.brightness
        #print scanner.white_level
        
        # Initiate the scan
        scanner.start()
        
        # Get an Image object
        # (For my B&W QuickCam, this is a grey-scale image.  Other scanning devices
        #  may return a
        im=scanner.snap()
        print 'Device parameters after snap:', scanner.get_parameters()

        # Write the image out as a GIF file
        #im.save('/home/jhamel/foo.png')
        
        im.show()
        if (im.mode != "RGB"):
            im = im.convert("RGB")

        singleDMS.size_x = im.size[0]
        singleDMS.size_y = im.size[1]
        
        s = im.tostring('raw','RGB')
        print len(s)
        s2 = bz2.compress(s)
        print len(s2)
        singleDMS.imageData = s2
Ejemplo n.º 53
0
#!/usr/bin/env python

#
# Shows how to scan a color image into a PIL rgb-image
#

# Get the path set up to find PIL modules if not installed yet:
import sys
sys.path.append('../PIL')

import sane
print('SANE version:', sane.init())
print('Available devices=', sane.get_devices())

s = sane.open(sane.get_devices()[0][0])

s.mode = 'color'
s.br_x = 320.
s.br_y = 240.

print('Device parameters:', s.get_parameters())

# Initiate the scan
s.start()

# Get an Image object
# (For my B&W QuickCam, this is a grey-scale image.  Other scanning devices
#  may return a
im = s.snap()

# Write the image out as a GIF file
Ejemplo n.º 54
0
#!/usr/bin/python3

import sane

sane.init()

# modes: 'Lineart', 'Gray', 'Color'
# source: 'Flatbed', 'Automatic Document Feeder'

devices = sane.get_devices()
print('devices:', devices)

dev = sane.open(devices[0][0])

params = dev.get_parameters()
print('parameters:', params)

options = dev.get_options()
#print('options:', options)
print('options:')
for option in options:
    print(option)

try:
    dev.depth = 1
except:
    print('Cannot set depth, defaulting to', params[3])

try:
    dev.mode = 'Lineart'
except:
Ejemplo n.º 55
0
import sane
from PIL import Image

var = sane.init()

devices = sane.get_devices()
print("Devices: ", devices)

# Open first device
dev = sane.open(devices[0][0])

# Start a scan and get and PIL.Image object
dev.start()
im = dev.snap()
im.save("Test.png")
Ejemplo n.º 56
0
def initialize_driver():
    """Initialize the scanner driver.
    """
    return sane.init()
Ejemplo n.º 57
0
from numarray import *
import sane
import Image

def toImage(arr):
    if arr.type().bytes == 1:
        # need to swap coordinates btw array and image (with [::-1])
        im = Image.frombytes('L', arr.shape[::-1], arr.tostring())
    else:
        arr_c = arr - arr.min()
        arr_c *= (255./arr_c.max())
        arr = arr_c.astype(UInt8)
        # need to swap coordinates btw array and image (with [::-1])
        im = Image.frombytes('L', arr.shape[::-1], arr.tostring())
    return im

print('SANE version:', sane.init())
print('Available devices=', sane.get_devices())

s = sane.open(sane.get_devices()[0][0])

# Set scan parameters
s.mode = 'gray'
s.br_x=320. ; s.br_y=240.

print('Device parameters:', s.get_parameters())

s.depth=16
arr16 = s.arr_scan()
toImage(arr16).show()
Ejemplo n.º 58
0
def run_scanapp():
    global logger
    global dpi
    global source
    global endorse_int
    global page_width_mm
    global page_height_mm
    global testmode
    global sane_error
    global current_root
    sane_error = None
    testmode = 0
    source = 'ADF Front'
    dpi = 150
    endorse_int = 1  # begin with endorser on,
    # so that you can set other endorser characteristics
    page_width_mm = int(round(25.4 * 8.5))
    page_height_mm = int(round(25.4 * 11))
    gobject.threads_init()
    # read configuration from tevs.cfg and set constants for this run
    cfg_file = tevsgui_get_args.get_args()
    scanconfig.get(cfg_file)
    homepath = os.path.expanduser("~")
    rootpath = homepath
    logbasefilename = os.path.basename(const.logfilename)
    logcompletefilename = os.path.join(homepath, logbasefilename)
    logger = scanconfig.logger(logcompletefilename)
    #print dir(const)
    # The file numbers and endorser values will come from a SerialNumber.
    endorser_step = 1

    testnumberfile = os.path.join(homepath, "nexttoscan.txt")
    sn = SerialNumber(testnumberfile, initial_value_if_no_file=50)
    if not os.path.exists(testnumberfile):
        try:
            f = open(testnumberfile, "w")
            f.write("0\n")
            f.close()
        except Exception as e:
            print e

# Initialize sane and set the scanner's defaults prior to the thread.
    s = sane.init()
    devices = sane.get_devices()
    try:
        s = sane.open(devices[0][0])
    except IndexError:
        print "No devices found."
        builder = gtk.Builder()
        runpath = os.path.split(__file__)[0]
        gladefile = os.path.join(runpath, "scanapp.glade")
        builder.add_from_file(gladefile)
        nsd = builder.get_object("noScannerDialog")
        nsd.run()
        #gtk.main()
        sys.exit(-1)

    sc = Scanner(None, sn, logger)
    scanner_init(sc)
    sa = ScanApp(sc, sn)

    gtk.main()
Ejemplo n.º 59
0
 def get_scanners(self):
     sane.init()
     devices = sane.get_devices()
     self.data_queue.put(devices)