def decode_array(img):
        reader = BarCodeReader()
        results = reader.decode_array(img)

        print("results ", results)

        if 'raw' in results[0]:
            result_string = results[0]['raw'].decode("utf-8")
            # print(result_string.split('\n'))

            barcode_data_split = [s.strip() for s in result_string.split('\n')]
            # print(barcode_data_split)

            barcode_dict = {}

            with open("LicenseCodes.json") as f:
                codes = json.load(f)
                # print(codes['DAB']['val'])
                barcode_dict = {
                    codes[s[:3]]['val']: s[3:]
                    for s in barcode_data_split if s[:3] in codes
                }

            # print(barcode_dict)

            # print(json.dumps(barcode_dict, indent=4, sort_keys=False))

            return json.dumps(barcode_dict, indent=4, sort_keys=False)
        else:
            return "Could not detect barcode"
示例#2
0
def main():
    ''' main '''
    reader = BarCodeReader()
    for fn in common.get_pngs():
        print('fn:', fn)
        results = reader.decode(fn)
        print(results)
示例#3
0
文件: scanner.py 项目: leisux/pyzxing
def main(args):
    reader = BarCodeReader()

    results = reader.decode(args.file)
    if results:
        if isinstance(results[0], dict):
            results_string = [result['parsed'] for result in results]
        else:
            results_string = [
                x['parsed'] for result in results for x in result
            ]

        for result in results_string:
            print(result)
示例#4
0
 def test_create_reader_no_local(self):
     cache_dir = osp.join(osp.expanduser('~'), '.local')
     if osp.exists(cache_dir):
         shutil.rmtree(cache_dir)
     if osp.exists(build_jar_dir):
         shutil.rmtree(build_jar_dir)
     self.reader = BarCodeReader()
示例#5
0
def read_qr_by_pyzxing(img: Union[bytearray, str]):
    reader = BarCodeReader()
    if isinstance(img, bytearray):
        np_array = np.array(Image.open(io.BytesIO(img)))
        results = reader.decode_array(np_array)
    elif isinstance(img, str):
        results = reader.decode(img)
    else:
        return "", False

    try:
        results = [
            code for code in results
            if code['format'].decode("utf-8") == 'QR_CODE'
        ]
    except:
        return "", False
    if len(results) == 0:
        return '', False
    text = results[0]['raw'].decode("utf-8")
    return text, True
示例#6
0
    def test_create_reader_with_built_jar(self):
        cache_dir = osp.join(osp.expanduser('~'), '.local')
        if osp.exists(cache_dir):
            shutil.rmtree(cache_dir)
        # Check build dir
        build_jar_path = glob.glob(
            osp.join(build_jar_dir, "javase-*-jar-with-dependencies.jar"))
        if not build_jar_path:
            # Prepare fake built jar file
            from pyzxing.reader import preset_jar_url_prefix, preset_jar_filename
            build_jar_dir_abs = osp.join(osp.abspath('.'), build_jar_dir)
            download_url = osp.join(preset_jar_url_prefix, preset_jar_filename)
            get_file(preset_jar_filename, download_url, build_jar_dir_abs)

        self.reader = BarCodeReader()
示例#7
0
 def test_create_reader_with_cache_jar(self):
     self.reader = BarCodeReader()
示例#8
0
            bwm = watermark(int(random_seed1),
                            int(random_seed2),
                            mod1,
                            wm_shape=(wm_shape0, wm_shape1),
                            block_shape=(args.block_shape, args.block_shape),
                            dwt_deep=args.dwt_deep)
        elif len(args.key) == 4:
            random_seed1, random_seed2, mod1, mod2 = args.key
            bwm = watermark(int(random_seed1),
                            int(random_seed2),
                            mod1,
                            mod2,
                            wm_shape=(wm_shape0, wm_shape1),
                            block_shape=(args.block_shape, args.block_shape),
                            dwt_deep=args.dwt_deep)
        bwm.extract(args.ori_img, args.output)
        if args.show_ncc:
            if args.wm:
                test_ncc(args.wm, args.output)
            else:
                print(
                    "When you want to show the similarity between the output watermark and the original watermark, you need to give the path of the original watermark"
                )

        # Now decode QR code
        from pyzxing import BarCodeReader
        reader = BarCodeReader()
        results = reader.decode(args.output)
        if len(results) >= 1:
            print("Watermark data:", results[0]['raw'])
示例#9
0
 def setUp(self):
     self.reader = BarCodeReader()
示例#10
0
class TestBarCodeReaderDecode(unittest.TestCase):
    def setUp(self):
        self.reader = BarCodeReader()

    def test_codabar(self):
        basename = 'src/resources/codabar'
        result = self.reader.decode(basename + '.png')
        with open(basename + '.txt', 'rb') as fp:
            gt = fp.readline().strip()
        self.assertEqual(result[0]['parsed'], gt)

    def test_code39(self):
        basename = 'src/resources/code39'
        result = self.reader.decode(basename + '.png')
        with open(basename + '.txt', 'rb') as fp:
            gt = fp.readline().strip()
        self.assertEqual(result[0]['parsed'], gt)

    def test_code128(self):
        basename = 'src/resources/code128'
        result = self.reader.decode(basename + '.png')
        with open(basename + '.txt', 'rb') as fp:
            gt = fp.readline().strip()
        self.assertEqual(result[0]['parsed'], gt)

    def test_pdf417(self):
        basename = 'src/resources/pdf417'
        result = self.reader.decode(basename + '.png')
        with open(basename + '.txt', 'rb') as fp:
            gt = fp.readline().strip()
        self.assertEqual(result[0]['parsed'], gt)

    def test_qrcode(self):
        basename = 'src/resources/qrcode'
        result = self.reader.decode(basename + '.png')
        with open(basename + '.txt', 'rb') as fp:
            gt = fp.readline().strip()
        self.assertEqual(result[0]['parsed'], gt)

    def test_nonexistfile(self):
        basename = 'src/resources/nonexistfile'
        try:
            result = self.reader.decode(basename + '.png')
            raise Exception('Exception not raise properly')
        except FileNotFoundError as e:
            pass
        except Exception as e:
            raise e

    def test_nobarcodefile(self):
        basename = 'src/resources/ou'
        result = self.reader.decode(basename + '.jpg')
        self.assertEqual(result[0].get('parsed', None), None)

    def test_multibarcodes(self):
        basename = 'src/resources/multibarcodes'
        results = self.reader.decode(basename + '.jpg')
        result_string = [result['parsed'] for result in results]

        with open(basename + '.txt', 'rb') as fp:
            gt = [line.strip() for line in fp.readlines()]

        self.assertEqual(set(result_string), set(gt))

    def test_multifiles(self):
        filename_pattern = 'src/resources/*.png'
        results = self.reader.decode(filename_pattern)
        results_string = [x['parsed'] for result in results for x in result]

        filenames = glob.glob(filename_pattern)
        annofiles = [
            os.path.splitext(filename.replace('\\', '/'))[0] + '.txt'
            for filename in filenames
        ]
        gt = []
        for annofile in annofiles:
            with open(annofile, 'rb') as fp:
                gt.append(fp.readline().strip())

        self.assertEqual(set(results_string), set(gt))
示例#11
0
def decodificar_2():
    reader = BarCodeReader()
    results = reader.decode(MEDIA_ROOT + '/barcode.png')
    datos = results[0]['parsed'].replace("'", "\"")
    return ast.literal_eval(datos)
                    codes[s[:3]]['val']: s[3:]
                    for s in barcode_data_split if s[:3] in codes
                }

            # print(barcode_dict)

            # print(json.dumps(barcode_dict, indent=4, sort_keys=False))

            return json.dumps(barcode_dict, indent=4, sort_keys=False)
        else:
            return "Could not detect barcode"


if __name__ == "__main__":

    reader = BarCodeReader()
    results = reader.decode("2D-Gen-Back-DL-01.png")
    # Or file pattern for multiple files
    # results = reader.decode('/PATH/TO/FILES/*.png')
    # print(results[0]['raw'].decode("utf-8"))

    # Or a numpy array
    # Requires additional installation of opencv
    # pip install opencv-python
    # results = reader.decode_array(img)

    result_string = results[0]['raw'].decode("utf-8")
    # print(result_string.split('\n'))

    barcode_data_split = [s.strip() for s in result_string.split('\n')]
    print(barcode_data_split)
示例#13
0
from pyzxing import BarCodeReader
reader = BarCodeReader()
示例#14
0
 def test_create_reader_no_local(self):
     if os.path.exists(jar_path + jar_filename):
         os.remove(jar_path + jar_filename)
     self.reader = BarCodeReader()
示例#15
0
 def test_create_reader_with_local(self):
     if os.path.exists(jar_path):
         shutil.rmtree(jar_path)
     self.reader = BarCodeReader()
     self.reader = BarCodeReader()