Пример #1
0
    def test_only_thumbnail_works(self):  # noqa: D200
        """
        User submitted sample that can only be decoded after thumbnail or after adding a black border of at least 5px.
        """
        # thumbnail
        image = self.get_image('sample_only_thumbnail_works', ext='jpg')
        image.thumbnail((image.size[0] / 8, image.size[1] / 8))
        self.assertEqual(
            sorted(zbarlight.scan_codes(['qrcode'], image) or []),
            sorted([b"It's great! Your app works!"]),
        )

        # black border of 5px
        image = self.get_image('sample_only_thumbnail_works', ext='jpg')
        bordered = Image.new("RGB", (image.size[0] + 10, image.size[1] + 10),
                             zbarlight.BLACK)
        bordered.paste(image, box=(5, 5))
        self.assertEqual(
            sorted(zbarlight.scan_codes(['qrcode'], bordered) or []),
            sorted([b"It's great! Your app works!"]),
        )

        # original image
        image = self.get_image('sample_only_thumbnail_works', ext='jpg')
        self.assertEqual(
            sorted(zbarlight.scan_codes(['qrcode'], image) or []),
            sorted([b"It's great! Your app works!"]),
        )
Пример #2
0
    def test_only_thumbnail_works(self):  # noqa: D200
        """
        User submitted sample that can only be decoded after thumbnail or after adding a black border of at least 5px.
        """
        # thumbnail
        image = self.get_image('sample_only_thumbnail_works', ext='jpg')
        image.thumbnail((image.size[0] / 8, image.size[1] / 8))
        self.assertEqual(
            sorted(zbarlight.scan_codes(['qrcode'], image) or []),
            sorted([b"It's great! Your app works!"]),
        )

        # black border of 5px
        image = self.get_image('sample_only_thumbnail_works', ext='jpg')
        bordered = Image.new("RGB", (image.size[0] + 10, image.size[1] + 10), zbarlight.BLACK)
        bordered.paste(image, box=(5, 5))
        self.assertEqual(
            sorted(zbarlight.scan_codes(['qrcode'], bordered) or []),
            sorted([b"It's great! Your app works!"]),
        )

        # original image
        image = self.get_image('sample_only_thumbnail_works', ext='jpg')
        self.assertEqual(
            sorted(zbarlight.scan_codes(['qrcode'], image) or []),
            sorted([b"It's great! Your app works!"]),
        )
Пример #3
0
def scan_qr(fpath):
    with open(fpath, 'rb') as image_file:
        image = Image.open(image_file)
        image.load()
        code = zbarlight.scan_codes('qrcode', image)
        if code is None:
            for i in THRESHOLD_VALUES:
                image_bw = convert_to_BW(image, i)
                code = zbarlight.scan_codes('qrcode', image_bw)
        if code is None:
            return None
        return str(code[0], "utf-8")
Пример #4
0
def convert_image_to_seeds(url):
    image = Image.open(io.BytesIO(requests.get(url).content))
    ctype_list = ['ean13', 'upca', 'ean8', 'upce', 'code128', 'i25']
    codes = None
    for ctype in ctype_list:
        if zbarlight.scan_codes([ctype], image) is not None:
            codes = zbarlight.scan_codes([ctype], image)
            break
    if codes != None:
        return (int(codes[0].decode()))
    else:
        return False
Пример #5
0
def test_need_white_background():
    """User submitted sample that can only be decoded after add a white background."""
    image = get_image('sample_need_white_background')
    excepted_codes = [b'http://en.m.wikipedia.org']

    # No code is detected on the original image
    original_codes = zbarlight.scan_codes(['qrcode'], image)
    assert original_codes is None

    # But code is detected when adding a white background
    image_with_background = zbarlight.copy_image_on_background(image)
    background_codes = zbarlight.scan_codes(['qrcode'], image_with_background)
    assert background_codes == excepted_codes
Пример #6
0
    def test_one_qr_code_and_one_ean(self):
        image = self.get_image('one_qr_code_and_one_ean')

        # Only read QRcode
        self.assertEqual(
            sorted(zbarlight.scan_codes(['qrcode'], image)),
            sorted([b'zbarlight test qr code']),
        )

        # Only read EAN code
        self.assertEqual(
            sorted(zbarlight.scan_codes(['ean13'], image)),
            sorted([b'0012345678905']),
        )
Пример #7
0
    def test_one_qr_code_and_one_ean(self):
        image = self.get_image('one_qr_code_and_one_ean')

        # Only read QRcode
        self.assertEqual(
            sorted(zbarlight.scan_codes('qrcode', image)),
            sorted([b'zbarlight test qr code']),
        )

        # Only read EAN code
        self.assertEqual(
            sorted(zbarlight.scan_codes('ean13', image)),
            sorted([b'0012345678905']),
        )
Пример #8
0
def get_qr():
    with open('flag1.png', 'rb') as f:
        image1 = Image.open(io.BytesIO(f.read()))
    with open('flag2.png', 'rb') as f:
        image2 = Image.open(io.BytesIO(f.read()))
    with open('flag3.png', 'rb') as f:
        image3 = Image.open(io.BytesIO(f.read()))

    result1 = zbarlight.scan_codes('qrcode', image1)[0].decode()
    result2 = zbarlight.scan_codes('qrcode', image2)[0].decode()
    result3 = zbarlight.scan_codes('qrcode', image3)[0].decode()

    print(result1)
    print(result2)
    print(result3)
Пример #9
0
def _read(cv2_image):
    barcode_binary = binarization.nlbin(Image.fromarray(cv2_image), zoom=1.0)
    codes = zbarlight.scan_codes('code39', barcode_binary)
    if codes:
        return codes[0].decode('utf-8')
    else:
        return ''
def register_wallet():
    """Registers the BlockIO address encoded in a QR code provided by the user.
    If the user already has a wallet registered, registration will fail.
    """
    social_id = current_user.social_id
    user = User.query.filter_by(social_id=social_id).first()

    im = Image.open(BytesIO(base64.b64decode(request.data)))
    address = zbarlight.scan_codes('qrcode', im)
    if address is None or len(address) > 1:
        return json.dumps({'status': 'failed', 'code': 1, 'reason': errors[1]})
    address = address[0].decode("utf-8")

    if address not in addresses:
        return json.dumps({'status': 'failed', 'code': 2, 'reason': errors[2]})

    # Get balance and send doge to logged in user if there is any Doge in the wallet
    balance = get_balance(address)
    if balance is None:
        return json.dumps({'status': 'failed', 'code': 3, 'reason': errors[3]})
    available_balance = float(balance["data"]["available_balance"])
    if available_balance < 2:
        return json.dumps({'status': 'failed', 'code': 4, 'reason': errors[4]})

    # Send doge in wallet to current user - leave 2 Doge for network fee
    resp = system_send_doge(address, user.doge_address, available_balance - 2)
    return json.dumps(resp)
Пример #11
0
def camstream():
    pygame.init()
    pygame.camera.init()
    display = pygame.display.set_mode(SIZE, 0)
    camera = pygame.camera.Camera(DEVICE, SIZE)
    camera.start()
    screen = pygame.surface.Surface(SIZE, 0, display)
    capture = True
    while capture:
        screen = camera.get_image(screen)
        display.blit(screen, (0, 0))
        pygame.display.flip()
        string = pygame.image.tostring(screen, "RGBA", False)
        image = Image.frombytes("RGBA", SIZE, string)
        codes = zbarlight.scan_codes('qrcode', image)
        if codes:
            print('QR codes: %s' % codes[0])
        for event in pygame.event.get():
            if event.type == QUIT:
                capture = False
            elif event.type == KEYDOWN and event.key == K_s:
                pygame.image.save(screen, FILENAME)
                print("saved")
    camera.stop()
    pygame.quit()
    return
Пример #12
0
        def scan(self,verbose=False):
            #### picamera capture to PIL Image

            # Create the in-memory stream
            stream = BytesIO()

            self.camera.capture(stream, format='jpeg',use_video_port= False)   # perhaps change from jpeg to gif or png
            ###
            ''' The use_video_port parameter controls whether the camera’s image or video port is used to capture images.
            It defaults to False which means that the camera’s image port is used. This port is slow but produces better
             quality pictures. If you need rapid capture up to the rate of video frames, set this to True.'''
            ###

            # "Rewind" the stream to the beginning so we can read its content
            stream.seek(0)
            self.still = Image.open(stream)
            self.codes = zbarlight.scan_codes('qrcode', self.still)
            if self.codes:
                self.codes = [b(i) for i in self.codes]
                """
                if self.verbose:
                    for i in self.codes:
                        print('QR code: %s\n\n' % i)
                """
                return self.codes
            else:
                self.codes=[]
                #print("\n======\n\nNo QR Found\n\n======")
                return None
Пример #13
0
def calculate_elapsed(current_time, snapshot_path):
    """
    Reads the QR from the snapshot path, which contains a timestamp, and calculates the delay.
    :param current_time: Timestamp in milliseconds. (Not in seconds!)
    :param snapshot_path:
    :return:
    """
    # Note: Opening and parsing the QR takes around 27 ms.
    image = Image.open(snapshot_path)
    image.load()
    codes = zbarlight.scan_codes('qrcode', image)

    if codes is None or len(codes) != 1:
        print("No code in image")
        return None

    code = codes[0]
    timestamp, crc = code.split(b'|')
    crc_expected = hex(zlib.crc32(timestamp)).encode('utf-8')
    if crc != crc_expected:
        print("Code was parsed wrong")
        print("CRC: {}; expected: {}".format(crc, crc_expected))
        return None

    then_time = int(timestamp)
    elapsed = current_time - then_time

    return elapsed
Пример #14
0
def barstrfromxpath(browser, xpathstr):

    savepath = "./temp.png"

    codes = None
    while codes == None:

        waittime = 15
        try:
            WebDriverWait(browser, waittime).until(
                lambda the_driver: the_driver.find_element_by_xpath(xpathstr))
        except TimeoutException:
            timeoutlog(browser, xpath, waittime)

        imgelement = browser.find_element_by_xpath(xpathstr)
        location = imgelement.location
        size = imgelement.size
        browser.save_screenshot(savepath)
        time.sleep(0.5)  ### 图像没有显示出来之前 失败率较高

        im = Image.open(savepath)
        left = location['x']
        top = location['y']
        right = left + size['width']
        bottom = location['y'] + size['height']
        im = im.crop((left, top, right, bottom))

        codes = zbarlight.scan_codes('qrcode', im)
        if codes != None:
            break
        print("二维码识别失败,再次尝试")

    return codes[0].decode('utf-8')
Пример #15
0
def extract_qr_from_image(qr_count):
    """Attempt to read the QR code from the image
    """
    print("Scanning image..")
    with open(config.QRFOLDER + "/lntxcred_" + str(qr_count) + ".jpg", "rb") as f:
        qr = Image.open(f)
        qr.load()
        invoice = zbarlight.scan_codes("qrcode", qr)

    if not invoice:
        logger.info("No QR code found")
        print("No QR code found")
        os.remove(config.QRFOLDER + "/lntxcred_" + str(qr_count) + ".jpg")
        return False

    else:
        # extract invoice from list
        logger.info("Invoice detected")
        invoice = invoice[0]
        invoice = invoice.decode()
        # invoice = invoice.lower()
        # print(invoice)

        # with open(config.QRFOLDER+'/qr_code_scans.txt','a+') as f:
        #    f.write(invoice + ' ' + str(datetime.now()) + '\n')

        # remove "lightning:" prefix
        # if 'lightning:' in invoice:
        #    invoice = invoice[10:]

        return invoice
Пример #16
0
def decodeQrcode(data):
    qrImg = Image.fromarray(np.uint8(data))
    codes = zbarlight.scan_codes('qrcode', qrImg)
    for i in codes:
        codes = i.decode('utf-8', 'ignore')

    return codes
Пример #17
0
 def process_file(self, file):
     assert hasattr(file, "pixels")  # TODO proper check
     codes = zbarlight.scan_codes('qrcode', file.pil)
     if codes is not None:
         codes = ';'.join(sorted(x.decode('utf8') for x in codes))
     file.report.update({"QRCodes": codes})
     return file
Пример #18
0
def scan_qr_code(image):
    """Get codes from image object

    :param image: an image object (from PIL.Image)
    :return: result of zbarlight scan_code (list of text scanned from qrcode)
    """
    return zbarlight.scan_codes('qrcode', image)
Пример #19
0
def picture():
    print('Taking picture..')
    try:
        f = 1
        #qr_count = len(os.listdir('qr_codes'))
        get_image()
        #os.system('sudo fswebcam -d /dev/video'+sys.argv[1]+' -q qr_codes/qr_'+str(qr_count)+'.jpg')
        print('Picture taken..')
    except Exception as e:
        f = 0
        print('Picture couldn\'t be taken with exception ' + str(e))

    #print

    if (f):
        print('Scanning image..')
        f = open('foo.jpg', 'rb')
        qr = PIL.Image.open(f)
        qr.load()

        codes = zbarlight.scan_codes('qrcode', qr)
        if (codes == None):
            #os.remove('qr_codes/qr_'+str(qr_count)+'.jpg')
            print('No QR code found')
            return 0
        else:
            print('QR code(s):')
            return 1
Пример #20
0
def qrRead():
    print("enter qrRead")
    file_path = 'qrphoto.jpg'
    with open(file_path, 'rb') as image_file:
        image = Image.open(image_file)
        image.load()

    codes = zbarlight.scan_codes('qrcode', image)
    #codes = 5
    if codes == [b'1']:
        codes = 1
    elif codes == [b'2']:
        codes = 2
    elif codes == [b'3']:
        codes = 3
    elif codes == [b'4']:
        codes = 4
    elif codes == [b'5']:
        codes = 5
    elif codes == [b'6']:
        codes = 6
    elif codes == [b'7']:
        codes = 7
    elif codes == [b'8']:
        codes = 8
    elif codes == [b'9']:
        codes = 9
    else:
        codes = 0  #return "0",False
    print(codes)
    print("qrRead")
    return codes
Пример #21
0
def scan_code(device, size):
    pygame.init()
    pygame.camera.init()
    display = pygame.display.set_mode(size, 0)
    pygame.display.set_caption("Scan QR-code here")
    camera = pygame.camera.Camera(device, size)
    camera.start()
    screen = pygame.surface.Surface(size, 0, display)
    capture = True
    while capture:
        screen = camera.get_image(screen)
        display.blit(screen, (0, 0))
        pygame.display.flip()
        string = pygame.image.tostring(screen, "RGBA", False)
        image = Image.frombytes("RGBA", size, string)
        codes = zbarlight.scan_codes('qrcode', image)
        if codes:
            code = codes[0]
            capture = False
        for event in pygame.event.get():
            if event.type == QUIT:
                capture = False
    camera.stop()
    pygame.quit()
    code = str(code)
    code = code[2:len(code) - 1]
    return code
Пример #22
0
def qr_read(filename):
    with open(filename, 'rb') as image_file:
        image = Image.open(image_file)
        image.load()
        codes = zbarlight.scan_codes('qrcode', image)
        code = codes[0].decode('utf8')
        print('QR code:%s' % code)
Пример #23
0
def find_qrcode(file_path):
    with open(file_path, 'rb') as image_file:
        image = Image.open(image_file)
        image.load()
    codes = zbarlight.scan_codes('qrcode', image)
    print('QR codes in {}: {}'.format(file_path, codes))
    return codes
Пример #24
0
 def test_two_qr_code(self):
     image = self.get_image('two_qr_codes')
     self.assertEqual(
         sorted(zbarlight.scan_codes('qrcode', image)),
         sorted(
             [b'second zbarlight test qr code', b'zbarlight test qr code']),
     )
Пример #25
0
def scan(request):
    if request.method == 'GET':
        message = ''
        return render(request, 'scan.html', locals())
    if request.method == 'POST':
        upfile = request.FILES.get('upfile', '')
        if upfile == '':
            message = '你没有选择任何文件'
        else:
            u = str(uuid.uuid1())
            # 打开特定的文件进行二进制的写操作
            destination = open('home/static/qr/' + u + '.png', 'wb+')
            # 分块写入文件
            for chunk in upfile.chunks():
                destination.write(chunk)
            # 关闭文件
            destination.close()
            # 二维码上传后的新路径
            file_path = 'home/static/qr/' + u + '.png'
            # 打开并读取二维码图片
            with open(file_path, 'rb') as qr_file:
                qr = Image.open(qr_file)
                qr.load()
            # 扫描二维码文件获得二维码中的内容
            qr_content = zbarlight.scan_codes('qrcode', qr)
            # 获得二维码文件路径
            p = 'download/qr/' + u + '.png'
            if qr_content == None:
                message = '扫描二维码内容失败'
            else:
                message = str(qr_content[0].decode('utf-8'))
    return render(request, 'scan.html', locals())
 def extract_qrcode_info(self, file_path):
     for zoom in range(1,5):
         try:
             doc = fitz.open(file_path)
             png = doc[0].getPixmap(matrix=fitz.Matrix(1<<zoom,1<<zoom), alpha=False).getPNGdata()
             img = Image.open(BytesIO(png))
             values = list(filter(None, scan_codes(['qrcode'], img)[0].decode().split(',')))
             for keys in self.qrcode_keys:
                 ret = dict(zip(keys, values))
                 try:
                     ret['金额'] = eval(ret['金额'])
                     ret['开票日期'] = datetime.strptime(ret['开票日期'], '%Y%m%d').date()
                 except:
                     pass
                 else:
                     break
             for key in ['f0', 'f1', 'f6']:
                 ret.pop(key, None)
         except:
             pass
         else:
             break
     else:
         print('Read QRcode failed')
         ret = {}
     return ret
Пример #27
0
def scan():

    with PiCamera() as camera:
        try:
            camera.start_preview()
            time.sleep(1)
            logger.info("Start scanning for QR code")
        except:
            logger.error("PiCamera.start_preview() raised an exception")

        stream = BytesIO()
        qr_codes = None
        # Set timeout to 10 seconds
        timeout = time.time() + 10

        while qr_codes is None and (time.time() < timeout):
            stream.seek(0)
            # Start camera stream (make sure RaspberryPi camera is focused correctly
            # manually adjust it, if not)
            camera.capture(stream, "jpeg")
            stream.seek(0)
            qr_codes = zbarlight.scan_codes("qrcode", Image.open(stream))
            time.sleep(0.05)
        camera.stop_preview()

        # break immediately if we didn't get a qr code scan
        if not qr_codes:
            logger.info("No QR within 10 seconds detected")
            return False

        # decode the first qr_code to get the data
        qr_code = qr_codes[0].decode()

        return qr_code
Пример #28
0
def scan(path):
    with open(path, 'rb') as image_file:
        image = Image.open(image_file)
        image.load()

    codes = zbarlight.scan_codes('qrcode', image)
    return codes
Пример #29
0
def check_image(url, filename):
    global invalid_img
    global valid_img
    global valid_qr

    try:
        with Image.open(filename).convert('RGBA') as img:
            img.load()
            qr_codes = zbarlight.scan_codes('qrcode', img)
    except:
        invalid_img += 1
        return
    valid_img += 1
    if qr_codes:
        valid_qr += 1
        with open('valid_qr_codes.txt', 'a') as qr_file:
            for qr_code in qr_codes:
                try:
                    qr_data = qr_code.decode('ascii', errors='replace')
                except:
                    pass

                print("{} - {}".format(qr_data, url))
                qr_file.write("{} - {}\n".format(qr_data, url))

                if ((re.match(r'5(H|J|K).{49}$', qr_data) or      # match private key (WIF, uncompressed pubkey) with length 51
                   re.match(r'(K|L).{51}$', qr_data) or           # match private key (WIF, compressed pubkey) with length 52
                   re.match(r'S(.{21}|.{29})$', qr_data)) and     # match mini private key with length 22 (deprecated) or 30
                   re.match(r'[1-9A-HJ-NP-Za-km-z]+', qr_data)):  # match only BASE58
                    print('^^^ Possibly Satoshi Nakamoto ^^^')
                    qr_file.write('^^^ Possibly Satoshi Nakamoto ^^^\n')
Пример #30
0
 def test_code_type_deprecation(self):
     image = self.get_image('one_qr_code_and_one_ean')
     with pytest.deprecated_call():
         self.assertEqual(
             sorted(zbarlight.scan_codes('qrcode', image)),
             sorted([b'zbarlight test qr code']),
         )
Пример #31
0
    def test_need_white_background(self):
        """User submitted sample that can only be decoded after add a white background."""
        # Not working
        image = self.get_image('sample_need_white_background')

        self.assertEqual(
            sorted(zbarlight.scan_codes(['qrcode'], image) or []),
            [],
        )

        # Working when adding white background
        image_with_background = zbarlight.copy_image_on_background(image)
        self.assertEqual(
            sorted(zbarlight.scan_codes(['qrcode'], image_with_background) or []),
            sorted([b'http://en.m.wikipedia.org']),
        )
Пример #32
0
 def test_code_type_deprecation(self):
     image = self.get_image('one_qr_code_and_one_ean')
     with pytest.deprecated_call():
         self.assertEqual(
             sorted(zbarlight.scan_codes('qrcode', image)),
             sorted([b'zbarlight test qr code']),
         )
Пример #33
0
def get_qr_code_by_sharpening(image):
    """Try to sharpen the image to find the QR code."""
    sharpened = image.filter(ImageFilter.SHARPEN)
    qr_code = zbarlight.scan_codes('qrcode', sharpened)
    if qr_code:
        return qr_code[0].decode('utf-8')
    return None
Пример #34
0
def main():

    # Begin capturing video
    capture = cv2.VideoCapture(0)

    while True:
        # To quit this program press q
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

        # Breaks down the video into frames
        ret, frame = capture.read()

        # Displays the current frame
        cv2.imshow('Current', frame)

        # Converts image to grayscale.
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        # Uses PIL to convert the grayscale image into an array that zbarlight can understand.
        pil_im = Image.fromarray(gray)

        # Scans the zbarlight image.
        codes = zbarlight.scan_codes('qrcode', pil_im)

        # Prints data from image.
        print('QR codes: %s' % codes)
Пример #35
0
def QRReader(file_path = './out.png'):
    start = datetime.datetime.utcnow()
    with open(file_path, 'rb') as image_file:
        image = PILImage.open(image_file)
        image.load()
    codes = zbarlight.scan_codes('qrcode', image)
    print('QR codes: %s' % codes)
    print(datetime.datetime.utcnow()-start)
Пример #36
0
def load_from_file(file_path="filename.png"):
    with open(file_path, "rb") as image_file:
        image = Image.open(image_file)
        image.load()

    codes = zbarlight.scan_codes("qrcode", image)
    codes = codes[0].decode("ascii")
    print("QR codes: %s" % codes)
Пример #37
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('image', help='input image')
    args = parser.parse_args()
    with open(args.image, 'rb') as image_file:
        image = Image.open(image_file)
        image.load()
        codes = zbarlight.scan_codes(['qrcode'], image)
        print('QR codes: %s' % codes)
Пример #38
0
def DecodeQRImage(CVImage):
    #start = datetime.datetime.utcnow()
    codes = None
    if not CVImage == None :
        image = PILImage.fromarray(CVImage)
        codes = zbarlight.scan_codes('qrcode', image)
        #print('QR codes: %s' % codes)
    #print(datetime.datetime.utcnow()-start)
    return codes
Пример #39
0
def decodeQR(file_path):
    """(str) -> str
    Returns the string obtained by decoding the QR image located at file_path
    """

    with open(file_path, 'rb') as image_file:
        image = Image.open(image_file)
        image.load()

    codes = zbarlight.scan_codes('qrcode', image)
    return str(codes)
Пример #40
0
def read_qrcode_new(pic_name):
    with open(pic_name, 'rb') as image_file:
        image = Image.open(image_file)
        image.load()
    codes = zbarlight.scan_codes('qrcode', image)
    print 'codes:' + codes
    if codes != None:
        pic_id = get_pic_id(codes)
        return pic_id
    else:
        print '[No Need to Rename] pic_name: ' + pic_name
        return ''
Пример #41
0
Файл: qr.py Проект: bauna/vot.ar
def leer_qr(path_imagen):
    '''Lee los datos de una imagen que contenga un codigo qr.'''
    from zbarlight import scan_codes
    ret = ""

    with open(path_imagen, 'rb') as image_file:
        image = Image.open(image_file)
        image.load()

    codes = scan_codes('qrcode', image)
    if codes is not None and len(codes):
        ret = codes[0].decode("utf8")
    return ret
Пример #42
0
 def read(self):
     with open(self.filename, 'rb') as image_file:
         image = Image.open(image_file)
         image.load()
     self.codes = zbarlight.scan_codes('qrcode', image)
     self.remove()
     if self.codes:
         otpauth_url = self.codes[0].decode()
         self.codes = dict(parse_qsl(urlparse(otpauth_url)[4]))
         return self.codes
     else:
         logging.error("Invalid QR image")
         return None
    def readImage(self, img):
        try:
            img
        except NameError:
            print 'Unable to find image'
            return None

        filename = '/tmp/lastQRImage.jpg'
        cv2.imwrite(filename, img)
        image = Image.open(filename)
        image.load()
        codes = zbarlight.scan_codes('qrcode', image)

        if codes != None:
            print("Found Code! Code: "+str(codes))
            cv2.imwrite('/tmp/lastFoundQRImage.jpg', img)
            return codes[0]
        return None
Пример #44
0
def scanQrCode(path):
    # return None
    with open(path, 'rb') as image_file:
        image = Image.open(image_file)
        image.load()
    # wxp://f2f0JV5T664Amfb_JDHLXtMBTrL2_8PvU68O
    # HTTPS://QR.ALIPAY.COM/FKX05639AEMUOSN0TE016F
    codes = zbarlight.scan_codes('qrcode', image)
    if codes != None:
        code = str(codes[0]).lstrip("b'").rstrip("'")
        print('二维码识别结果:' + code)
        return code
    else:
        print('二维码识别失败')
        return None



# zbarlight==1.2
# zbarlight==1.2
# zbar==0.10
Пример #45
0
    def grab(self):
        self.frame = self.cap.read()[1]

        # expand/shrink to widget size
        wsize = (self.size().width(), self.size().height())
        self.cvImage = cv2.resize(self.frame, wsize)

        height, width, byteValue = self.cvImage.shape
        bytes_per_line = byteValue * width

        # hsv to rgb
        cv2.cvtColor(self.cvImage, cv2.COLOR_BGR2RGB, self.cvImage)
        self.mQImage = QImage(self.cvImage, width, height,
                              bytes_per_line, QImage.Format_RGB888)

        cv_img = cv2.cvtColor(self.cvImage, cv2.COLOR_RGB2GRAY)
        raw = Image.fromarray(cv_img)

        # extract results and display first code found
        codes = zbarlight.scan_codes('qrcode', raw)
        if codes:
            self.emit(SIGNAL('code(QString)'), codes[0].decode("UTF-8"))
Пример #46
0
 def test_one_qr_code(self):
     image = self.get_image('one_qr_code')
     code = zbarlight.scan_codes(['qrcode'], image)
     self.assertEqual(code, [b"zbarlight test qr code"])
Пример #47
0
def start():
  print "Starting capture..."
  camera = PiCamera()
  camera.resolution = (640,480)
  camera.framerate = 24
  camera.hlip = False

  rawCapture = PiRGBArray(camera,size=(640,480))
  time.sleep(0.1)

  qrResult = {}
  confirmationFrames = 5
  frameCountdown = 140

  for frame in camera.capture_continuous(rawCapture,format="bgr",use_video_port=True):
    #GIVEUP AFTER SO MANY FRAMES
    frameCountdown-=1
    if (frameCountdown <= 0):
      break

    image = frame.array
    img = image
    
    edges = cv2.Canny(image,100,200)
    contours,hierarchy = cv2.findContours(edges,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
    mu = []
    mc = []
    mark = 0
    for x in range(0,len(contours)):
      mu.append(cv2.moments(contours[x]))

    for m in mu:
      if m['m00'] != 0:
        mc.append((m['m10']/m['m00'],m['m01']/m['m00']))
      else:
        mc.append((0,0))

    for x in range(0,len(contours)):
      k = x
      c = 0
      while(hierarchy[0][k][2] != -1):
        k = hierarchy[0][k][2]
        c = c + 1
      if hierarchy[0][k][2] != -1:
        c = c + 1

      if c >= 5:
        if mark == 0:
          A = x
        elif mark == 1:
          B = x
        elif mark == 2:
          C = x
        mark = mark+1

    if mark >2 :
      AB = distance(mc[A],mc[B])
      BC = distance(mc[B],mc[C])
      AC = distance(mc[A],mc[C])

      if(AB>BC and AB>AC):
        outlier = C
        median1 = A
        median2 = B
      elif(AC>AB and AC>BC):
        outlier = B
        median1 = A 
        median2 = C 
      elif(BC>AB and BC>AC):
        outlier = A 
        median1 = B
        median2 = C

      top = outlier
      dist = lineEquation(mc[median1],mc[median2],mc[outlier])
      slope,align = lineSlope(mc[median1],mc[median2])

      if align == 0:
        bottom = median1
        right = median2
      elif(slope < 0 and dist < 0):
        bottom = median1
        right = median2
        orientation = 0
      elif(slope > 0 and dist < 0):
        right = median1
        bottom = median2
        orientation = 1
      elif(slope < 0 and dist > 0):
        right = median1
        bottom = median2
        orientation = 2
      elif(slope > 0 and dist > 0):
        bottom = median1
        right = median2
        orientation = 3

      areatop = 0.0
      arearight = 0.0
      areabottom = 0.0

      if(top < len(contours) and right < len(contours) and bottom < len(contours) and cv2.contourArea(contours[top]) > 10 and cv2.contourArea(contours[right]) > 10 and cv2.contourArea(contours[bottom]) > 10):
        #FLIP, SCAN, AND SAVE BEFORE ADDING COLOURS 
        scanimg = cv2.flip(img,1)

        #DRAW DETECTED LINES
        tempL = []
        tempM = []
        tempO = []
        N = (0,0)
        tempL = getVertices(contours,top,slope,tempL)
        tempM = getVertices(contours,right,slope,tempM)
        tempO = getVertices(contours,bottom,slope,tempO)
        L = updateCornerOr(orientation,tempL)
        M = updateCornerOr(orientation,tempM)
        O = updateCornerOr(orientation,tempO)
        
        iflag,N = getIntersection(M[1],M[2],O[3],O[2],N)
        cv2.circle(img,N,1,(0,0,255),2)
        cv2.drawContours(img,contours,top,(255,0,0),2)
        cv2.drawContours(img,contours,right,(0,255,0),2)
        cv2.drawContours(img,contours,bottom,(0,0,255),2)

        #SCAN FLIPPED
        code = zbarlight.scan_codes('qrcode', Image.fromarray(scanimg))
        if code == None:
          print "No qr found"
        elif len(code) == 1:
          confirmationFrames -= 1
          qrResult = parseUrl(code[0])
          if qrResult['success'] and (confirmationFrames <= 0):
            break
    
    #DISPLAY      
    img = cv2.flip(img,1)
    #draw arrow
    cv2.line(img,(630,470),(590,430),(240,240,240),2)
    cv2.line(img,(630,470),(630,460),(240,240,240),2)
    cv2.line(img,(630,470),(620,470),(240,240,240),2)
    
    #add text
    cv2.putText(img, "Show your address QR code", (50, 50), cv2.FONT_HERSHEY_PLAIN, 2, (240,240,240), 2, cv2.CV_AA)
    cv2.putText(img, "Camera", (560, 420), cv2.FONT_HERSHEY_PLAIN, 1, (240,240,240), 2, cv2.CV_AA)

    cv2.namedWindow("window", cv2.WND_PROP_FULLSCREEN)
    cv2.setWindowProperty("window", cv2.WND_PROP_FULLSCREEN, 1)
    cv2.imshow("window", img)

    key = cv2.waitKey(1) & 0xFF
    rawCapture.truncate(0)
    if key == ord("q"):
      break

  camera.close()
  cv2.destroyAllWindows()
  for i in range (1,5):
    cv2.waitKey(1)
  return qrResult
Пример #48
0
import zbarlight
import io
from PIL import Image
import urllib2

url='http://media.twiliocdn.com.s3-external-1.amazonaws.com/ACa52bfd8d5b49c0c3fa25cc747a8767b6/934939f4b7ecb2e8d839d4e443333cba'

fd = urllib2.urlopen(url)
image_file = io.BytesIO(fd.read())
image = Image.open(image_file)

print(image)

codes = zbarlight.scan_codes('qrcode', image)

print(codes)
def load_qrcode(image):
    code = zbarlight.scan_codes("qrcode", image)[0]
    return json.loads(code.decode("utf-8"))
Пример #50
0
 def test_no_qr_code(self):
     image = self.get_image('no_qr_code')
     self.assertIsNone(zbarlight.scan_codes(['qrcode'], image))
Пример #51
0
def decodeQR(arquivo):
    with open(arquivo, 'rb') as image_file:
         image = Image.open(image_file)
         image.load()
    codes = zbarlight.scan_codes('qrcode', image)
    return codes
Пример #52
0
 def test_two_qr_code(self):
     image = self.get_image('two_qr_codes')
     self.assertEqual(
         sorted(zbarlight.scan_codes(['qrcode'], image)),
         sorted([b'second zbarlight test qr code', b'zbarlight test qr code']),
     )
Пример #53
0
 def test_one_qr_code_and_one_ean_at_once(self):
     image = self.get_image('one_qr_code_and_one_ean')
     self.assertEqual(
         sorted(zbarlight.scan_codes(['qrcode', 'ean13'], image)),
         sorted([b'zbarlight test qr code', b'0012345678905']),
     )
Пример #54
0
def create_qrcode(qr):
    img = Image.new('1', (23, 23), 'white')
    qr = qr.split('\n')

    for i in range(1, 22):
        for j in range(2, 44, 2):
            if qr[i][j] == ' ':
                img.putpixel((i, j/2), 0) # add a black block

    return img


with open('README.txt') as f:
    lines = f.read().split('\n')[:-1]

b64code = ''
message = ''
for l in lines:
    b64code += l
    if len(l) < 76:
        qr_text = b64decode(b64code).decode('utf8')
        qrcode = create_qrcode(qr_text)
        message += scan_codes('qrcode', qrcode)[0]
        b64code = ''

        #qrcode.resize((500, 500)).show()
        #raw_input('')

print message