def search(): name = request.form["searchbox"] capture = cv2.VideoCapture(0) # capture = cv2.VideoCapture(1) 外接摄像头 ff, ret = capture.read() h, w, ch = ret.shape # 获取shape的数值,height和width、通道 # 新建全零图片数组src2,将height和width,类型设置为原图片的通道类型(色素全为零,输出为全黑图片) a = 1.5 g = 10 src2 = np.zeros([h, w, ch], ret.dtype) dst = cv2.addWeighted(ret, a, src2, 1 - a, g) # addWeighted函数说明如下 dst = cv2.fastNlMeansDenoisingColored(dst, None, 10, 10, 7, 21) sp = ret.shape height = sp[0] # height(rows) of image width = sp[1] # width(colums) of image print(height) img1 = dst[0:height, 0:int(width / 3)] img2 = dst[0:height, int(width / 3):int(width * 2 / 3)] img3 = dst[0:height, int(width * 2 / 3):width - 1] img1 = rotate_about_center(img1, 90, 1) img2 = rotate_about_center(img2, 90, 1) img3 = rotate_about_center(img3, 90, 1) # cv2.imwrite("1.jpg", img1) # cv2.imwrite("2.jpg", img2) # cv2.imwrite("3.jpg", img3) flag = True try: regImage1 = "1.jpg" barcode1 = zxing.BarCodeReader().decode(regImage1) print(barcode1.parsed) if (barcode1.parsed == '9780684801223' and name == 'The Old Man And The Sea'): print('The Old Man And The Sea') os.system("python3 low_level_right.py") else: regImage2 = "2.jpg" barcode2 = zxing.BarCodeReader().decode(regImage2) print(barcode2.parsed) if (barcode2.parsed == '9787512508712' and name == 'Othello'): print('Othello') os.system("python3 low_level_left.py") flag = True else: flag = False except: flag = False if (flag == False and name == "宴山亭"): flag = True os.system("python3 low_level.py") #识别 # print(name) # start() # os.system("python3 low_level.py") if (flag == False): return render_template('404.html') return render_template('index.html')
def red(im): reader = zxing.BarCodeReader(java='java') barcode = reader.decode( im, try_harder=True) # ,possible_formats ='ITF')#possible_formats ='ITF' print(barcode) return barcode
def read(filename): reader = zxing.BarCodeReader() decoded = reader.decode(filename) if decoded: return decoded.parsed else: return ""
def qrcode_zxing(self, image, temp_flag=False): zx = zxing.BarCodeReader() zxing_img_temp_dir = os.path.join(os.path.abspath('.'), 'zxing_img_temp_dir') os.makedirs(zxing_img_temp_dir, exist_ok=True) save_path = os.path.join(zxing_img_temp_dir, f"test_{uuid.uuid1()}.jpg") if isinstance(image, np.ndarray): cv2.imwrite(save_path, image) image = save_path temp_flag = True elif isinstance(image, bytes): # 读取到图片 image = Image.open(BytesIO(image)) # image.show('test') image.save(save_path) image = save_path temp_flag = True try: zxdata = zx.decode(image) # 图片解码 except Exception as e: logger.error(e.args) # 删除临时文件 if temp_flag and os.path.exists(image): os.remove(image) return zxdata
def qrcode2url(img): """ 将二维码转化成URL :param img: ndarray or fname :return: """ flag = False if (isinstance(img, str)): print('str') fname = img else: try: img = np.array(img, dtype=np.uint8) except: pass fname = '/tmp/tmp.jpg' cv2.imwrite(fname, img) flag = True # check if file exist. if not os.path.isfile(fname): raise Exception("%s is not a file." % img) reader = zxing.BarCodeReader() barcode = reader.decode(fname) url = barcode.parsed if flag: os.system('rm %s' % fname) return url
def ocr_qrcode_zxing(filename): img = Image.open(filename) ran = int(random.random() * 100000) img.save('%s%s.jpg' % (os.path.basename(filename).split('.')[0], ran)) zx = zxing.BarCodeReader() data = '' zxdata = zx.decode('%s%s.jpg' % (os.path.basename(filename).split('.')[0], ran)) # 删除临时文件 os.remove('%s%s.jpg' % (os.path.basename(filename).split('.')[0], ran)) if zxdata: #logger.debug(u'zxing识别二维码:%s,内容: %s' %(filename ,zxdata.data)) print(zxdata.points) if(len(zxdata.points)): calculate(zxdata.points) '''class BarCode: format = "" 四个角位置points = [leftdown,lefton,righton,rightdown] data = "" 读取的内容raw = ""''' #data = zxdata.data else: logger.error(u'识别zxing二维码出错:%s' %(filename)) img.save('%s-zxing.jpg' %filename) return data
def read_QR_code1(img_path): logger = logging.getLogger(__name__) if not logger.handlers: logging.basicConfig(level=logging.INFO) DEBUG = (logging.getLevelName(logger.getEffectiveLevel()) == 'DEBUG') # 在当前目录生成临时文件,规避java的路径问题 img = Image.open(img_path) ran = int(random.random() * 100000) img.save('%s%s.jpg' % (os.path.basename(img_path).split('.')[0], ran)) zx = zxing.BarCodeReader() data = '' zxing_data = zx.decode('%s%s.jpg' % (os.path.basename(img_path).split('.')[0], ran)) # 删除临时文件 os.remove('%s%s.jpg' % (os.path.basename(img_path).split('.')[0], ran)) if zxing_data: logger.debug(u'zxing识别二维码:%s,内容: %s' % (img_path, zxing_data.parsed)) data = zxing_data.parsed else: logger.error(u'识别zxing二维码出错:%s' % img_path) # img.save('%s-zxing.jpg' % img_path) return data
def get_qrcode(self): self.img_url = self.driver.find_element_by_xpath( "// *[ @ alt = '二维码']") time.sleep(2) print(self.img_url) self.relimg_ulr = self.img_url.get_attribute("src") print(self.relimg_ulr) # 保存图片到指定路径 if self.relimg_ulr != None: filename = '/qcode.jpg' # 保存图片数据 data = urllib.request.urlopen(self.relimg_ulr).read() filepath = os.path.join(os.getcwd(), 'img') print("112223444") print(filepath) f = open(filepath + filename, 'wb') f.write(data) f.close() reader = zxing.BarCodeReader() path = os.path.join(os.getcwd(), 'img') filepath = path + "/qcode.jpg" print(filepath) barcode = reader.decode(filepath) codelist = str(barcode).split("'") return codelist
def recover_data_from_lables(lables, lables_to_bits, qr_shape, qr_margin): qr = Image.new('1', qr_shape, 1) pix = qr.load() reader = zxing.BarCodeReader() data = [] for color in range(0, len(lables_to_bits[0])): i = 0 for x in range(qr_margin[0], qr_shape[0] - qr_margin[0]): for y in range(qr_margin[1], qr_shape[1] - qr_margin[1]): pix[y, x] = (lables_to_bits[lables[i]][color]) i += 1 #plt.subplot(122), plt.imshow(qr), plt.title('qr') zbar_code = decode(qr) if not zbar_code: qr.save('tmp.jpeg', 'jpeg') zxing_code = reader.decode("tmp.jpeg", True) if not zxing_code: continue else: # print(zxing_code) data.append(zxing_code.raw) else: # print(zbar_code) data.append(zbar_code[0].data) return data
def qrcode_to_data(filename): """ 二维码解析 代码来源:https://www.cnblogs.com/zhongtang/p/7148375.html 修改部分代码,子调用时会无法解析原因为zxing调用java包,需要考虑路径问题 :param filename: :return: """ img = Image.open(filename) # 先用pyzbar包解析,如果解析不成功则用zxing模块解析 data = pyzbar.decode(img, symbols=[pyzbar.ZBarSymbol.QRCODE]) if data: return data[0].data.decode('utf-8') else: ran = int(random.random() * 100000) img.save('%s%s.png' % (os.path.basename(filename).split('.')[0], ran)) zx = zxing.BarCodeReader() zxdata = zx.decode('%s%s.png' % (os.path.basename(filename).split('.')[0], ran)) # 删除临时文件 os.remove('%s%s.png' % (os.path.basename(filename).split('.')[0], ran)) if zxdata: return zxdata.parsed else: img.save('%s-zxing.png' % filename)
def ocr_qrcode_zxing(filename): zx = zxing.BarCodeReader() #调用zxing二维码读取包 data = '' zxdata = zx.decode(filename) #图片解码 if zxdata: data = zxdata return data.raw #返回记录的内容
def scan(self): reader = zxing.BarCodeReader() barcode = reader.decode(self.photo) if barcode != None: print(barcode.parsed) # 二维码识别内容 else: print("cant find the QR code")
def test(): reader = zxing.BarCodeReader() shutil.copy( "C:\\Users\\admin\\PycharmProjects\\jiliangyuan_classify\\data\\test.jpg", "tmp\\tmp.jpg") barcode = reader.decode("tmp/tmp.jpg") os.remove("tmp\\tmp.jpg") return barcode.parsed
def test_decoding(): reader = zxing.BarCodeReader() for filename, expected in test_barcodes: path = os.path.join(test_barcode_dir, filename) logging.debug('Trying to parse {}, expecting {!r}.'.format(path, expected)) dec = reader.decode(path) if dec.parsed != expected: raise AssertionError('Expected {!r} but got {!r}'.format(expected, dec.parsed))
def barcode_decode(pic_path): import zxing reader = zxing.BarCodeReader() barcode = reader.decode(pic_path) if barcode is not None: print(barcode.parsed, end='') else: print('Empty QR Code!')
def decode_qrcode_image(image_file): """ 通过一个二维码图片提取对应的URL @param image_file: 二维码图片 @return:二维码中包含的URL """ reader = zxing.BarCodeReader() barcode = reader.decode(image_file) return barcode.parsed
def checkEngineerInput(self, EngineerInput): while True: if EngineerInput == "1": # Login by QR code reader = zxing.BarCodeReader() # Build a list of tuples for each file type the file dialog should display my_filetypes = [('all files', '.*'), ('text files', '.txt')] # Ask the user to select a single file name. path = filedialog.askopenfilename( initialdir=os.getcwd(), title="Please select a file:", filetypes=my_filetypes) if path == "": break # decode QR barcode = reader.decode(path) username = barcode.parsed.split(', ')[0] password = barcode.parsed.split(', ')[1] message = [ "CheckEngineerIdentity", username, password, self.carid ] elif EngineerInput == "2": # Login by username and password username = input("Enter username (Leave blank to quit) : ") if (not username): return password = getpass("Enter Password: "******"CheckEngineerIdentity", username, password, self.carid ] # Receive login reply self.s.sendall(pickle.dumps(message)) data = pickle.loads(self.s.recv(4096)) if data[0] == "True": # True message = ["Repair", self.carid] self.s.sendall(pickle.dumps(message)) data = pickle.loads(self.s.recv(4096)) # Send and Receive Repair reply if data[0] == "True": # True print() print("Start repairing the car") time.sleep(2) print() print("The car has been repaired") return else: # False print() print("The car does not need to be repaired") return else: # False print("Username or Password is incorrect")
def Read_QR(img): reader = zxing.BarCodeReader() barcode = reader.decode(img) if barcode.type == None: return "Fail to read" return barcode.parsed
def qrcode(path): reader = zxing.BarCodeReader() barcode = reader.decode(path) if barcode is None: boo = False link = "Does not exist" else: boo = True link = barcode.raw return boo, link
def analyzeQRCode(fileName): zx = zxing.BarCodeReader() zxData = zx.decode(fileName) if zxData: # print(zxData) a = zxData.__getattribute__("raw") print(a) else: print("none") pass
def get_zxing_qr_data(image_path): zxing_reader = zxing.BarCodeReader() zxing_qr_data = zxing_reader.decode(image_path, try_harder=True) if zxing_qr_data is not None: qr_data = json.loads(zxing_qr_data.parsed) else: qr_data = {'rb_id': None, 'set_id': None, 'name': None, 'page': None} return qr_data
def test_barcode_readability(self): r = zxing.BarCodeReader() # FIXME: ZXing command-line runner tries to coerce everything to UTF-8, so we can only reliably # encode and decode characters in the intersection of utf-8 and iso8559-1. self._encode_and_decode(r, 'Wikipedia, the free encyclopedia', ec_percent=0) self._encode_and_decode(r, 'Wow. Much error. Very correction. Amaze', ec_percent=95) self._encode_and_decode(r, '¿Cuánto cuesta?')
def read_zxing(jpgfile): global zxing_recognized result = "NULL" reader = zxing.BarCodeReader( "/home/parshin/PycharmProjects/barcode_reader/zxing") result = reader.decode(jpgfile) if result is not None: zxing_recognized += 1 return result.data else: return "NULL"
def qr_login(): headers = { 'Connection': 'keep-alive', 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64)', } status = True s = requests.session() try: while status is True: result = get_qrcode() imgurl = result[0] token = result[1] res = s.get(imgurl, headers=headers, cookies=cookies) content = res.content f = open('image.png', 'wb') f.write(content) f.close() reader = zxing.BarCodeReader() raw = reader.decode("image.png").raw url = pyqrcode.create(raw) print(url.terminal(quiet_zone=1)) start = time.time() while True: if time.time() - start < 120: url = 'https://www.zhihu.com/api/v3/account/api/login/qrcode/{}/scan_info'.format(token) res = s.get(url, headers=headers) if res.status_code == 200: content = res.json() if 'status' in content: if content['status'] == 1: print('扫码成功 请确认登陆') continue else: print('成功确认登陆') cookies_dict = res.cookies.get_dict() for key in cookies_dict: cookies.set(key, cookies_dict[key]) q_c0 = content['cookie']['q_c0'] z_c0 = content['cookie']['z_c0'] cookies.set('q_c0', q_c0) cookies.set('z_c0', z_c0) save_cookies() os.system('cls') return True else: print('二维码已经过期 重新加载二维码') status = False time.sleep(5) os.system('cls') break qr_login() except Exception: return False
def main(): while True: im = ImageGrab.grab() im.save('temp.png') zx = zxing.BarCodeReader() code = zx.decode('temp.png', ) if code and code.raw: text = bytes.decode(zlib.decompress(base64.b64decode(code.raw)), 'utf-8') print(text) pyperclip.copy(text) time.sleep(.5)
def test_barcode_readability_eci(self): r = zxing.BarCodeReader() # Released versions of ZXing <=3.4.1, don't correctly decode ECI or FNC1 in Aztec (https://github.com/zxing/zxing/issues/1327), # so we don't have a way to test readability of barcodes containing characters not in iso8559-1. # Now that https://github.com/zxing/zxing/pull/1328 is merged, we should be able to decode them correctly on # subsequent releases. if r.zxing_version_info <= (3, 4, 1): raise unittest.SkipTest("Running with ZXing v{}, which can't decode non-iso8859-1 charsets in Aztec Code".format(r.zxing_version)) self._encode_and_decode(r, 'The price is €4', encoding='utf-8') self._encode_and_decode(r, 'אין לי מושג', encoding='iso8859-8')
def r_decode(file_name): image_file = file_name img = cv2.imread(image_file) temp_name = "temp.jpg" cv2.imwrite(temp_name, img) zx = zxing.BarCodeReader() data = zx.decode(temp_name) os.remove(temp_name) if data == None: return None return data.raw
def _qr_decode_one_file(img_file): ''' compute signal file :param img_file: QR code path :return: string decoded code ''' reader = zxing.BarCodeReader() print('decode img {}...'.format(img_file)) barcode = reader.decode('./upload/{}'.format(img_file)) ret = barcode.parsed print('root is {}'.format(ret)) return ret
def test_barcode_readability(self): r = zxing.BarCodeReader() # FIXME: ZXing command-line runner tries to coerce everything to UTF-8, at least on Linux, # so we can only reliably encode and decode characters that are in the intersection of utf-8 # and iso8559-1 (though with ZXing >3.4.1, the iso8559-1 requirement is relaxed; see below). # # More discussion at: https://github.com/dlenski/python-zxing/issues/17#issuecomment-905728212 # Proposed solution: https://github.com/dlenski/python-zxing/issues/19 self._encode_and_decode(r, 'Wikipedia, the free encyclopedia', ec_percent=0) self._encode_and_decode(r, 'Wow. Much error. Very correction. Amaze', ec_percent=95) self._encode_and_decode(r, '¿Cuánto cuesta?')
def test_against_zxing(): test_number = 0 success = 0 failure = 0 zxing_success = 0 zxing_failure = 0 while (True): test_number += 1 # Randomize barcode settings columns = 10 #random.randint(5,15) security_level = 3 #random.randint(2,5) scale = 2 #random.randint(2,5) ratio = 2 #random.randint(2,4) # With random text valid for a PDF417 barcode text_length = 300 #random.randint(1, 5) * 50 text = ''.join(random.choices(string.ascii_letters + string.digits + "&,:#-.$/+%* =^;<>@[\\]_'~!|()?{}", k=text_length)) # and Create the barcode. barcode = BarcodeTest(text, columns, security_level, scale, ratio) barcode.CrappifiedImage.save("barcode.png") # Start decoding try: reader = zxing.BarCodeReader() decodedZxing = reader.decode("barcode.png", possible_formats="PDF_417").parsed except: decodedZxing = '' try: decoder = PDF417Decoder(barcode.CrappifiedImage) barcode_count = decoder.decode() if (barcode_count == 0): decoded = '' else: decoded = decoder.barcode_data_index_to_string(0) except: decoded = '' if (decoded == barcode.EncodedData): success += 1 else: failure += 1 if (decodedZxing == barcode.EncodedData): zxing_success += 1 else: zxing_failure += 1 print(f"Success: {success} - Failure: {failure} - ZXing Success: {zxing_success} - ZXing: Failure {zxing_failure} - Total: {test_number}")