Esempio n. 1
0
    def _detect_labels(self):
        scanner = zbar.Scanner()
        t0 = time.time()
        last_result_data = None
        for i in range(len(self._frames)):
            frame = self._frames_gray[i]
            results = scanner.scan(frame)
            results = filter(lambda x: x.type == u"QR-Code", results) 
            assert len(results) <= 1
            if len(results) == 0 or results[0].data == last_result_data:
                label = None
            else:
                last_result_data = results[0].data
                items = results[0].data.split()
                label = []
                for item in items:
                    x, y = item.split("_")
                    label.append(tuple((int(float(x)), int(float(y)))))

            self._labels.append(label)
    
            t1 = time.time()
            time_remain = datetime.timedelta(seconds=int((t1 - t0)/(i + 1)*(len(self._frames) - (i + 1))))
            print  "\rProcessing frame {0}/{1}, {2} remaining".format(i + 1, len(self._frames), time_remain),
    
        print ""
Esempio n. 2
0
def qr_position():
    #function return the x-position of the middle of the barcode
    rawCapture = PiRGBArray(camera, size=(camera_rows, camera_columns))
    for frame in camera.capture_continuous(rawCapture,
                                           format="bgr",
                                           use_video_port=True):
        image = frame.array
        image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        scanner = zbar.Scanner()
        #scanner.scan return multiple information about the barcode
        results = scanner.scan(image)
        rawCapture.truncate(0)
        if len(results) == 0:
            #when no barcode is detected the function returns 0
            return 0
        else:
            #results contains one element per detected barcode
            for result in results:
                ans = result.position
                x = 0
                for i in range(3):
                    #calculates the deviation using the positions of the barcodes corners
                    x = x + ans[i][0] - camera_rows / 2
                x = x / 4
                #also returns 0 when the badcode is perfectly central in front of the camera
                return x
Esempio n. 3
0
def ReadBarCode(CurrentImage):
    scanner = zbar.Scanner()
    results = scanner.scan(CurrentImage)
    barcode = ""
    for result in results:
        barcode = barcode + str(result.data)
    return barcode
Esempio n. 4
0
    def __init__(self):
        super().__init__("ros2senbay_publisher")
        self.pub_lst = {
            "TIME":
            self.create_publisher(Float32, "TIME", 10),
            "RPM":
            self.create_publisher(Float32, "RPM", 10),
            "SPEED":
            self.create_publisher(Float32, "SPEED", 10),
            "COOLANT_TEMP":
            self.create_publisher(Float32, "COOLANT_TEMP", 10),
            "DISTANCE_SINCE_DTC_CLEAR":
            self.create_publisher(Float32, "DISTANCE_SINCE_DTC_CLEAR", 10),
            "MAF":
            self.create_publisher(Float32, "MAF", 10),
            "INTAKE_TEMP":
            self.create_publisher(Float32, "INTAKE_TEMP", 10)
        }

        self.title = "ros2senbay"
        self.fps = 10
        self.timer = self.create_timer(1 / self.fps, self.timer_callback)
        infile = "resource/video.m4v"
        filepath = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                infile)
        self.cap = cv2.VideoCapture(filepath)
        self.scanner = zbar.Scanner()
        self.senbayData = SenbayData()
Esempio n. 5
0
 def verify_qrcode(self):
     capture = cv2.VideoCapture(0)
     print("Send KeyboardInterrupt (Ctrl+C) to abort verification.")
     try:
         while True:
             #Unfortunately manual abortion is not possible without a working GUI, see comment below -> Use Ctrl+C (KeyboardInterrupt) instead.
             if (cv2.waitKey(1) & 0xFF) == 'q':
                 print('Aborted verification.')
                 return False
             ret, frame = capture.read()
             # Currently not possible to display the camera image frame due to a bug/incompatibility in cv2
             #cv2.imshow('Camera', frame)
             gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
             img = Image.fromarray(gray)
             res = zbar.Scanner().scan(img)
             for decoded in res:
                 try:
                     if base64.b64decode(
                             decoded.data) == self.combined_fingerprint:
                         print("Fingerprint succesfully verified!")
                         return True
                 except binascii.Error:
                     print(
                         "Could not read fingerprint. It is not base64 encoded. Data read from QRCode:\n{}"
                         .format(decoded.data))
                     return False
                 print(
                     "Fingerprints did not match. You are using different certificates. Update the certificates retrieved from PKI at both cliens. If the problem persists, it might indicate a Man-in-the-Middle Attack."
                 )
                 return False
     except KeyboardInterrupt:
         print('\nAborted verification.')
         return False
def main(ip_address: str, scanner_logic: ScannerLogic, show_video=False):
    cap = cv2.VideoCapture(0)
    scanner = zbar.Scanner()
    api = BarcodedAPI(ip_address)
    while True:
        ret, img = cap.read()
        if img is None:
            print("Failed to get camera", file=sys.stderr)
            sys.exit(1)

        results = read_barcode(scanner, img)
        for result in results:
            # TODO: Incorporate the result.quality into the scanner logic?
            barcode, others = scanner_logic.input(result.data)
            if barcode is not None:
                print(barcode, others)
                feedback.play_sound()
                result = api.add_barcode(barcode.decode("utf-8"))

                if result is not None:
                    print(result)
                else:
                    print("Could not send barcode to server.", file=sys.stderr)

        if show_video:
            for res in results:
                draw_barcode(img, res.position)
            cv2.imshow("input", img)

        key = cv2.waitKey(10)
        if key == 27:
            break

    cv2.destroyAllWindows()
    cv2.VideoCapture(0).release()
    def __init__(self, wrapped):
        self.wrapped = wrapped

        self.url = 'http://192.168.122.1:10000/sony/camera'
        self.id = 1
        self.action_space = wrapped.action_space
        self.observation_space = spaces.Box(
            np.array([0.0] * 19), np.array([1.0] * 19)
        )  # 3 object detectors (one for each color), giving x, y, size, then one-hot encoding of the largest barcode visible (0 by default)

        self._scanner = zbar.Scanner()
        self._centroids = [None] * 3
        self._areas = [0.0] * 3

        # Connect to the camera
        r = self.send_basic_cmd("getVersions")
        print('Sony Camera version %s' % r['result'][0][0])

        # Enable steady mode to have a smaller field of view
        self.send_basic_cmd('setSteadyMode', ['on'])

        # Open liveview stream
        self.send_basic_cmd('stopLiveview')
        r = self.send_basic_cmd('startLiveview')
        self._stream = urllib.urlopen(r['result'][0])

        self._thread = LiveThread(self._stream)
        self._thread.start()

        print('Liveview stream opened')
Esempio n. 8
0
    def _detect_labels(self):
        scanner = zbar.Scanner()
        t0 = time.time()
        for i in range(len(self._frames)):
            frame = self._frames_gray[i]
            results = scanner.scan(frame)
            results = filter(lambda x: x.type == u"QR-Code", results)
            assert len(results) <= 1
            if len(results) == 0:
                label = None
            else:
                items = results[0].data.split()
                # 04/07/2018: add a dummy event charactor because new sensys18 result format doesn't have event encoded
                if '_' in items[0]:
                    items = ['n'] + items
                event = items[0]
                label = [event]
                for item in items[1:]:
                    x, y = item.split("_")
                    label.append(tuple((int(float(x)), int(float(y)))))

            self._labels.append(label)

            t1 = time.time()
            time_remain = datetime.timedelta(seconds=int((t1 - t0) / (i + 1) *
                                                         (len(self._frames) -
                                                          (i + 1))))
            print "\rProcessing frame {0}/{1}, {2} remaining".format(
                i + 1, len(self._frames), time_remain),

        print ""
Esempio n. 9
0
    def doit(x=4, w=64):

        try:
            import zbar
        except ImportError:
            raise pytest.skip('need zbar-py module')
        import numpy
        from PIL import ImageOps

        # see <http://qrlogo.kaarposoft.dk/qrdecode.html>

        img = cap_image()
        img = img.crop((x, 0, x + w, w))
        img = ImageOps.expand(img, 16, 255)
        img = img.resize((256, 256))
        img.save('debug/last-qr.png')
        #img.show()

        scanner = zbar.Scanner()
        np = numpy.array(img.getdata(), 'uint8').reshape(img.width, img.height)

        for sym, value, *_ in scanner.scan(np):
            assert sym == 'QR-Code', 'unexpected symbology: ' + sym
            value = str(value, 'ascii')
            return value

        raise pytest.fail('qr code not found')
Esempio n. 10
0
def scan(url):
    file_path = './tmp.jpg'

    try:
        print("Downloading image temporarily to {}".format(file_path))
        urllib.request.urlretrieve(url, file_path)
        image = Image.open(file_path)

        print("Start scanning")
        image_array = numpy.array(image.getdata(), numpy.uint8)
        scanner = zbar.Scanner()

        results = scanner.scan(image_array)
        print("Finished scanning")

        if len(results) > 0:
            result = results[0]
            barcode = result.data.decode('utf-8')
            print("Scanned barcode: {}".format(barcode))

            return barcode

    except Exception as e:
        print("ERROR while scanning image")

    return -1
Esempio n. 11
0
    def _add_otp(self, name=None, otp_type=None, secret=None):
        if not name:
            self.q.put([Action.ask_input, _("Add OTP to which password?"), "", "add_otp"])
        elif not otp_type:
            screenshot = pyscreenshot.grab(childprocess=False).convert('L')
            qr_codes = zbar.Scanner().scan(screenshot)
            autodetected = 0
            for qr_code in qr_codes:
                qr_data = qr_code.data.decode()
                try:
                    pyotp.parse_uri(qr_data)
                except ValueError:
                    continue

                autodetected += 1
                self._append_password(name, qr_data)

            if autodetected == 0:
                self.q.put([Action.add_error, _("Could not detect any valid OTP QR codes on your screen. Continuing with manual configuration...")])
                self.q.put([Action.ask_choice, _("Use which OTP type?"), ["TOTP", "HOTP"], "add_otp {}".format(name)])
            else:
                self.q.put([Action.add_message, _("Detected and added {} valid OTP QR code(s) on your screen.").format(str(autodetected))])
                return
        elif not secret:
            self.q.put([Action.ask_input, _("What is the OTP secret?"), "", "add_otp {} {}".format(name, otp_type)])
        else:
            if otp_type == "TOTP":
                otp_uri = pyotp.TOTP(secret).provisioning_uri()
            elif otp_type == "HOTP":
                otp_uri = pyotp.HOTP(secret).provisioning_uri()
            else:
                return

            self._append_password(name, otp_uri)
Esempio n. 12
0
    def _add_otp(self, name=None, otp_type=None, secret=None):
        if not hasattr(pyotp, "parse_uri"):
            self.q.put([
                Action.critical_error,
                _("pyotp lib doesn't support this yet")
            ])
            return
        if not name:
            self.q.put([
                Action.ask_input,
                _("What password should OTP be added to?"), "", "add_otp"
            ])
        elif not otp_type:
            screenshot = pyscreenshot.grab(childprocess=False).convert('L')
            qr_codes = zbar.Scanner().scan(screenshot)
            autodetected = 0
            for qr_code in qr_codes:
                qr_data = qr_code.data.decode()
                try:
                    pyotp.parse_uri(qr_data)
                except ValueError:
                    continue

                autodetected += 1
                self._append_password(name, qr_data)

            if autodetected == 0:
                self.q.put([
                    Action.add_error,
                    _("No valid OTP QR codes detected on your screen. Configuring manually…"
                      )
                ])
                self.q.put([
                    Action.ask_choice,
                    _("Which OTP type should be used?"), ["TOTP", "HOTP"],
                    "add_otp {}".format(name)
                ])
            else:
                self.q.put([
                    Action.add_message,
                    _("Detected and added {} valid OTP QR code(s) on your screen."
                      ).format(str(autodetected))
                ])
                return
        elif not secret:
            self.q.put([
                Action.ask_input,
                _("What is the OTP secret?"), "",
                "add_otp {} {}".format(name, otp_type)
            ])
        else:
            if otp_type == "TOTP":
                otp_uri = pyotp.TOTP(secret).provisioning_uri()
            elif otp_type == "HOTP":
                otp_uri = pyotp.HOTP(secret).provisioning_uri()
            else:
                return

            self._append_password(name, otp_uri)
Esempio n. 13
0
def __scan_barcode(image_filename):
    scanner = zbar.Scanner()
    image_as_numpy_array = __imread(image_filename)
    results = scanner.scan(image_as_numpy_array)
    if not results:
        return None
    for result in results:
        return from_qr_code_format(result.data.decode('ascii'))
Esempio n. 14
0
def qr_scanner():
    global frame_cap
    frame = cv2.resize(frame_cap.frame, (640, 480))
    cv2.imshow('Tello', frame)
    qr_ret = False
    qr_space = 0
    qr_data = 0
    qr_Xpos = 0
    qr_Ypos = 0
    hasan = zbar.Scanner()
    qr_farame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    qr_results = hasan.scan(qr_farame)
    for result in qr_results:
        qr_ret = True
        for i in result.position:
            a_point, b_point = i
            cv2.circle(qr_farame, (a_point, b_point), 4, (0, 255, 255), -1)
        result.position.sort(key=myFunc)
        a1, b1 = result.position[0]
        a2, b2 = result.position[1]
        a3, b3 = result.position[2]
        a4, b4 = result.position[3]
        dist1 = math.sqrt((b2 - b1)**2 + (a2 - a1)**2)
        dist2 = math.sqrt((b4 - b3)**2 + (a4 - a3)**2)
        if dist1 > dist2:
            qr_space = 2
            # wall
        else:
            qr_space = 1
            # grund
        qr_Xpos = (a1 + a2 + a3 + a4) / 4
        qr_Ypos = (b1 + b2 + b3 + b4) / 4
        qr_data = result.data.decode()
        print('qr detected ' + str(qr_data) + str(qr_space))
        print('qr detected ' + str(qr_data) + str(qr_space))
        print('qr detected ' + str(qr_data) + str(qr_space))
        print('qr detected ' + str(qr_data) + str(qr_space))
        print('qr detected ' + str(qr_data) + str(qr_space))
        print('qr detected ' + str(qr_data) + str(qr_space))
        print('qr detected ' + str(qr_data) + str(qr_space))
        print('qr detected ' + str(qr_data) + str(qr_space))
        print('qr detected ' + str(qr_data) + str(qr_space))
        print('qr detected ' + str(qr_data) + str(qr_space))
        print('qr detected ' + str(qr_data) + str(qr_space))
        print('qr detected ' + str(qr_data) + str(qr_space))
        print('qr detected ' + str(qr_data) + str(qr_space))
        print('qr detected ' + str(qr_data) + str(qr_space))
        print('qr detected ' + str(qr_data) + str(qr_space))
        print('qr detected ' + str(qr_data) + str(qr_space))
        print('qr detected ' + str(qr_data) + str(qr_space))
        print('qr detected ' + str(qr_data) + str(qr_space))
        print('qr detected ' + str(qr_data) + str(qr_space))
        print('qr detected ' + str(qr_data) + str(qr_space))
        print('qr detected ' + str(qr_data) + str(qr_space))
        print('qr detected ' + str(qr_data) + str(qr_space))

    return qr_ret, qr_data, qr_space, qr_Xpos, qr_Ypos
Esempio n. 15
0
    def __init__(self):
        super().__init__()
        self._frames_buffer = []
        self.__alive = True

        self.__last_code = None
        self.__last_time = time.time()

        self.__scanner = zbar.Scanner()
 def load(self, path, filename):
     loaded_code = cv2.imread(os.path.join(path, filename[0]), 0)
     scanner = zbar.Scanner()
     results = scanner.scan(loaded_code)
     for result in results:
         print(result.type, result.data, result.quality, result.position)
         byteData = result.data
         app = App.get_running_app()
         app.txtReadData = byteData.decode("UTF-8")
Esempio n. 17
0
 def __init__(self, cam, exit_event: threading.Event):
     self._cam = cam
     self._thread_exit = exit_event
     self._scan_queue = queue.LifoQueue(maxsize=2)
     self._code_queues = set()
     self._img_queues = set()
     self._scanner = zbar.Scanner()
     self._detect_t = threading.Thread(target=self.fill_cam_queue,
                                       daemon=True)
     self._scan_t = threading.Thread(target=self.scan_tf, daemon=True)
Esempio n. 18
0
    def __init__(self, name="Squirrel LPS"):
        self.name = name

        self.scanner = zbar.Scanner()

        self.frame = 0
        self.objects = {}
        self.reference = None

        self.frame_timestamp = time.time()
Esempio n. 19
0
        def kgen(cam):
            """Video streaming generator function."""
            while True:
                _cam = settings.camera.get_cam(cam)

                img, _ = _cam.getFrame(calibrate=True)

                zimg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
                scanner = zbar.Scanner()
                results = scanner.scan(zimg)
                for result in results:
                    r = {
                        'type': result.type,
                        'data': result.data.decode("ascii"),
                        'quality': result.quality,
                        'absolute-position-px': {
                            'topleft': result.position[0],
                            'topright': result.position[1],
                            'bottomright': result.position[2],
                            'bottomleft': result.position[3]
                        }
                    }
                    for p in result.position:
                        cv2.circle(img, (p[0], p[1]), 5, (0, 255, 0), -1)
                    center, width, height, angle = rotation(result.position)
                    cv2.circle(img, (int(center[0]), int(center[1])), 5,
                               (0, 255, 0), -1)
                    r['center'] = center
                    r['width'] = width
                    r['height'] = height
                    r['angle'] = angle
                    r['relative-position-px'] = {
                        'topleft': [
                            result.position[0][0] - center[0],
                            result.position[0][1] - center[1]
                        ],
                        'topright': [
                            result.position[1][0] - center[0],
                            result.position[1][1] - center[1]
                        ],
                        'bottomright': [
                            result.position[2][0] - center[0],
                            result.position[2][1] - center[1]
                        ],
                        'bottomleft': [
                            result.position[3][0] - center[0],
                            result.position[3][1] - center[1]
                        ]
                    }
                    img = subimage(img, (center[0], center[1]), angle)
                ret, measured_img = cv2.imencode('.jpg', img)

                yield (b'--jpgboundary\r\n'
                       b'Content-Type: image/jpeg\r\n\r\n' +
                       bytearray(measured_img) + b'\r\n')
Esempio n. 20
0
def scan_barcode(image_filename):
    scanner = zbar.Scanner()
    print('scanning image ' + image_filename)
    image_as_numpy_array = imread(image_filename)
    results = scanner.scan(image_as_numpy_array)
    if not results:
        print('  No barcode found.')
    for result in results:
        # zbar returns barcode data as byte array, so decode byte array as ascii
        print('  type: {}, quality: {}'.format(result.type, result.quality))
        return from_qr_code_format(result.data.decode('ascii'))
Esempio n. 21
0
def getQR(img):
    img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
    scanner = zbar.Scanner()
    result = scanner.scan(img)
    print(result)
    if len(result) > 0:
        code = result[0].data
        code = code.replace("padproject.nd.edu/?s=", "")
        code = code.replace("padproject.nd.edu/?t=", "")
        return code
    return "Unknown"
Esempio n. 22
0
    def get(self, cam):
        """
        Get the rotation and midpoint by scanning qr code in field of view
        """
        cam = settings.camera.get_cam(cam)

        img, _ = cam.getFrame(calibrate=True)

        zimg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        scanner = zbar.Scanner()
        results = scanner.scan(zimg)
        ar = []
        for result in results:
            r = {
                'type': result.type,
                'data': result.data.decode("ascii"),
                'quality': result.quality,
                'absolute-position-px': {
                    'topleft': result.position[0],
                    'topright': result.position[1],
                    'bottomright': result.position[2],
                    'bottomleft': result.position[3]
                }
            }
            center, width, height, angle = rotation(result.position)
            r['center'] = center
            r['width'] = width
            r['height'] = height
            r['angle'] = angle
            r['relative-position-px'] = {
                'topleft': [
                    result.position[0][0] - center[0],
                    result.position[0][1] - center[1]
                ],
                'topright': [
                    result.position[1][0] - center[0],
                    result.position[1][1] - center[1]
                ],
                'bottomright': [
                    result.position[2][0] - center[0],
                    result.position[2][1] - center[1]
                ],
                'bottomleft': [
                    result.position[3][0] - center[0],
                    result.position[3][1] - center[1]
                ]
            }
            ar.append(r)
            if hasattr(cam, 'ppmm'):
                r['ar'] = cam.ppmm
            else:
                r['ppmm'] = -1
        return ar
Esempio n. 23
0
def findDrone(imageL, imageR):
    LdroneInfo, RdroneInfo, LotherCodes, RotherCodes = [], [], [], []
    bothFound = False
    # create a reader
    scanner = zbar.Scanner()

    resultsL = scanner.scan(imageL)
    resultsR = scanner.scan(imageR)

    #stringBuilder = ""

    if len(resultsL) > 0 and len(resultsR) > 0:
        bothFound = True
        for L in resultsL:
            if (L.data == "Left") or (L.data == "Right") or (
                    L.data == "Front") or (L.data == "Back"):
                LdroneInfo.append(L.data)
                LdroneInfo.append(L.position)
            else:
                LotherCodes.append(L.data)
                LotherCodes.append(L.position)
        for R in resultsR:
            if (R.data == "Left") or (R.data == "Right") or (
                    R.data == "Front") or (R.data == "Back"):
                RdroneInfo.append(R.data)
                RdroneInfo.append(R.position)
            else:
                RotherCodes.append(R.data)
                RotherCodes.append(R.position)
    elif len(resultsL) > 0:
        for L in resultsL:
            if (L.data == "Left") or (L.data == "Right") or (
                    L.data == "Front") or (L.data == "Back"):
                LdroneInfo.append(L.data)
                LdroneInfo.append(L.position)
            else:
                LotherCodes.append(L.data)
                LotherCodes.append(L.position)
    elif len(resultsR) > 0:
        for R in resultsR:
            if (R.data == "Left") or (R.data == "Right") or (
                    R.data == "Front") or (R.data == "Back"):
                RdroneInfo.append(R.data)
                RdroneInfo.append(R.position)
            else:
                RotherCodes.append(R.data)
                RotherCodes.append(R.position)
    #else:
    #print "QR not found"
    return bothFound, LdroneInfo, RdroneInfo, LotherCodes, RotherCodes
Esempio n. 24
0
def locate_qr_code(image):
    """Find the location of a QR code in the image."""
    scanner = zbar.Scanner()  # Memory leaks somewhere, so be careful here
    gray = image.convert('L')

    results = scanner.scan(gray)
    if results:
        return bbox(results)

    results = locate_qr_code_using_slider(gray, scanner)
    if results:
        return results

    return None
Esempio n. 25
0
def barcodescanner():
    raw_capture = PiRGBArray(camera, size=(camera_rows,camera_columns))
    # grab an image from the camera
    camera.capture(raw_capture, format="bgr")
    image = raw_capture.array
    image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    scanner = zbar.Scanner()
    results = scanner.scan(image)
    raw_capture.truncate(0)
    if len(results) == 0:
        return 0
    else:
        for result in results:
            return result.data.decode("utf-8")
Esempio n. 26
0
def scan_for_isbn(image_file):
    """A method to extract the ISBN from an image of the barcode.

    :param image_file:
        A filename (string), pathlib.Path object or a file object.
        The file object must implement :py:meth:`~file.read`,
        :py:meth:`~file.seek`, and :py:meth:`~file.tell` methods,
        and be opened in binary mode.
    """
    isbns = []

    max_length = 850
    scanner = zbar.Scanner(config=[('ZBAR_ISBN13', 'ZBAR_CFG_ENABLE', 1)])

    # import image, converting to black and white
    image = Image.open(image_file).convert('L')

    # resize big images for speed and improved scanning in most cases
    if [d > max_length for d in image.size]:
        image = image.resize((500, 700), Image.ANTIALIAS)

    # first scan image as it is
    img_arr = np.fromstring(image.tobytes(), dtype=np.uint8)
    img_arr = img_arr.reshape((image.size[1], image.size[0]))

    results = scanner.scan(img_arr)

    # if no ISBN or non-ISBN code found, enhance contrast and scan again
    if not results or not all(r.type == 'ISBN-13' for r in results):
        image = ImageEnhance.Contrast(image).enhance(2)

        img_arr = np.fromstring(image.tobytes(), dtype=np.uint8)
        img_arr = img_arr.reshape((image.size[1], image.size[0]))

        results = scanner.scan(img_arr)

    # if no ISBN or non-ISBN codes found, change size and scan again
    if not results or not all(r.type == 'ISBN-13' for r in results):
        image = image.resize((700, 500), Image.ANTIALIAS)

        img_arr = np.fromstring(image.tobytes(), dtype=np.uint8)
        img_arr = img_arr.reshape((image.size[1], image.size[0]))

        results = scanner.scan(img_arr)

    if results:
        for result in [r for r in results if r.type == 'ISBN-13']:
            isbns.append(result.data.decode('ascii'))

    return isbns
Esempio n. 27
0
    def code(file_path=None, barcode_type='QRCODE'):

        image = read_image(file_path)

        if len(image.shape) == 3:
            image = zbar.misc.rgb2gray(image)

        barcodes = []

        scanner = zbar.Scanner()
        results = scanner.scan(image)
        for barcode in results:
            barcodes.append(barcode.data.decode(u'utf-8'))

        return barcodes
def qrScan(file_name):
    scanner = zbar.Scanner()
    #打开zbar解析配置
    scanner.parse_config('enable')
    #打开需要扫描的二维码
    img = Image.open(file_name).convert('L')
    #获取二维码图片的宽和高
    w, h = img.size
    #将图片数据传入扫描器
    zimg = zbar.Image(w, h, 'Y800', img.tobytes())
    scanner.scan(zimg)
    for s in zimg:
        if not s.data:
            print "error:This is not QRcode!\nPlease select another photo."
        else:
            print s.data.decode('utf-8').encode('gbk')
Esempio n. 29
0
    def scan(self, aframe):
        imgray = cv2.cvtColor(aframe, cv2.COLOR_BGR2GRAY)
        #raw = str(imgray.data)
        pil_img = Image.fromarray(imgray)
        npy_img = numpy.array(pil_img)

        scanner = zbar.Scanner()
        scanner.scan(imgray)

        codes = scanner.scan(npy_img)
        try:
            code = codes[0].data
            segment = code.decode('utf-8')
            self.currentSegment.insert(0,segment)
            print("Scanner: ", segment)
        except:
            self.currentSegment.insert(0,"X")
Esempio n. 30
0
    def getLinkFromPic(self, pic_path):

        #打开含有二维码的图片
        #pytfile_path = '/Users/didi/PycharmProjects/douyin+youtube/QR_CODE_PIC/1346664679.png'
        image = Image.open(pic_path).convert('L')

        scanner = zbar.Scanner()
        results = scanner.scan(image)

        string = str(results)

        try:
            link = self.tools.getLinkFromText(string).replace("'", "").replace(
                ",", "")
        except:
            link = "None"

        return link