Python pyzbar.pyzbar.decode() Examples
The following are 25
code examples of pyzbar.pyzbar.decode().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
pyzbar.pyzbar
, or try the search function
.
Example #1
Source File: qr_reader.py From Authenticator with GNU General Public License v2.0 | 11 votes |
def read(self): try: from PIL import Image from pyzbar.pyzbar import decode decoded_data = decode(Image.open(self.filename)) if path.isfile(self.filename): remove(self.filename) try: url = urlparse(decoded_data[0].data.decode()) query_params = parse_qsl(url.query) self._codes = dict(query_params) return self._codes.get("secret") except (KeyError, IndexError): Logger.error("Invalid QR image") return None except ImportError: from ..application import Application Application.USE_QRSCANNER = False QRReader.ZBAR_FOUND = False
Example #2
Source File: QR_Scaner1.py From OpenCV-Python-Tutorial with MIT License | 6 votes |
def main(): fp = 'macbookPro.jpg' # image = Image.open(fp) # image.show() image = cv2.imread(fp) barcodes = decode(image) decoded = barcodes[0] print(decoded) # url: bytes = decoded.data url = url.decode() print(url) # rect rect = decoded.rect print(rect) # Rect(left=19, top=19, width=292, height=292) # loop over the detected barcodes for barcode in barcodes: # extract the bounding box location of the barcode and draw the # bounding box surrounding the barcode on the image (x, y, w, h) = barcode.rect cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 2) # the barcode data is a bytes object so if we want to draw it on # our output image we need to convert it to a string first barcodeData = barcode.data.decode("utf-8") barcodeType = barcode.type # draw the barcode data and barcode type on the image text = "{} ({})".format(barcodeData, barcodeType) cv2.putText(image, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2) # print the barcode type and data to the terminal print("[INFO] Found {} barcode: {}".format(barcodeType, barcodeData)) # show the output image cv2.imshow("Image", image) # cv2.imwrite('macbook_qr_rect.jpg', image) cv2.waitKey(0) # 按任意键退出
Example #3
Source File: util.py From docassemble with MIT License | 6 votes |
def run_python_module(module, arguments=None): """Runs a python module, as though from the command line, and returns the output.""" if re.search(r'\.py$', module): module = this_thread.current_package + '.' + re.sub(r'\.py$', '', module) elif re.search(r'^\.', module): module = this_thread.current_package + module commands = [re.sub(r'/lib/python.*', '/bin/python3', docassemble.base.ocr.__file__), '-m', module] if arguments: if not isinstance(arguments, list): raise DAError("run_python_module: the arguments parameter must be in the form of a list") commands.extend(arguments) output = '' try: output = subprocess.check_output(commands, stderr=subprocess.STDOUT).decode() return_code = 0 except subprocess.CalledProcessError as err: output = err.output.decode() return_code = err.returncode return output, return_code
Example #4
Source File: read_zbar.py From pyzbar with MIT License | 6 votes |
def main(args=None): if args is None: args = sys.argv[1:] parser = argparse.ArgumentParser( description='Reads barcodes in images, using the zbar library' ) parser.add_argument('image', nargs='+') parser.add_argument( '-v', '--version', action='version', version='%(prog)s ' + pyzbar.__version__ ) args = parser.parse_args(args) from PIL import Image for image in args.image: for barcode in decode(Image.open(image)): print(barcode.data)
Example #5
Source File: util.py From docassemble with MIT License | 5 votes |
def map_of(*pargs, **kwargs): """Inserts into markup a Google Map representing the objects passed as arguments.""" the_map = {'markers': list()} all_args = list() for arg in pargs: if isinstance(arg, list): all_args.extend(arg) else: all_args.append(arg) for arg in all_args: if isinstance(arg, DAObject): markers = arg._map_info() if markers: for marker in markers: if 'icon' in marker and not isinstance(marker['icon'], dict): marker['icon'] = {'url': server.url_finder(marker['icon'])} if 'info' in marker and marker['info']: marker['info'] = markdown_to_html(marker['info'], trim=True) the_map['markers'].append(marker) if 'center' in kwargs: the_center = kwargs['center'] if callable(getattr(the_center, '_map_info', None)): markers = the_center._map_info() if markers: the_map['center'] = markers[0] if 'center' not in the_map and len(the_map['markers']): the_map['center'] = the_map['markers'][0] if len(the_map['markers']) or 'center' in the_map: return '[MAP ' + re.sub(r'\n', '', codecs.encode(json.dumps(the_map).encode('utf-8'), 'base64').decode()) + ']' return word('(Unable to display map)')
Example #6
Source File: qr_detector.py From study-picamera-examples with MIT License | 5 votes |
def draw_positions(self, frame, decoded_objs): for obj in decoded_objs: left, top, width, height = obj.rect frame = cv2.rectangle(frame, (left, top), (left + width, height + top), (0, 255, 0), 2) data = obj.data.decode('utf-8') return frame
Example #7
Source File: qrcode.py From platypush with MIT License | 5 votes |
def generate(self, content: str, output_file: Optional[str] = None, show: bool = False, format: str = 'png', camera_plugin: Optional[str] = None) -> QrcodeGeneratedResponse: """ Generate a QR code. If you configured the :class:`platypush.backend.http.HttpBackend` then you can also generate codes directly from the browser through ``http://<host>:<port>/qrcode?content=...``. :param content: Text, URL or content of the QR code. :param output_file: If set then the QR code will be exported in the specified image file. Otherwise, a base64-encoded representation of its binary content will be returned in the response as ``data``. :param show: If True, and if the device where the application runs has an active display, then the generated QR code will be shown on display. :param format: Output image format (default: ``png``). :param camera_plugin: If set then this plugin (e.g. ``camera`` or ``camera.pi``) will be used to capture live images from the camera and search for bar codes or QR-codes. :return: :class:`platypush.message.response.qrcode.QrcodeGeneratedResponse`. """ import qrcode qr = qrcode.make(content) img = qr.get_image() ret = { 'content': content, 'format': format, } if show: img.show() if output_file: output_file = os.path.abspath(os.path.expanduser(output_file)) img.save(output_file, format=format) ret['image_file'] = output_file else: f = io.BytesIO() img.save(f, format=format) ret['data'] = base64.encodebytes(f.getvalue()).decode() return QrcodeGeneratedResponse(**ret)
Example #8
Source File: qrcode.py From platypush with MIT License | 5 votes |
def decode(self, image_file: str) -> QrcodeDecodedResponse: """ Decode a QR code from an image file. :param image_file: Path of the image file. """ from pyzbar import pyzbar from PIL import Image image_file = os.path.abspath(os.path.expanduser(image_file)) img = Image.open(image_file) results = pyzbar.decode(img) return QrcodeDecodedResponse(results)
Example #9
Source File: qr.py From remi with Apache License 2.0 | 5 votes |
def process_image(self, **kwargs): try: image = Image.open(io.BytesIO(base64.b64decode(kwargs['image']))) except Exception: return qr_code_list = decode(image) if len(qr_code_list)>0: qr_code_data = qr_code_list[0][0].decode('utf-8') self.qr_label.set_text(qr_code_data) return
Example #10
Source File: test_useradm_enterprise.py From integration with Apache License 2.0 | 5 votes |
def _qr_dec(self, qr_b64): # decode png from temp inmem file b = base64.b64decode(qr_b64) f = io.BytesIO(b) image = Image.open(f) # decode qr code - results in a otpauth://... url in 'data' bytes dec = decode(image)[0] qs = parse.urlsplit(dec.data).query secret_b32 = parse.parse_qs(qs)[b"secret"][0] return secret_b32
Example #11
Source File: v2rayLui.py From v2rayL with GNU General Public License v3.0 | 5 votes |
def add_ss_by_input(self): """ 手动添加shadowsocks配置 :return: """ remark = self.ss_add_child_ui.lineEdit_2.text().strip() addr = self.ss_add_child_ui.lineEdit_3.text().strip() port = self.ss_add_child_ui.lineEdit_4.text().strip() password = self.ss_add_child_ui.lineEdit_5.text().strip() method = self.ss_add_child_ui.comboBox.currentText() # print(remark, addr, port, password, security) if not remark: remark = "shadowsocks_" + str(random.choice(range(10000, 99999))) b64str = "ss://"+base64.b64encode("{}:{}@{}:{}".format(method, password, addr, port).encode()).decode()\ + "#" + remark self.v2rayL.addconf(b64str) shell = "notify-send -i /etc/v2rayL/images/logo.ico v2rayL 添加成功" subprocess.call([shell], shell=True) self.v2rayL = V2rayL() self.display_all_conf() self.ss_add_child_ui.lineEdit_2.setText("") self.ss_add_child_ui.lineEdit_3.setText("") self.ss_add_child_ui.lineEdit_4.setText("") self.ss_add_child_ui.lineEdit_5.setText("") self.ss_add_ui.hide()
Example #12
Source File: v2rayLui.py From v2rayL with GNU General Public License v3.0 | 5 votes |
def get_conf_from_qr(self): """ 从二维码导入配置 :return: """ fname, ok = QFileDialog.getOpenFileName(self, '选择二维码图片', '/home', 'Image files(*.jpg *.png)') if ok: try: barcode = pyzbar.decode(Image.open(fname)) except: shell = "notify-send -i /etc/v2rayL/images/logo.ico v2rayL 二维码解析错误:无法解析该二维码" subprocess.call([shell], shell=True) else: try: self.v2rayL.addconf(barcode[0].data.decode("utf-8")) except MyException as e: shell = "notify-send -i /etc/v2rayL/images/logo.ico v2rayL '{}'".format("错误: " + e.args[0]) subprocess.call([shell], shell=True) except: shell = "notify-send -i /etc/v2rayL/images/logo.ico v2rayL 二维码解析错误:无法解析该二维码" subprocess.call([shell], shell=True) else: shell = "notify-send -i /etc/v2rayL/images/logo.ico v2rayL 添加配置成功" subprocess.call([shell], shell=True) self.v2rayL = V2rayL() self.display_all_conf()
Example #13
Source File: generate_fixture_images.py From hermit with Apache License 2.0 | 5 votes |
def generate_fixture_images(json_filename): filename_base = json_filename.split('.json')[0] with open(json_filename, 'r') as f: test_vector = json.load(f) data = json.dumps(test_vector['request']) data = data.encode('utf-8') data = gzip.compress(data) data = base64.b32encode(data) print(filename_base, "data length: ", len(data), " (must be <= 4296)") # qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=4 ) qr.add_data(data) qr.make(fit=True) image = qr.make_image(fill_color="black", back_color="white") image.save(filename_base + '.png') #loaded_image = Image.open(filename_base + '.png') #decoded = pyzbar.decode(loaded_image) image_array = np.array(image.convert('RGB'))[:, :, ::-1].copy() numpy.save(filename_base + '.npy',image_array)
Example #14
Source File: reader-webcam.py From HomePWN with GNU General Public License v3.0 | 5 votes |
def capture_qr(self, verbose, path, save_capture): """Get the webcam and wait for a qr image Args: verbose (Boolean): Verbose mode path (str): Path to store the image save_capture (Boolean): Set to true to save the image """ cap = cv2.VideoCapture(0) cap.set(3,640) cap.set(4,480) time.sleep(1) while(cap.isOpened()): ret, frame = cap.read() im = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) read = decode(im) cv2.imshow('frame',frame) if(read): display_qr(read, verbose) if(save_capture): cv2.imwrite(path, frame) cap.release() cv2.destroyAllWindows() break key = cv2.waitKey(1) if key & 0xFF == ord('q'): break
Example #15
Source File: util.py From docassemble with MIT License | 4 votes |
def read_qr(image_file, f=None, l=None, x=None, y=None, W=None, H=None): """Reads QR codes from a file or files and returns a list of codes found.""" if not (isinstance(image_file, DAFile) or isinstance(image_file, DAFileList)): return word("(Not a DAFile or DAFileList object)") if isinstance(image_file, DAFile): image_file = [image_file] pdf_to_ppm = get_config("pdftoppm") if pdf_to_ppm is None: pdf_to_ppm = 'pdftoppm' ocr_resolution = get_config("ocr dpi") if ocr_resolution is None: ocr_resolution = '300' file_list = list() temp_directory_list = list() for doc in image_file: if hasattr(doc, 'extension'): if doc.extension not in ['pdf', 'png', 'jpg', 'gif']: return word("(Not a readable image file)") path = doc.path() if doc.extension == 'pdf': directory = tempfile.mkdtemp() temp_directory_list.append(directory) prefix = os.path.join(directory, 'page') args = [pdf_to_ppm, '-r', str(ocr_resolution)] if f is not None: args.extend(['-f', str(f)]) if l is not None: args.extend(['-l', str(l)]) if x is not None: args.extend(['-x', str(x)]) if y is not None: args.extend(['-y', str(y)]) if W is not None: args.extend(['-W', str(W)]) if H is not None: args.extend(['-H', str(H)]) args.extend(['-png', path, prefix]) try: result = subprocess.run(args, timeout=3600).returncode except subprocess.TimeoutExpired: result = 1 logmessage("read_qr: call to pdftoppm took too long") if result > 0: return word("(Unable to extract images from PDF file)") file_list.extend(sorted([os.path.join(directory, f) for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))])) continue file_list.append(path) codes = list() for page in file_list: from pyzbar.pyzbar import decode for result in decode(Image.open(page)): codes.append(result.data.decode()) return codes
Example #16
Source File: v2rayLui.py From v2rayL with GNU General Public License v3.0 | 4 votes |
def add_vmess_by_input(self): """ 手动添加vmess配置 :return: """ remark = self.vmess_add_child_ui.lineEdit.text().strip() addr = self.vmess_add_child_ui.lineEdit_2.text().strip() port = self.vmess_add_child_ui.lineEdit_3.text().strip() uid = self.vmess_add_child_ui.lineEdit_4.text().strip() aid = self.vmess_add_child_ui.lineEdit_5.text().strip() net = self.vmess_add_child_ui.comboBox.currentText() types = self.vmess_add_child_ui.comboBox_2.currentText() host = self.vmess_add_child_ui.lineEdit_6.text().strip() path = self.vmess_add_child_ui.lineEdit_7.text().strip() tls = self.vmess_add_child_ui.comboBox_3.currentText() # print(remark, addr, port, password, security) if not remark: remark = "vmess_" + str(random.choice(range(10000, 99999))) conf = { 'add': addr, 'port': port, 'host': host, 'ps': remark, 'id': uid, 'aid': aid, 'net': net, 'type': types, 'path': path, 'tls': tls, "v": 2 } b64str = "vmess://" + base64.b64encode(str(conf).encode()).decode() self.v2rayL.addconf(b64str) shell = "notify-send -i /etc/v2rayL/images/logo.ico v2rayL 添加成功" subprocess.call([shell], shell=True) self.v2rayL = V2rayL() self.display_all_conf() self.vmess_add_child_ui.lineEdit.setText("") self.vmess_add_child_ui.lineEdit_2.setText("") self.vmess_add_child_ui.lineEdit_3.setText("") self.vmess_add_child_ui.lineEdit_4.setText("") self.vmess_add_child_ui.lineEdit_5.setText("") self.vmess_add_child_ui.lineEdit_6.setText("") self.vmess_add_child_ui.lineEdit_7.setText("") self.vmess_add_ui.hide()
Example #17
Source File: reader.py From hermit with Apache License 2.0 | 4 votes |
def _capture_qr_code_async() -> Optional[str]: capture = _start_camera() preview_dimensions = (640, 480) decoded_data = None encoded_data = None window_name = "Signature Request QR Code Scanner" cv2.namedWindow(window_name) while window_is_open(window_name): ret, frame = capture.read() frame = cv2.resize(frame, preview_dimensions) for qrcode in pyzbar.decode(frame): # Extract the position & dimensions of box bounding the QR # code (x, y, w, h) = qrcode.rect # Draw this bounding box on the image cv2.rectangle( frame, (x, y), (x + w, y + h), (0, 0, 255), 2) # Decode the QR code data encoded_data = qrcode.data try: decoded_data = decode_qr_code_data(encoded_data) except InvalidSignatureRequest as e: print("Invalid signature request: {}".format(str(e))) # Use the first QR code found if decoded_data is not None: break # Preview the (reversed) frame mirror = cv2.flip(frame, 1) cv2.imshow(window_name, mirror) # Break out of the loop if we found a valid QR code if decoded_data: break await asyncio.sleep(0.01) # Clean up windows before exiting. capture.release() cv2.destroyWindow(window_name) return decoded_data
Example #18
Source File: reader.py From HomePWN with GNU General Public License v3.0 | 4 votes |
def read_qr(self, verbose, path): """Reads the QR code to get the attributes Args: verbose (Boolean): Set to True to verbose mode path (str): Path to store the image """ try: read = decode(Image.open(path)) except: print_error("Error, file not found or not readable") return display_qr(read, verbose)
Example #19
Source File: wallet_runnable.py From wallets with Apache License 2.0 | 4 votes |
def initiate_ap(wallet, ledger_api): if wallet.temp_balance <= 0: print("You need some money first") return None # TODO: add a strict format checker to input here (and everywhere tbh) # Actual puzzle lockup/spend a_pubkey = wallet.get_next_public_key().serialize() b_pubkey = input("Enter recipient's pubkey: 0x") amount = -1 while amount > wallet.temp_balance or amount < 0: amount = input("Enter amount to give recipient: ") if amount == "q": return if not amount.isdigit(): amount = -1 amount = int(amount) APpuzzlehash = ap_wallet_a_functions.ap_get_new_puzzlehash( a_pubkey, b_pubkey) spend_bundle = wallet.generate_signed_transaction(amount, APpuzzlehash) await ledger_api.push_tx(tx=spend_bundle) print() print(f"{informative} AP Puzzlehash is: {str(APpuzzlehash)}") print(f"{informative} Pubkey used is: {hexlify(a_pubkey).decode('ascii')}") sig = str(ap_wallet_a_functions.ap_sign_output_newpuzzlehash( APpuzzlehash, wallet, a_pubkey).sig) print(f"{informative} Approved change signature is: {sig}") print() print("Give the AP wallet the following initialisation string -") print(f"{informative} Initialisation string: {str(APpuzzlehash)}:{hexlify(a_pubkey).decode('ascii')}:{sig}") print() print("The next step is to approve some contacts for the AP wallet to send to.") print("From another standard wallet press '4' to print out their puzzlehash for receiving money.") choice = "" while choice != "q": singlestr = input("Enter approved puzzlehash: ") if singlestr == "q": return puzzlehash = puzzlehash_from_string(singlestr) print() #print("Puzzle: " + str(puzzlehash)) sig = wallet.sign(puzzlehash, a_pubkey) #print("Signature: " + str(sig.sig)) name = input("Add a name for this puzzlehash: ") print("Give the following contact string to the AP wallet.") print(f"{informative} Contact string for AP Wallet: {name}:{str(puzzlehash)}:{str(sig.sig)}") choice = input("Press 'c' to continue, or 'q' to quit to menu: ")
Example #20
Source File: wallet_runnable.py From wallets with Apache License 2.0 | 4 votes |
def read_qr(wallet): amount = -1 if wallet.current_balance <= 0: print("You need some money first") return None print("Input filename of QR code: ") fn = input(prompt) decoded = decode(Image.open(fn)) puzzlehash = puzzlehash_from_string(decoded[0].data) while amount > wallet.temp_balance or amount <= 0: amount = input("Amount: ") if amount == "q": return if not amount.isdigit(): amount = -1 amount = int(amount) return wallet.generate_signed_transaction(amount, puzzlehash)
Example #21
Source File: wallet_runnable.py From wallets with Apache License 2.0 | 4 votes |
def print_my_details(wallet): print(f"{informative} Name: {wallet.name}") print(f"{informative} Pubkey: {hexlify(wallet.get_next_public_key().serialize()).decode('ascii')}") print(f"{informative} Puzzlehash: {wallet.get_new_puzzlehash()}")
Example #22
Source File: qrcode.py From platypush with MIT License | 4 votes |
def start_scanning(self, camera_plugin: Optional[str] = None, duration: Optional[float] = None, n_codes: Optional[int] = None) -> Optional[List[ResultModel]]: """ Decode QR-codes and bar codes using a camera. Triggers: - :class:`platypush.message.event.qrcode.QrcodeScannedEvent` when a code is successfully scanned. :param camera_plugin: Camera plugin (overrides default ``camera_plugin``). :param duration: How long the capturing phase should run (default: until ``stop_scanning`` or app termination). :param n_codes: Stop after decoding this number of codes (default: None). :return: When ``duration`` or ``n_codes`` are specified or ``stop_scanning`` is called, it will return a list of :class:`platypush.message.response.qrcode.ResultModel` instances with the scanned results, """ from pyzbar import pyzbar assert not self._capturing.is_set(), 'A capturing process is already running' camera = self._get_camera(camera_plugin) codes = [] last_results = {} last_results_timeout = 10.0 last_results_time = 0 self._capturing.set() try: with camera: start_time = time.time() while self._capturing.is_set() \ and (not duration or time.time() < start_time + duration) \ and (not n_codes or len(codes) < n_codes): output = camera.get_stream() with output.ready: output.ready.wait() img = self._convert_frame(output.raw_frame) results = pyzbar.decode(img) if results: results = [ result for result in QrcodeDecodedResponse(results).output['results'] if result['data'] not in last_results or time.time() >= last_results_time + last_results_timeout ] if results: codes.extend(results) get_bus().post(QrcodeScannedEvent(results=results)) last_results = {result['data']: result for result in results} last_results_time = time.time() finally: self._capturing.clear() return codes
Example #23
Source File: qr_detector.py From study-picamera-examples with MIT License | 4 votes |
def decode(self, frame): decoded_objs = pyzbar.decode(frame, scan_locations=True) for obj in decoded_objs: print(datetime.now().strftime('%H:%M:%S.%f')) print('Type: ', obj.type) print('Data: ', obj.data) return decoded_objs
Example #24
Source File: qr_detector.py From study-picamera-examples with MIT License | 4 votes |
def process_image(self, frame): decoded_objs = self.decode(frame) # 認識したQRコードの位置を描画する # frame = self.draw_positions(frame, decoded_objs) detected = False if len(decoded_objs) > 0: detected = True cv2.putText(frame, 'Detected: {}'.format(detected), (15, 30), cv2.FONT_HERSHEY_DUPLEX, 0.8, (0, 255, 0), 1) return frame
Example #25
Source File: pypyzbar.py From vrequest with MIT License | 4 votes |
def parse_rect_from_png_bytes(*a): pixbytes, w, h = screenshot_rect(s) deco = decode((pixbytes, w, h)) for i in deco: print(i)