Example #1
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
Example #2
0
 def reset(self):
     self.device.close()
     sane.exit()
     sane.init()
     devices = sane.get_devices()
     self.device = sane.open(devices[0][0])
     self.initialize()
Example #3
0
 def close(self):
     """
     Destory 'sane' class of sane module generated in getScanners function ie sane.init()
     Destory 'self.scanner' class of sane module generated in setScanner function
     """
     if self.scanner:
         self.scanner.close()
     sane.exit()
Example #4
0
    def scan(self, dpi=200):
        sane.init()
        scanner = sane.open(self._device)
        image = scanner.scan()
        scanner.close()
        sane.exit()

        return image
Example #5
0
def get_devices():
    # Try to find the devices.
    try:
        return sane.get_devices()
    except _sane.error:
        print('no devices found')
    finally:
        sane.exit()
Example #6
0
    def scan(self, dpi=200):
        sane.init()
        scanner = sane.open(self._device)
        image = scanner.scan()
        scanner.close()
        sane.exit()

        return image
Example #7
0
 def close(self):
     """
     Destory 'sane' class of sane module generated in getScanners function ie sane.init()
     Destory 'self.scanner' class of sane module generated in setScanner function
     """
     if self.scanner:
         self.scanner.close()
     sane.exit()
Example #8
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
Example #9
0
 def onB_exit(self):
     devs=sane.get_devices()
     if not devs:
         try:
             sane.exit()
         except: pass
     else:
         try:
             s=sane.cancel()
         except: pass
         #print "dev found:",s
         
     self.close()
Example #10
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()
Example #11
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()
Example #12
0
File: app.py Project: 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})
Example #13
0
 def exit(self):
     print "exiting"
     sane.exit()
Example #14
0
    print(scanner['mode'])
    scanner.mode = 'Color'
    print(scanner['mode'])

    print(scanner['resolution'])
    scanner.resolution = 600
    print(scanner['resolution'])

    # 600 dpi.
    # scanner.mode = 'Color'
    # scanner.resolution = 600

    # Scan.
    scanner.start()
    img = scanner.snap()

    # Letter paper: 600 dpi * 8.5 in = 5100 width
    #               600 dpi * 11 in = 6600 length

    # img.resize((5100, 6600)).save('test.pdf')
    img.save('test.pdf')

    print(scanner['mode'])
    print(scanner['resolution'])

    # Call sane.close() before sane.exit() to avoid a segmentation fault.
    scanner.close()

    sane.exit()
Example #15
0
 def exit(self):
     print "exiting"
     sane.exit()
Example #16
0
#!/usr/bin/python
import sane

def grab_image(cam):
	cam.mode = 'color'
	cam.start()
	return cam.snap()

sane.init()
webcam = sane.open('v4l:/dev/video0')
ones = 0
zeroes = 0
bstring = ''
for i in range(100):
	img = grab_image(webcam)
	data = list(img.getdata())
	for value in data:
		if value[2]%2 == 0:
			zeroes += 1
			bstring += '0'
		else:
			ones += 1
			bstring += '1'
		if len(bstring) == 32:
			print int(bstring, 2)
			bstring = ''
webcam.close()
sane.exit()

Example #17
0
def Scan(x, y, ptID, pt_dir, file_name, device='hpaio:/usb/Officejet_4500_G510n-z?serial=CN078H70X905HR', mode='simplex'):
    sane.init()
    d = sane.get_devices()
    lt = "%s/EMR_outputs/%s/%s/%s-%s.pdf" % (settings.LINUXPATH, ptID, pt_dir, file_name, dateToday('file format'))
    at = "%s/EMR_outputs/%s/%s/%s-%s.pdf" % (settings.LINUXPATH, ptID, pt_dir, file_name, dateToday('file format'))
    wt = "%s\EMR_outputs\%s\%s\%s-%s.pdf" % (settings.WINPATH, ptID, pt_dir, file_name, dateToday('file format'))
    if mode == 'duplex':
	#check which scanner and then opens the HP which I use for scanning ID cards
	try:						#need try in case there is only one scanner attached
	    if d[1][1] == 'Hewlett-Packard':
		s = sane.open(d[1][0])
	    else:
		s = sane.open(d[0][0])
	except:
	    s = sane.open(d[0][0])
	s.mode = 'gray'
	s.resolution = 150
	s.br_x = x
	s.br_y = y
	image = s.scan()
	wx.MessageBox("Turn doc over in the scanner, then click 'OK'.", "", wx.OK)
	t = tempfile.mkstemp(suffix='.pdf')
	image.save(t[1])
	image2 = s.scan()
	t2 = tempfile.mkstemp(suffix='.pdf')
	image2.save(t2[1])
	inpt = PdfFileReader(open(t[1], 'rb'))
	inpt2 = PdfFileReader(open(t2[1], 'rb'))
	otpt = PdfFileWriter()
	otpt.addPage(inpt.getPage(0))
	otpt.addPage(inpt2.getPage(0))
	newfile = file(platformText(lt, at, wt), 'wb')
	otpt.write(newfile)
	s.close()
	os.remove(t[1])
	os.remove(t2[1])
	sane.exit()
    elif mode == 'ADF':
	if d[1][1] == 'Hewlett-Packard':
	    s = sane.open(d[1][0])
	else:
	    s = sane.open(d[0][0])
	s.mode = 'gray'
	s.resolution = 150
	s.br_x = x
	s.br_y = y
	msg = wx.MessageDialog(None, "Would you like an ADF Scan?", "", style=wx.YES_NO)
	otpt = PdfFileWriter()
	while msg.ShowModal() == wx.ID_YES:
	    image = s.multi_scan()
	    t = tempfile.mkstemp(suffix='.pdf')
	    image.save(t[1])
	    inpt = PdfFileReader(open(t[1], 'rb'))
	    otpt.addPage(inpt.getPage(0)) 
	    #s.cancel()
	newfile = file(platformText(lt, at, wt), 'wb')
	otpt.write(newfile)
	s.close()
	os.remove(t[1])
	sane.exit()    
    else:
	try:						#need try in case there is only one scanner attached
	    if d[1][1] == 'Hewlett-Packard':
		s = sane.open(d[1][0])
	    else:
		s = sane.open(d[0][0])
	except:
	    s = sane.open(d[0][0])
	s.mode = 'gray'
	s.resolution = 150
	s.br_x = x
	s.br_y = y
	image = s.scan()
	image.save(platformText(lt, at, wt))
	s.close()
	sane.exit()
Example #18
0
    def scan(  # pylint: disable=too-many-branches
            self, notebook: models.Notebook,
            pages_queue: collections.deque) -> None:
        """Performs scanning with the given preferences.

        Args:
            notebook:
                A notebook which should be scanned.
            pages_queue:
                Numbers of pages that should be scanned.
        """
        if not self._conf.scanner_device:
            try:
                sane.init()

                self._callback.on_searching_for_devices()
                devices = list(itertools.starmap(Device, sane.get_devices()))

                if devices:
                    device_name = self._callback.on_set_device(devices)

                    if device_name:
                        self._conf.scanner_device = device_name
                    else:
                        self._callback.on_error('Device is not set.')
                else:
                    self._callback.on_error('No devices found.')

            except _sane.error as exception:
                log.exception(exception)
                self._callback.on_error('Failed to load the list of devices')

            except KeyboardInterrupt as exception:
                log.exception(exception)
                message = 'Keyboard interrupt while loading list of devices'
                self._callback.on_error(message)

            finally:
                sane.exit()

        device = None

        try:
            sane.init()

            device = self._get_device(self._conf.scanner_device)
            self._scan(device, notebook, pages_queue)

        except _sane.error as exception:
            log.exception(exception)
            self._callback.on_error(str(exception))

        except KeyboardInterrupt:
            log.error('Scan failed due to keyboard interrupt')
            self._callback.on_error('Keyboard interrupt')

        finally:
            if device:
                device.close()

            sane.exit()
 def closeScanner(self):
     """ We close the scanner """
     print self.scanner.close()
     print sane.exit()
Example #20
0
 def cleanup(self):
     logging.info('cleaning up SANE')
     self.disconnect()
     sane.exit()
Example #21
0
    def __init__(self, pat_rec):
        QtGui.QWidget.__init__(self)
        #super(MainWindow, self).__init__()
        uic.loadUi("mainfrm.ui", self)
        
        QtCore.QObject.connect(self.B_export, QtCore.SIGNAL('clicked()'), self.onB_export)
        QtCore.QObject.connect(self.B_help, QtCore.SIGNAL('clicked()'), self.onB_help)
        QtCore.QObject.connect(self.B_scan, QtCore.SIGNAL('clicked()'), self.onB_scan)
        QtCore.QObject.connect(self.B_exit, QtCore.SIGNAL('clicked()'), self.onB_exit)

        self.pat_rec = pat_rec
        self.setWindowTitle(u'Пациент: '+self.pat_rec["pat_fio"])
        #self.l_pat_name.setText(u"...")        #self.l_pat_name.setText(self.pat_rec["pat_fio"]+u"\nА/К:"+self.pat_rec["pat_reg"])
        self.DrawCurrStatus()
        
        #self.imageLabel = QtGui.QLabel(self)        #self.imageLabel.resize(370, 120)
        self.imageLabel.move(10, 220)
        self.imageLabel.setText(u"...")
        
        #self.labelHelp.setText(u"<b>Справка </b>")        QtCore.QObject.connect(self.labelHelp,QtCore.SIGNAL("click()"), self.changeEdit)
        
        self.comboBox.addItem(u'Направление');
        self.comboBox.addItem(u'Другое...');
        self.lineEdit.setDisabled(True)
        QtCore.QObject.connect(self.comboBox,QtCore.SIGNAL("currentIndexChanged(int)"), self.changeEdit)
        
        self.DrawPreview("./logo.jpg")
        self.listWidget.itemSelectionChanged.connect(self.RepaintPreview)
        self.progressBar.reset()
        self.progressBar.hide()
        self.setWindowFlags(self.windowFlags() | QtCore.Qt.WindowStaysOnTopHint)
        
        self.scanthread = scannerThread()
        self.connect(self.scanthread, QtCore.SIGNAL('errScan'), self.errScan )
        self.connect(self.scanthread, QtCore.SIGNAL('scanFinished'), self.scanOk )
        self.connect(self.scanthread, QtCore.SIGNAL('scanCancelled'), self.scanCancelled )

        self.activateWindow()
        self.show()
          
        tv=os.getenv('TMP') or os.getenv('TEMP') or os.getenv('TMPDIR')
        if not tv: tv= os.getenv('HOME') or os.getenv('USERPROFILE') #tmp variable not found =:(  )
        if tv[-1:] != '/': tv=tv+'/' 
        self.dirpath=tv+str( time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime()) )

        if not os.path.exists(self.dirpath):
            try:
                os.makedirs(self.dirpath)
            except:
                #err=True
                self.dirpath=os.getenv("HOME")
                
        self.scanthread.threadInitialize(self.dirpath)
        
        # есть ли сканеры?
        sane_version = sane.init()
        scanners=sane.get_devices()        #        print "scanners", scanners
        if not scanners:
            self.errScan(u"Сканер не обнаружен, проверьте подключение сканера.")
            logging.error("MainWnd _init_: сканер не найден")
            sane.exit()
            return
Example #22
0
    def run(self):
        #print "rnning, wait"
        #import time
        #time.sleep(12)
        try:
            sane_version = sane.init()
            devs=sane.get_devices()
        except:  pass
        
        if not devs:
            #self.ScanNotFoundMess()            #self.DrawCurrStatus()
            self.emit( QtCore.SIGNAL('errScan'), u"Сканер не обнаружен, проверьте подключение." )
            logging.error("scannerThread: Сканер не обнаружен")
            sane.exit()
            return
        
        try:
            self.s = sane.open(devs[0][0])
        except:
            print "ошибка открытия сканера"
            #self.DrawCurrStatus()            #self.ScanNotFoundMess()
            self.emit( QtCore.SIGNAL('errScan'), u"Ошибка открытия сканера" )
            try:
                self.s.close()
                sane.exit()
            except: pass
            self.imWorking = False
            return 
            
        #print 'Device parameters:', s.get_parameters()
        #for opt in s.get_options():
        #    print opt
        
        self.s.mode = 'color'
        #self.s.resolution=130#150
        self.s.resolution=self.dpi
        #s.depth = 32
        #print 'Device parameters:', s.get_parameters()        #print 'Device options:', s.get_options()        #print 'Device options:', s.optlist

        self.imWorking = True
        try:
            #self.s.start()
            im=self.s.scan()
        except:  # _sane.Error, se:            #print se
            self.emit( QtCore.SIGNAL('errScan'), u"Ошибка сканирования" )
            self.imWorking = False
            return #?
        
        #im=self.s.snap() #заюзать кутэ
        #import ImageQt
        #image = ImageQt.ImageQt(im)
        
        self.s.close()
        sane.exit()

        #im.show()
        filename=self.dirpath+'/'+str( time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime()) )+'.jpg'
        im = self.autocrop2(im)
        im.save(filename)
        self.emit( QtCore.SIGNAL('scanFinished'), QtCore.QString(filename ))
        #
        #image.save(QtCore.QString(filename+'111'),"jpg",70)
        #
        
         #тестовая секция
        #filename =u"это имя файла.жпег"
        #self.emit( QtCore.SIGNAL('scanFinished'),QtCore.QString(filename) )
        #тестовая секция
        
        self.imWorking = False