Ejemplo n.º 1
0
    def scan(self, event):
        self.id = self.control.GetValue()

        self.numPages = int(self.control2.GetValue())

        #if self.numPages < 1:
        #	self.control.SetValue("")
        #	return

        if not self.manager:
            self.manager = twain.SourceManager(self.GetHandle())
            if not self.manager:
                return

            self.manager.SetCallback(self.onEvent)

        if not self.scanner:
            self.scanner = self.manager.OpenSource("Network ScanGear Ver.2.1")
            if not self.scanner:
                return

        try:
            if self.radio1.GetSelection() == 0:
                self.scanner.SetCapability(twain.ICAP_SUPPORTEDSIZES, 4,
                                           11)  # A3 pages
            else:
                self.scanner.SetCapability(twain.ICAP_SUPPORTEDSIZES, 4,
                                           1)  # A4 pages
        except:
            #close and start again
            self.manager.destroy()
            self.manager = None
            self.manager = twain.SourceManager(self.GetHandle())
            self.manager.SetCallback(self.onEvent)
            self.scanner.destroy()
            self.scanner = None
            self.scanner = self.manager.OpenSource("Network ScanGear Ver.2.1")
            if self.radio1.GetSelection() == 0:
                self.scanner.SetCapability(twain.ICAP_SUPPORTEDSIZES, 4,
                                           11)  # A3 pages
            else:
                self.scanner.SetCapability(twain.ICAP_SUPPORTEDSIZES, 4,
                                           1)  # A4 pages

        if self.radio2.GetSelection() == 0:
            self.scanner.SetCapability(twain.CAP_DUPLEXENABLED, 4, 1)
        else:
            self.scanner.SetCapability(twain.CAP_DUPLEXENABLED, 4, 0)
        #self.scanner.SetCapability(twain.CCAP_CEI_SCANSPEED, 4, 1) # Scanning speed
        #self.scanner.SetCapability(0x8001, 2, 1) # Skip blank pages
        self.scanner.RequestAcquire(False)
Ejemplo n.º 2
0
    def test_scan(self):
        import twain
        root = tkinter.Tk()
        root.title('scan.py')
        logger.info('creating source manager')
        sm = twain.SourceManager(root)
        logger.info('opening source')
        ss = sm.open_source()  # this posts a modeless dialog...
        logger.info('request acquire')
        ss.request_acquire(show_ui=False, modal_ui=True)
        handles = []
        more = 1
        try:
            logger.info('transferring image')
            handle, more = ss.xfer_image_natively()
            handles.append(handle)
        except twain.excDSTransferCancelled:
            logger.info('cancelled')
            pass
        while more != 0:
            try:
                logger.info('transferring image')
                handle, more = ss.xfer_image_natively()
                handles.append(handle)
            except twain.excDSTransferCancelled:
                logger.info('cancelled')
                more = 0

        logger.info('transfer complete')
        index = 0
        curr_folder = os.path.dirname(__name__)
        for handle in handles:
            twain.dib_to_bm_file(handle, os.path.join(curr_folder, "{}.bmp".format(index)))
            twain.global_handle_free(handle)
            index += 1
Ejemplo n.º 3
0
    def _open(self):
        self._src_manager = twain.SourceManager(0)
        # self._src_manager.SetCallback(self.onTwainEvent)

        self._scanner = self._src_manager.OpenSource(self._source_name)
        self._scanner.SetCapability(twain.ICAP_YRESOLUTION, twain.TWTY_FIX32,
                                    200.0)
Ejemplo n.º 4
0
def twa():
    print(twain.version())

    #   scanners = twain.SourceManager(root).source_list

    #   ds = scanners[0]
    try:
        dso = twain.SourceManager(root).open_source(settings.DEVICE_BYTES)
    except:
        print('Aaaaaaaaaaaaaahhh')

    print(dso.get_capability_current(twain.ICAP_MINIMUMWIDTH))
    print(dso.get_capability_current(twain.ICAP_MINIMUMHEIGHT))
    print(dso.get_capability_current(twain.ICAP_PHYSICALWIDTH))
    print(dso.get_capability_current(twain.ICAP_PHYSICALHEIGHT))
    print(dso.get_capability_current(twain.ICAP_FRAMES))

    dso.set_capability(twain.ICAP_FRAMES, twain.TWTY_FRAME, settings.SCAN_AREA)
    #    OR
    #    dso.set_image_layout((0.9,0.6,3.8,1.6))

    dso.set_capability(twain.ICAP_UNITS, twain.TWTY_INT16, settings.UNITS)
    dso.set_capability(twain.ICAP_PIXELTYPE, twain.TWTY_INT16,
                       settings.PIXEL_TYPE)
    #    dso.set_image_layout(settings.SCAN_AREA)

    try:
        dso.acquire_file(before=GetName, show_ui=False)
    except:
        print('ooooooooooohhhhhhhh')
        dso.close()

    dso.close()
    print(dso.file_xfer_params)
Ejemplo n.º 5
0
def multi_scan_process(deviceId='', color='gray', capability=1):
    sm = twain.SourceManager(0)
    devices = sm.GetSourceList()
    ss = sm.OpenSource(devices[deviceId])

    try:
        # set kapabilitas menjadi ADR (Feeder)
        ss.SetCapability(twain.CAP_FEEDERENABLED, twain.TWTY_BOOL, True)
        # set output pixel twain
        # ini berfungsi agar OCR bisa membaca lebih jelas
        # jika kurang dari 1500px maka tidak akan jelas
        if (capability == 2):
            ss.SetCapability(twain.ICAP_YRESOLUTION, twain.TWTY_FIX32, 300.0)
            ss.SetCapability(twain.ICAP_XRESOLUTION, twain.TWTY_FIX32, 300.0)
        if (capability == 1):
            ss.SetCapability(twain.ICAP_YRESOLUTION, twain.TWTY_FIX32, 200.0)
            ss.SetCapability(twain.ICAP_XRESOLUTION, twain.TWTY_FIX32, 200.0)
        if (capability == 0):
            ss.SetCapability(twain.ICAP_YRESOLUTION, twain.TWTY_FIX32, 100.0)
            ss.SetCapability(twain.ICAP_XRESOLUTION, twain.TWTY_FIX32, 100.0)
    except Exception as e:
        print str(e.message)

    # print "acquire image"
    ss.RequestAcquire(0, 0)

    # looping untuk memeriksa apakah masih ada
    # file / document pada feeder
    while _next(ss):
        # jika error maka akan keluar dari loop scanner
        if (_capture(ss) != True):
            break
Ejemplo n.º 6
0
 def _open(self, resolution=0):
     self._src_manager = twain.SourceManager(0)
     self._scanner = self._src_manager.OpenSource(self._source_name)
     if resolution > 0:
         self._scanner.SetCapability(twain.ICAP_XRESOLUTION,
                                     twain.TWTY_FIX32, float(resolution))
         self._scanner.SetCapability(twain.ICAP_YRESOLUTION,
                                     twain.TWTY_FIX32, float(resolution))
Ejemplo n.º 7
0
 def get_scanner_name(self):
     """Get the available scanners"""
     self.sourceManager = twain.SourceManager(0)
     scanners = self.sourceManager.GetSourceList()
     if scanners:
         return scanners
     else:
         return None
Ejemplo n.º 8
0
 def getScanners(self):
     """Get available scanner from twain module
     """
     self.sourceManager = twain.SourceManager(0)
     scanners = self.sourceManager.GetSourceList()
     if scanners:
         return scanners
     else:
         return None
Ejemplo n.º 9
0
def open_scanner():
    sm = twain.SourceManager(0)
    sourcenames = sm.GetSourceList()
    if len(sourcenames) == 0:
        raise TwainutlError('No TWAIN sources available.')
    elif len(sourcenames) == 1:
        scanner = sm.OpenSource(sourcenames[0])
    else:
        scanner = sm.OpenSource() # select interactively
    return sm, scanner
Ejemplo n.º 10
0
 def test_dsm(self):
     import twain
     root = tkinter.Tk()
     root.title('scan.py')
     with twain.SourceManager(root) as sm:
         if len(sm.source_list) == 0:
             self.skipTest('No Sources present on the system')
         ds_name = sm.source_list[0]
         with sm.open_source(str(ds_name)) as ds:
             pass
Ejemplo n.º 11
0
    def open(self, name):
        self.manager = twain.SourceManager(0, ProductName=name)
        if not self.manager:
            return

        if self.source:
            self.source.destroy()
            self.source = None
        self.source = self.manager.OpenSource()
        if self.source:
            print "%s: %s" % (name, self.source.GetSourceName())
Ejemplo n.º 12
0
 def test_dsm(self):
     import twain
     root = tkinter.Tk()
     root.title('scan.py')
     with twain.SourceManager(root) as sm:
         if len(sm.source_list) == 0:
             self.skipTest('No Sources present on the system')
         ds_name = sm.source_list[0]
         with sm.open_source(str(ds_name)) as ds:
             val = ds.get_capability(twain.ICAP_YRESOLUTION)
             print(val)
             for v in val[1][2]:
                 print(v)
Ejemplo n.º 13
0
 def getScanners(self):
     """
     Get available scanner from twain module
     """
     if self.sourceManager is None:
         self.sourceManager = twain.SourceManager(0)
     scanners = [
         x for x in self.sourceManager.GetSourceList() if x != "SaneTwain"
     ]
     if scanners:
         return scanners
     else:
         return None
Ejemplo n.º 14
0
 def _refresh(self):
     self._devices = []
     src_manager = twain.SourceManager(0)
     devices = src_manager.GetSourceList()
     for dev in devices:
         scanner_id = 'twain-%s' % len(self._devices)
         try:
             scanner = Scanner(scanner_id, dev)
             self._devices.append(scanner)
         except Exception, exc:
             # XXX: What should be here?
             # Debuging to try to find out
             logging.debug(exc)
Ejemplo n.º 15
0
def single_scan_process(deviceId='', color='gray', capability=1):
    # create filename unique
    filename = name_unique() + ".bmp"
    # lokasi file
    loc_file = folder_upload + filename

    sm = twain.SourceManager(0)
    devices = sm.GetSourceList()
    ss = sm.OpenSource(devices[deviceId])
    ss.RequestAcquire(0, 0)
    # set output pixel twain
    # ini berfungsi agar OCR bisa membaca lebih jelas
    # jika kurang dari 1500px maka tidak akan jelas
    if (capability == 2):
        ss.SetCapability(twain.ICAP_YRESOLUTION, twain.TWTY_FIX32, 300.0)
        ss.SetCapability(twain.ICAP_XRESOLUTION, twain.TWTY_FIX32, 300.0)
    if (capability == 1):
        ss.SetCapability(twain.ICAP_YRESOLUTION, twain.TWTY_FIX32, 200.0)
        ss.SetCapability(twain.ICAP_XRESOLUTION, twain.TWTY_FIX32, 200.0)
    if (capability == 0):
        ss.SetCapability(twain.ICAP_YRESOLUTION, twain.TWTY_FIX32, 100.0)
        ss.SetCapability(twain.ICAP_XRESOLUTION, twain.TWTY_FIX32, 100.0)

    rv = ss.XferImageNatively()
    if rv:
        (handle, count) = rv
        twain.DIBToBMFile(handle, loc_file)

    color = color.lower()
    if color == 'color':
        pass
    if color == 'gray':
        # convert to grayscale
        image = cv2.imread(loc_file)
        im_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        cv2.imwrite(loc_file, im_gray)
    if color == 'black_white':
        # convert to grayscale
        image = cv2.imread(loc_file)
        im_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        (thresh, im_bw) = cv2.threshold(im_gray, 128, 255,
                                        cv2.THRESH_BINARY | cv2.THRESH_OTSU)
        cv2.imwrite(loc_file, im_bw)

    # encode to base64
    imagebase64 = convert_to_base64(loc_file)
    return [filename, imagebase64]
Ejemplo n.º 16
0
    def OnFilemenuitems0Menu(self, event):
        ## Connect
        exceptionTitle = None
        try:
            if self.SS:
                exceptionTitle = "Destroy Source Object"
                self.Log("del self.SS")
                self.Log("self.SS = None")
                del self.SS
                self.SS = None
                self.statusBar1.SetStatusText("3 - SourceManager Open", 2)
                self.statusBar1.SetStatusText("", 1)
            if not self.SM:
                exceptionTitle = "Open SourceManager"
                self.statusBar1.SetStatusText("Attempting SourceManager Open",
                                              0)
                self.Log("self.SM=twain.SourceManager(self.GetHandle())")
                self.SM = twain.SourceManager(self.GetHandle())
                self.Log("self.SM.SetCallback(self.OnTwainEvent)")
                self.SM.SetCallback(self.OnTwainEvent)
                if self.SM:
                    self.statusBar1.SetStatusText("3 - SourceManager Open", 2)

            exceptionTitle = "Open Source"
            self.statusBar1.SetStatusText("Attempting Connect", 0)
            self.Log("self.SS=self.SM.OpenSource()")
            self.SS = self.SM.OpenSource()
            if self.SS:
                self.statusBar1.SetStatusText("4 - Source Open", 2)
                self.statusBar1.SetStatusText(self.SS.GetSourceName(), 1)
                ## Display the source information
                self.statusBar1.SetStatusText("Connected", 0)
                self.Log("self.SS.GetIdentity()")
                dlg = dlgIdentity.wxDialog1(self)
                dlg.SetSourceInfo(self, self.SS.GetIdentity())
                dlg.ShowModal()
                dlg.Destroy()
                self.OnFilemenuitems3Menu(event)
                self.FileMenu.Enable(wxID_WXFRAME1FILEMENUITEMS1, True)
                self.FileMenu.Enable(wxID_WXFRAME1FILEMENUITEMS2, True)
                self.FileMenu.Enable(wxID_WXFRAME1FILEMENUITEMS3, True)
            else:
                self.statusBar1.SetStatusText("Connect Cancelled", 0)
        except:
            self.DisplayException(exceptionTitle)
Ejemplo n.º 17
0
    def OpenScanner(self,
                    mainWindow=None,
                    ProductName=None,
                    UseCallback=False):
        """Connect to the scanner"""
        if ProductName: self.ProductName = ProductName
        if mainWindow: self.mainWindow = mainWindow
        if not self.SM:
            self.SM = twain.SourceManager(self.mainWindow,
                                          ProductName=self.ProductName)
        if not self.SM:
            return
        if self.SD:
            self.SD.destroy()
            self.SD = None
        self.SD = self.SM.OpenSource()
        if self.SD:
            self.LogMessage(self.ProductName + ': ' + self.SD.GetSourceName())

        if UseCallback:
            self.SM.SetCallback(self.OnTwainEvent)
Ejemplo n.º 18
0
    def do_scan(self):
        global file
        Logger.info(self.logapp + 'My favourite - Scanning')
        try:
            dso = twain.SourceManager(root).open_source(settings.DEVICE_BYTES)
        except:
            Logger.info(self.logapp + 'Can\'t open scanner')

        dso.set_capability(twain.ICAP_FRAMES, twain.TWTY_FRAME,
                           settings.SCAN_AREA)
        dso.set_capability(twain.ICAP_UNITS, twain.TWTY_INT16, settings.UNITS)
        dso.set_capability(twain.ICAP_PIXELTYPE, twain.TWTY_INT16,
                           settings.PIXEL_TYPE)
        dso.set_image_layout(settings.SCAN_AREA)
        try:
            dso.acquire_file(before=GetName, show_ui=False)
        except:
            Logger.info(self.logapp + 'Something\'s gone wrong')
            dso.close()

        dso.close()

        self.background = file
        Logger.info(self.logapp + 'Scanned to ' + file)
Ejemplo n.º 19
0
 def start(self):
     lib = customLib.load_twain_dll()
     self.sourceManager = twain.SourceManager(1, dsm_name=lib)
Ejemplo n.º 20
0
 def initialize_scanner():
     Scanner.source_object = twain.SourceManager(0)
Ejemplo n.º 21
0
# Tell linearAct to intialize and wait for success
ser.write(INIT)
while ser.read() != INIT:
    print 'Waiting for linearAct to intialize... '
    time.sleep(.1)
print 'linearAct has initialized!'

# Move plate to initial location and wait for confirm
while ser.read() != READY:
    print 'Moving plate to initial position...'
    time.sleep(.1)
print 'Plate has arrived at its initial position!'

# Acquire image, move plate, and iterate
for n in range(nCols):
    sm = twain.SourceManager(0)

    print 'Scanning column ' + str(n + 1) + '/' + str(nCols) + '...'
    # Open the source using the string with the name of the scanner.
    # If you want to see available scanner names, just call this:
    #   sm.GetSourceList()
    # ...and you will get a list of all scanners connected to the computer.
    #
    # For testing:
    # sd = sm.OpenSource('TWAIN2 FreeImage Software Scanner 2.1')
    sd = sm.OpenSource('WIA-HP Scanjet G4050')

    #set resolution to 600dpi
    x_res = sd.SetCapability(twain.ICAP_XRESOLUTION, twain.TWTY_FIX32,
                             float(600))
    y_res = sd.SetCapability(twain.ICAP_YRESOLUTION, twain.TWTY_FIX32,
Ejemplo n.º 22
0
 def __init__(self, sc=None):
     self.sm = twain.SourceManager(0)
     if not sc:
         sc = self.sm.GetSourceList()[0]
     self.scanner = self.sm.OpenSource(bytes(sc, "utf-8"))
     self.typelookup = getTypeDict()
Ejemplo n.º 23
0
 def get_available():
     return twain.SourceManager(0).GetSourceList()
Ejemplo n.º 24
0
    def __init__(self, scanner=None, scanners_manager="twain", SM_HWND=0):

        if scanners_manager == "twain":
            self._SM = twain.SourceManager(SM_HWND)
            self._scanners = self._SM.GetSourceList()
            self._settings_list = {
                'Lightpath': [
                    twain.ICAP_LIGHTPATH, twain.TWTY_UINT16, 'options',
                    'Transmissive', twain.TWLP_TRANSMISSIVE, 'Reflective',
                    twain.TWLP_REFLECTIVE
                ],
                'Lighsource':
                [twain.ICAP_LIGHTSOURCE, twain.TWTY_UINT16, 'int', 0],
                'Unit': [
                    'options', 'Inches', twain.TWUN_INCHES, 'Centimeters',
                    twain.TWUN_CENTIMETERS, 'Pixels', twain.TWUN_PIXELS
                ],
                'Pixeltype': [
                    twain.ICAP_PIXELTYPE, twain.TWTY_UINT16, 'options', 'Gray',
                    twain.TWPT_GRAY, 'Color', twain.TWPT_RGB
                ],
                'Capability 32829': [32829, 4, 'int', 1],
                'Capability 32805': [32805, 6, 'bool', 0],
                'Capability 32793': [32793, 6, 'bool', 0],
                'Orientation': [
                    twain.ICAP_ORIENTATION, twain.TWTY_UINT16, 'options',
                    '90 degrees', twain.TWOR_ROT90, '0 degrees',
                    twain.TWOR_ROT0, '180 degrees', twain.TWOR_ROT180,
                    '270 degrees', twain.TWOR_ROT270
                ],
                'X-resolution':
                [twain.ICAP_XRESOLUTION, twain.TWTY_FIX32, 'float', 600],
                'Y-resolution':
                [twain.ICAP_YRESOLUTION, twain.TWTY_FIX32, 'float', 600],
                'Bit Depth':
                [twain.ICAP_BITDEPTH, twain.TWTY_UINT16, 'int', 8],
                'Contrast':
                [twain.ICAP_CONTRAST, twain.TWTY_FIX32, 'float', 25.0],
                'Brightness':
                [twain.ICAP_BRIGHTNESS, twain.TWTY_FIX32, 'float', 125.0],
                'Scnning area (TOP, LEFT, BOTTOM, RIGHT)':
                [None, None, 'float-list', '(0.0, 0.0, 11.69, 8.27)']
            }

        else:
            self._scanners = None
            self._settings_ilst = None

        self._treestore = gtk.TreeStore(str, str)

        for scanner in self._scanners:
            scanner_iter = self._treestore.append(None, [scanner, None])
            for key, item in self._settings_list.items():

                self._treestore.append(scanner_iter, [key, item[3]])

        gtk.TreeView.__init__(self, self._treestore)

        self._columns = []
        self._columns.append(gtk.TreeViewColumn('Setting'))
        self._columns.append(gtk.TreeViewColumn('Value'))

        for i, c in enumerate(self._columns):
            self.append_column(c)
            cell = gtk.CellRendererText()
            cell.connect("edited", self.verify_input)
            cell.connect("editing-started", self.guide_input)
            self._columns[i].pack_start(cell, True)
            self._columns[i].add_attribute(cell, 'text', i)
            cell.set_property('editable', i)

        self.show_all()
Ejemplo n.º 25
0
def get_devices():
    sm = twain.SourceManager(0)
    devices = sm.GetSourceList()
    return devices