def on_start_clicked(self, button): self.recognizer = face_recognizer.train_recognizer("./Database") img = face_functions.snap() predicted,conf = face_recognizer.recognize_face(self.recognizer, img) if(predicted==-1 or conf>50): message = Gtk.MessageDialog(self, 0, Gtk.MessageType.WARNING,Gtk.ButtonsType.CANCEL, "Face not recognized.") message.run() message.destroy() return message = Gtk.MessageDialog(self, 0, Gtk.MessageType.INFO,Gtk.ButtonsType.CANCEL, "Face recognized!") message.format_secondary_text("Recognized as subject "+str(predicted)+" with a doubt rating of "+str(conf)) message.run() message.destroy() d_barcode = barcode.get_barcode(img) if (len(d_barcode)>0): d_barcode=self.trim_barcode(d_barcode[0]) message = Gtk.MessageDialog(self, 0, Gtk.MessageType.INFO,Gtk.ButtonsType.CANCEL, "Barcode Detection") print(predicted) print("Barcode data found in this picture: " + str(d_barcode)) if (len(d_barcode)==0): message.format_secondary_text("Barcode not detected.") elif (int(predicted)==int(d_barcode)): message.format_secondary_text("Barcode detected:" + d_barcode + "\nMatches with face.") else: message.format_secondary_text("Barcode detected:" + d_barcode + "\nDoes not match face.") message.run() message.destroy()
def barcode(code, args=None): options = dict() if args is not None: arguments = args.split(',') for arg_pair in arguments: key, value = arg_pair.split('=') options[key] = int(value) import barcode from StringIO import StringIO from thirdparty import BarcodeImageWriter CODETYPE = 'code39' bc = barcode.get_barcode(CODETYPE) bc = bc(code, writer=BarcodeImageWriter(), add_checksum=False) bc.default_writer_options['quiet_zone'] = 6.4 bc.default_writer_options['dpi'] = 300 bc.default_writer_options['text_distance'] = 1.0 bc.default_writer_options['module_height'] = 10.0 # bc.default_writer_options['module_width'] = 0.3 bc.default_writer_options['font_size'] = int(bc.default_writer_options['dpi'] / 10) # update by custom arguments bc.default_writer_options.update(options) #write PNG image output = StringIO() bc.write(output) contents = output.getvalue().encode("base64") output.close() #return encoded base64 return str(contents)
def main(): st.title("Barcode detection app") image_file = st.file_uploader("Please upload your image:", type=['jpg', 'jpeg', 'png']) model = TinyYolo() if image_file is not None: imageText = st.empty() imageLocation = st.empty() imageText.text("Image uploaded") imageLocation.image(image_file) image_predicted = model.predict(image_file) if st.button("Launch barcode detection"): if image_predicted is not None: imageText.text("Image with barcode detected") imageLocation.image(image_predicted) barcode, info = get_barcode(image_file) if barcode is not None: st.success(f"Barcode : {barcode}") else: st.error(f"Cannot read barcode") st.title("Product info") if info and info.get("status"): st.write(info) else: st.write("Product not found")
def test_barcode(): N = 200 N_s = 50 k = int(N/5) w = .5 r = .6 vertices = get_image('C', 1, size=200, sample_size=N)[0] tangents = hm.find_tangents(vertices, k) curve = hm.get_curve(vertices, k = k, w = w) sparse = sparse_sample(vertices, N_s) v_s = vertices[sparse,:] t_s = tangents[sparse] c_s = curve[sparse] edges = hm.get_rips_complex(v_s, tangents=t_s, k = k, w = w, r = r) f, ax = plt.subplots(1,2) plt_edges, plt_barcode = ax plt_edges.scatter(v_s[:,0], v_s[:,1], marker = '.', c=c_s, s=200) for edge in edges: plt_edges.plot(v_s[edge, 0], v_s[edge, 1], lw = 1, c = 'blue') plt_edges.invert_yaxis() ordered_simplices, curve_lookup = hm.get_ordered_simplices(v_s, c_s, edges) barcode = bc.get_barcode(ordered_simplices, degree_values=c_s[np.argsort(c_s)]) b0 = barcode[barcode[:,2] == 0, :] bc.plot_barcode_gant(b0, plt=plt_barcode) plt.show()
def generate(request): context = { 'barcode_types': [b for b in barcode.PROVIDED_BARCODES if str(b).startswith('code')] + ['qrcode'] } if request.method == 'POST': b_type = request.POST['typeOfBarcode'] b_data = request.POST['barcodeData'] if b_type == 'qrcode': qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=1, ) qr.add_data(b_data) qr.make(fit=True) qr_file = qr.make_image(fill_color="black", back_color="white") # render qr image return generate_file(qr_file) # generate the file else: bar = barcode.get_barcode(name=b_type, code=b_data, writer=ImageWriter()) barcode_file = bar.render() # creates a PIL class image object return generate_file(barcode_file) # generate the file else: return render(request, 'generate_barcodes/generate.html', context=context)
def eanpng(request, broj): from barcode.writer import ImageWriter a = ImageWriter() a.dpi = 130 image = barcode.get_barcode('ean', broj, writer=a).render() response = HttpResponse(mimetype="image/png") image.save(response, "PNG") return response
def creaCodigoAux(): stamp = str(int(time.time() * 1000))[:12] ean = barcode.get_barcode('ean', stamp, writer=ImageWriter()) ean.save("sif/media/codes/" + stamp ) crea = CodigoBarras(codigo=stamp) crea.save() cofre = CodigoBarras.objects.get(id=crea.id) return cofre
def plot_barcode(vertices, edges = None, plt = plt, N_s = 50, k=4, r=.6, w=.5, annotate = False, triangulation='rips4'): vertices, tangents, curve, edges, simplices = hm.get_all(vertices, N_s, k, w, r, triangulation=triangulation, edges=edges) if edges is None: edges = _edges simplices = hm.get_ordered_simplices(vertices, curve, edges) barcode = bc.get_barcode(simplices, degree_values=curve[np.argsort(curve)]) plot_barcode_gant(barcode, plt = plt, annotate = annotate) try: plt.set_yticks([]) except: plt.gca().set_yticks([])
def get_fidelity_card(request, person_id): try: p = get_object_or_404(Personne, pk=person_id) except Http404: return reverse("population.views.get_person_by_barcode") ean = barcode.get_barcode('ean13', "2" + p.num_nat) return render_to_response("population/carte_fidelite.html", { "personne": p, "barcode":ean.render(), })
def get_fidelity_card(request, person_id): try: p = get_object_or_404(Personne, pk=person_id) except Http404: return reverse("population.views.get_person_by_barcode") ean = barcode.get_barcode('ean13', "2" + p.num_nat) return render_to_response("population/carte_fidelite.html", { "personne": p, "barcode": ean.render(), })
def run(self): """ Get barcode data. This function waits for the hardware scanner to read a barcode. The barcode something something something. """ while not self.stop_event.isSet(): barcode_data = barcode.get_barcode() self.callback(barcode_data)
def barcode_test(self, name): """Base module for all barcode testing""" assert self.data[name.lower()], "No test data available for {}".format( name) for datum in self.data[name.lower()]: (text, code) = datum coder = get_barcode(name, text=text) code2 = coder.encode(text) assert code == code2
def generate_barcode(code): image = barcode.get_barcode('code39') image_bar = image(code) image_bar.writer.dpi = 30 image_bar.default_writer_options['module_height'] = 10.583333333 image_bar.default_writer_options['module_width'] = 0.5291666667 image_bar.code = code bar = image_bar.render({}).decode("utf-8").replace('\n', '') return bar
def generate(self): (pos_x, pos_y) = self.svg.namedview.center return get_barcode( self.options.type, text=self.options.text, height=self.options.height, document=self.document, x=pos_x, y=pos_y, scale=self.svg.unittouu('1px'), ).generate()
def index(_): byte_io = BytesIO() ean = barcode.get_barcode('ean13', '4902102072618', writer=ImageWriter()) ean.write(byte_io) byte_io.seek(0) return send_file( byte_io, as_attachment=True, attachment_filename='barcode.png', mimetype='image/png', )
def __init__(self, barcode_type, code): self.barcode_type = barcode_type self.code = code writer = PdfStreamBarcodeWriter() # render everything here, since we need part of the rendering # operation's results to determine the box parameters to pass to # the parent b = barcode.get_barcode(self.barcode_type, code=code, writer=writer) self._barcode_commands = b.render() (w, h) = writer.size super().__init__(box=BoxConstraints(width=w, height=h))
def _graph_barcode(self, code, bc, width, height, pos, font): ''' Print Barcode for the provided string ''' if ImageWriter: writer = ImageWriter() writer.dpi = self.device.printer.dpi bcode = get_barcode(bc.lower(), code, writer=writer) img = bcode.render().convert('RGB') w, h = img.size img = img.crop((w / 10, 0, w - (w / 10), h - (w / 10) - (h / 10))) # FIXME # convert image for printable format pix_line, img_size = self._convert_image(img) # and print it self._print_image(pix_line, img_size) else: sys.stderr.write('PIL not found. Image output disabled.\n\n')
def test_distances(): letters = 'ABCDE' M = 5 N = 500 N_s = 30 k = int(N/5) w = .5 r = .6 barcodes = [] f, bax = plt.subplots(len(letters),M) f, iax = plt.subplots(len(letters),M) for i, letter in enumerate(letters): print("Doing {0}".format(letter)) for j in range(0, M): print("Doing {0}-{1}".format(letter, j)) idx = i * M + j vertices = get_image(letter, j, size=100, sample_size=N)[0] # v, t, c, e = hm.get_all_rips(vertices, N_s = N_s, k = k, r = r, w = w) v, t, c, e = hm.get_all_witness_4d(vertices, N_s = N_s, k = k, r = r, w = w) # v, t, c, e = hm.get_all_witness_4d(vertices, N_s = N_s, k = k, r = r, w = w) ordered_simplices = hm.get_ordered_simplices(v, c, e)[0] b = bc.get_barcode(ordered_simplices, degree_values=c[np.argsort(c)]) # b = b[b[:, 2] == 0, :] barcodes.append(b) bc.plot_barcode_gant(b, plt=bax[i][j]) plot_edges(v, e, iax[i][j]) print("Doing diffs...") M_b = len(barcodes) diffs = np.zeros([M_b,M_b]) inf = 1e14 for i in range(M_b): for j in range(M_b): diffs[i,j] = bc.barcode_diff(barcodes[i], barcodes[j], inf=inf) print("Diff ({0},{1}) = {2:1.3f}".format(i, j, diffs[i,j])) dmax = np.max(diffs[diffs < inf/100]) * 1.1 + 1 diffs[diffs > inf/100] = dmax plt.figure() plt.imshow(diffs, cmap='gray') plt.gca().set_xticklabels(list('-' + letters)) plt.gca().set_yticklabels(list('-' + letters)) plt.show()
def handle_noargs(self, **options): person_list = Person.objects.all() person_list = person_list.exclude(status='cancelled') # person_list = person_list.exclude(contact_type='V') person_list = person_list.filter(contact_type='V').order_by('last_name', 'first_name') file = open('public/contactes/img/9_acreditacions_voluntaris.svg') template_acreditacio = file.read() counter = 0 page_number = 0 new_acreditacio = template_acreditacio for person in person_list: # generate barcode ean = barcode.get_barcode('ean', str(person.id).zfill(12)) #save barcode filename = 'generated_files/acreditacions/barcode' ean.save(filename) # convert barcode svg in png os.system("inkscape -d 300 -z -f %s -j -a ""20:995:137:1020"" -e %s" % (filename + '.svg',filename + str(counter) + '.png')) filename = filename + str(counter) + '.png' # Rotate barcode os.system("convert -rotate 90 %s %s" % (filename, filename) ) # generate acreditacio new_acreditacio = new_acreditacio.replace('%codibarres' + str(counter) + '%', os.getcwd() + '/' + filename) new_acreditacio = new_acreditacio.replace('%nom' + str(counter) + '%',person.first_name.encode('utf-8')) new_acreditacio = new_acreditacio.replace('%llinatges' + str(counter) + '%',person.last_name.encode('utf-8')) new_acreditacio = new_acreditacio.replace('%lloc' + str(counter) + '%',person.home_province.encode('utf-8')) print "%d - %s - Pos %d" % (person.id, person.fullname, counter) counter = counter + 1 if counter == 9: save_acreditacions(new_acreditacio,page_number) new_acreditacio = template_acreditacio page_number = page_number + 1 counter = 0 if counter > 0: while counter < 9: new_acreditacio = new_acreditacio.replace('%codibarres' + str(counter) + '%', os.getcwd() + '/generated_files/acreditacions/emptybarcode.png') new_acreditacio = new_acreditacio.replace('%nom' + str(counter) + '%','') new_acreditacio = new_acreditacio.replace('%llinatges' + str(counter) + '%','') new_acreditacio = new_acreditacio.replace('%lloc' + str(counter) + '%','') counter = counter +1 save_acreditacions(new_acreditacio,page_number)
def _graph_barcode(self, code, bc, width, height, pos, font): ''' Print Barcode for the provided string ''' if ImageWriter: writer = ImageWriter() writer.dpi = self.device.printer.dpi bcode = get_barcode(bc.lower(), code, writer=writer) img = bcode.render().convert('RGB') w, h = img.size img = img.crop( (w / 10, 0, w - (w / 10), h - (w / 10) - (h / 10))) # FIXME # convert image for printable format pix_line, img_size = self._convert_image(img) # and print it self._print_image(pix_line, img_size) else: sys.stderr.write('PIL not found. Image output disabled.\n\n')
def register(): ''' Register User (Tests for the match code create_user) ''' rm = resources.model form = RegisterForm() fill_selects() weather = get_weather() if weather: track = db.session.query(rm.Track).filter_by(id=weather.track).first() else: track = False if not track: name = u"Трек не выбран" else: name = track.name g.session = weather.session if form.validate_on_submit(): # if request.form.getlist('agree'): if request.form.getlist('btn_ok'): rf = request.form user = rm.user_datastore.create_user(user_tag='', email=rf.getlist('email')[0], user_phone=rf.getlist('phone')[0]) userinfo = rm.UserInfo(user=user, user_lname=rf.getlist('lastname')[0].encode('utf-8'), user_fname=rf.getlist('firstname')[0].encode("utf-8"), user_patronymic=rf.getlist('patronymic')[0].encode("utf-8"), user_nickname=rf.getlist('nickname')[0].encode("utf-8"), user_status=1, user_why=' '.encode("utf-8")) db.session.add(userinfo) db.session.commit() usertag = "u"+generate_tag(user.id) db.session.query(rm.User).filter_by(id=user.id).update({'user_tag':usertag}) db.session.commit() ''' Generate barcode ''' # print usertag.encode('utf-8') ean = barcode.get_barcode('code39', usertag, writer=ImageWriter()) filename = ean.save('telemetriya/static/img/'+str(user.id)) return redirect('/created_user/%s' % userinfo.id) elif request.form.getlist('btn_cancel'): return redirect('/admin') else: if request.form.getlist('btn_cancel'): return redirect('/admin') elif request.form.getlist('btn_ok'): g.validator_not_passed = 1 return render_template('register.html', form=form, track=name, weather=weather)
def test(): if not os.path.isdir(TESTPATH): try: os.mkdir(TESTPATH) except OSError as e: print('Test not run.') print('Error:', e) sys.exit(1) objects = [] def append(x, y): objects.append(OBJECTS.format(filename=x, name=y)) def append_img(x, y): objects.append(IMAGES.format(filename=x, name=y)) options = dict(module_width=0.495, module_height=25.0) for codename, code in TESTCODES: bcode = get_barcode(codename, code) if codename.startswith('i'): options['center_text'] = False else: options['center_text'] = True filename = bcode.save(os.path.join(TESTPATH, codename), options) print('Code: {0}, Input: {1}, Output: {2}'.format( bcode.name, code, bcode.get_fullcode())) append(filename, bcode.name) if ImageWriter is not None: bcodec = get_barcode_class(codename) bcode = bcodec(code, writer=ImageWriter()) opts = dict(font_size=14, text_distance=1) if codename.startswith('i'): opts['center_text'] = False else: options['center_text'] = True filename = bcode.save(os.path.join(TESTPATH, codename), opts) append_img(filename, bcode.name) else: objects.append(NO_PIL) # Save htmlfile with all objects with codecs.open(HTMLFILE, 'w', encoding='utf-8') as f: obj = '\n'.join(objects) f.write(HTML.format(version=__version__, body=obj))
def distance_test(): letters = 'ABCDE' L = len(letters) M = 5 N = 500 N_s = 50 k = int(N/5) w = .7 r = .5 triangulation = 'alpha4' barcodes = [] f, bax = plt.subplots(len(letters),M) f, iax = plt.subplots(len(letters),M) for i, letter in enumerate(letters): for j in range(0, M): print("Doing {0}-{1}".format(letter, j)) idx = i * M + j vertices = get_image(letter, j, size=100, sample_size=N)[0] v, t, c, e, simplices = hm.get_all(vertices, N_s = N_s, k = k, r = r, w = w, triangulation=triangulation) b = bc.get_barcode(simplices, degree_values=c[np.argsort(c)]) b = b[b[:, 2] == 0, :] # Only 1-bars barcodes.append(b) plot_barcode_gant(b, plt=bax[i][j]) bax[i][j] plot_edges(v, e, iax[i][j]) std_plot(iax[i][j]) print("Doing diffs...") M_b = len(barcodes) diffs = np.zeros([M_b,M_b]) inf = 1e14 for i in range(M_b): for j in range(M_b): diffs[i,j] = bc.barcode_diff(barcodes[i], barcodes[j], inf=inf) # print("Diff ({0},{1}) = {2:1.3f}".format(i, j, diffs[i,j])) plt.figure() plot_diffs(diffs, letters, plt) plt.show()
def test_generating_barcodes(): os.makedirs(TESTPATH, exist_ok=True) objects = [] def append(x, y): objects.append(OBJECTS.format(filename=x, name=y)) def append_img(x, y): objects.append(IMAGES.format(filename=x, name=y)) options = {} for codename, code in TESTCODES: bcode = get_barcode(codename, code) if codename.startswith("i"): options["center_text"] = False else: options["center_text"] = True filename = bcode.save(os.path.join(TESTPATH, codename), options=options) print("Code: {}, Input: {}, Output: {}".format(bcode.name, code, bcode.get_fullcode())) append(os.path.basename(filename), bcode.name) if ImageWriter is not None: bcodec = get_barcode_class(codename) bcode = bcodec(code, writer=ImageWriter()) opts = {} if codename.startswith("i"): opts["center_text"] = False else: opts["center_text"] = True filename = bcode.save(os.path.join(TESTPATH, codename), options=opts) append_img(os.path.basename(filename), bcode.name) else: objects.append(NO_PIL) # Save htmlfile with all objects with codecs.open(HTMLFILE, "w", encoding="utf-8") as f: obj = "\n".join(objects) f.write(HTML.format(version=version, body=obj)) print(f"\nNow open {HTMLFILE} in your browser.")
def test_generating_barcodes(): os.makedirs(TESTPATH, exist_ok=True) objects = [] def append(x, y): objects.append(OBJECTS.format(filename=x, name=y)) def append_img(x, y): objects.append(IMAGES.format(filename=x, name=y)) options = {'module_width': 0.495, 'module_height': 25.0} for codename, code in TESTCODES: bcode = get_barcode(codename, code) if codename.startswith('i'): options['center_text'] = False else: options['center_text'] = True filename = bcode.save(os.path.join(TESTPATH, codename), options=options) print('Code: {0}, Input: {1}, Output: {2}'.format( bcode.name, code, bcode.get_fullcode())) append(os.path.basename(filename), bcode.name) if ImageWriter is not None: bcodec = get_barcode_class(codename) bcode = bcodec(code, writer=ImageWriter()) opts = {'font_size': 14, 'text_distance': 1} if codename.startswith('i'): opts['center_text'] = False else: opts['center_text'] = True filename = bcode.save(os.path.join(TESTPATH, codename), options=opts) append_img(os.path.basename(filename), bcode.name) else: objects.append(NO_PIL) # Save htmlfile with all objects with codecs.open(HTMLFILE, 'w', encoding='utf-8') as f: obj = '\n'.join(objects) f.write(HTML.format(version=version, body=obj)) print('\nNow open {htmlfile} in your browser.'.format(htmlfile=HTMLFILE))
def gen(encoding, fileName, text, width=300, height=100): """Returns 0 success; all else are errors. gen(encoding, fileName, text, width=300, height=100) note: geometry settings only valid for code128. """ if encoding not in codes: raise NotImplementedError("Unsupported encoding") return 2 if encoding == 'qr': #generate QR code qr_image = pyqrcode.MakeQRImage(text, br=True) fileHandle = file(fileName, 'w') qr_image.save(fileHandle, 'PNG') fileHandle.close() return 0 elif encoding == 'code128': #generate using Code128() by Jostein Leira bar = Code128() bar.getImage(text, fileName, 300, 100) return 0 else: #generate barcode pre = barcode.get_barcode(encoding, text, writer=ImageWriter()) save = pre.save(fileName) out = Image.open(save) #crop the image if encoding == 'code39': out = out.crop((28, 10, out.size[0] - 24, 180)) os.unlink(save) fileHandle = file(fileName, 'w') out.save(fileHandle, 'PNG') fileHandle.close() return 0
def gen(encoding, fileName, text, width=300, height=100): """Returns 0 success; all else are errors. gen(encoding, fileName, text, width=300, height=100) note: geometry settings only valid for code128. """ if encoding not in codes: raise NotImplementedError("Unsupported encoding") return 2 if encoding == 'qr': #generate QR code qr_image = pyqrcode.MakeQRImage(text, br = True) fileHandle = file(fileName, 'w') qr_image.save(fileHandle, 'PNG') fileHandle.close() return 0 elif encoding == 'code128': #generate using Code128() by Jostein Leira bar = Code128() bar.getImage(text, fileName, 300, 100) return 0 else: #generate barcode pre = barcode.get_barcode(encoding, text, writer=ImageWriter()) save = pre.save(fileName) out = Image.open(save) #crop the image if encoding == 'code39': out = out.crop((28, 10, out.size[0]-24, 180)) os.unlink(save) fileHandle = file(fileName, 'w') out.save(fileHandle, 'PNG') fileHandle.close() return 0
def process_image_barcode(): img_counter = 0 cam = cv2.VideoCapture(0) cam.set(6, 24) cv2.namedWindow("test") while (True): ret, frame = cam.read() frame = cv2.flip(frame, 1) cv2.rectangle(frame, (500, 250), (900, 500), (255, 0, 0), 3) cv2.imshow("test", frame) img_name = "latest.jpg" roi = frame[250:500, 500:900] roi = cv2.flip(roi, 1) lab = cv2.cvtColor(roi, cv2.COLOR_BGR2LAB) l, a, b = cv2.split(lab) clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8, 8)) cl = clahe.apply(l) limg = cv2.merge((cl, a, b)) roi = cv2.cvtColor(limg, cv2.COLOR_LAB2BGR) cv2_im = cv2.cvtColor(roi, cv2.COLOR_BGR2RGB) pil_im = Image.fromarray(cv2_im) cv2.waitKey(1) product_barcode = barcode.get_barcode(pil_im) if product_barcode is not None: #cv2.imshow("contrast",cv2_im) #cv2.waitKey(0) print("found") cv2.rectangle(frame, (500, 250), (900, 500), (0, 255, 0), 3) cv2.imshow("test", frame) cv2.waitKey(10) time.sleep(1) cam.release() cv2.destroyAllWindows() client = vision.ImageAnnotatorClient() return product_barcode
def test_filtration(): N = 200 N_s = 50 k = int(N/5) w = .5 r = .6 vertices = get_image('A', 2, size=200, sample_size=N)[0] tangents = hm.find_tangents(vertices, k) curve = hm.get_curve(vertices, k = k, w = w) sparse = sparse_sample(vertices, N_s) v_s = vertices[sparse,:] t_s = tangents[sparse] c_s = curve[sparse] edges = hm.get_rips_complex(v_s, tangents=t_s, k = k, w = w, r = r) simplices, curve_lookup = hm.get_ordered_simplices(v_s, c_s, edges) max_degree = np.max(simplices[:,3]) degree_step = math.ceil(max_degree/16.0) verts_degree = simplices[simplices[:,4] == 0,0:3] f, ax = plt.subplots(4,4, sharex=True, sharey=True) ax[0][0].invert_yaxis() for i in range(4): for j in range(4): idx = i*4 + j deg = min(idx * degree_step, max_degree) plot_simplices(simplices, deg, v_s, ax[i][j]) ax[i][j].set_title("κ={0:1.4f}".format(curve[verts_degree[deg,0]]), fontsize=8) ax[i][j].set_xticklabels([]) ax[i][j].set_yticklabels([]) plt.tight_layout() plt.figure() barcode = bc.get_barcode(simplices, degree_values=c_s[np.argsort(c_s)]) b0 = barcode[barcode[:,2] == 0, :] bc.plot_barcode_gant(b0, plt=plt) plt.show()
def test_code39_checksum(): code39 = get_barcode('code39', 'Code39') assert 'CODE39W' == code39.get_fullcode()
) def test(): if not os.path.isdir(TESTPATH): try: os.mkdir(TESTPATH) except OSError, e: print('Test not run.') print('Error:', e) sys.exit(1) objects = [] append = lambda x, y: objects.append(OBJECTS.format(filename=x, name=y)) append_img = lambda x, y: objects.append(IMAGES.format(filename=x, name=y)) for codename, code in TESTCODES: bcode = get_barcode(codename, code) filename = bcode.save(os.path.join(TESTPATH, codename)) print('Code: ', bcode.name, ', digits: ', bcode.digits) append(filename, bcode.name) if ImageWriter is not None: bcodec = get_barcode_class(codename) bcode = bcodec(code, writer=ImageWriter()) filename = bcode.save(os.path.join(TESTPATH, codename), font_size=14, text_distance=1) append_img(filename, bcode.name) else: objects.append(NO_PIL) # Save htmlfile with all objects with codecs.open(HTMLFILE, 'w', encoding='utf-8') as f: obj = '\n'.join(objects) f.write(HTML.format(version=__version__, body=obj))
def test_pzn_checksum(): pzn = get_barcode('pzn', '103940') assert 'PZN-1039406' == pzn.get_fullcode()
def test_gs1_128_checksum(): gs1_128 = get_barcode('gs1_128', '00376401856400470087') assert '00376401856400470087' == gs1_128.get_fullcode()
def test_ean14_checksum(): ean = get_barcode('ean14', '1234567891258') assert '12345678912589' == ean.get_fullcode()
def test_jan_checksum(): jan = get_barcode('jan', '491400614457') assert '4914006144575' == jan.get_fullcode()
def test_ean8(self): ref = ('1010100011000110100100110101111010101000100' '100010011100101001000101') ean = get_barcode('ean8', '40267708') bc = ean.build() self.assertEqual(ref, bc[0])
La vista creaCodigo: Crea un codigo sin necesidad de formulario, solo le hace falta hacer un request post y automaticamente genera un codigo con ID unico y redirige a otro template donde se ve el codigo y la imagen del codigo generado ''' def creaCodigo(request): informacion = "Inicia" if request.method == "POST": <<<<<<< HEAD formulario = FormuCrea(request.POST) if formulario.is_valid(): informacion = "pasa post" EAN = barcode.get_barcode_class('ean13') codigo = formulario.cleaned_data['codigo'] ean = barcode.get_barcode('ean', codigo, writer=ImageWriter()) aux = int(codigo) / 10 ean.save("sif/media/codes/" + str(aux) ) crea = CodigoBarras(codigo=aux) crea.save() informacion = "Terminado" return HttpResponseRedirect('/codigoBarras/%s' %crea.id) else: formulario = FormuCrea() ======= informacion = "pasa post" EAN = barcode.get_barcode_class('ean13') #En esta linea creo un ID0 basado en el tiempo de Unix a prueba de Hash Collision stamp = str((int(time.time())*100)+(datetime.datetime.now().second+10))
def test(): if not os.path.isdir(TESTPATH): try: os.mkdir(TESTPATH) except OSError, e: print('Test not run.') print('Error:', e) sys.exit(1) objects = [] append = lambda x, y: objects.append(OBJECTS.format(filename=x, name=y)) append_img = lambda x, y: objects.append(IMAGES.format(filename=x, name=y)) options = dict(module_width=0.495, module_height=25.0) for codename, code in TESTCODES: bcode = get_barcode(codename, code) filename = bcode.save(os.path.join(TESTPATH, codename)) print('Code: {0}, Input: {1}, Output: {2}'.format( bcode.name, code, bcode.get_fullcode())) append(filename, bcode.name) if ImageWriter is not None: bcodec = get_barcode_class(codename) bcode = bcodec(code, writer=ImageWriter()) opts = dict(font_size=14, text_distance=1) if codename.startswith('i'): opts['center_text'] = False filename = bcode.save(os.path.join(TESTPATH, codename), opts) append_img(filename, bcode.name) else: objects.append(NO_PIL) # Save htmlfile with all objects
def test_isbn10_checksum(): isbn = get_barcode('isbn10', '376926085') assert '3769260856' == isbn.isbn10
while (1): row = cursor.fetchone () if row == None: break else: isbns[row[0]] = row[1] except MySQLdb.Error, e: print "Error %d: %s" % (e.args[0], e.args[1]) sys.exit (1) #print isbns for isbn in isbns: title = isbns[isbn] print isbn print title if(len(isbn)) == 13: isbnBarcode = barcode.get_barcode('isbn13', str(isbn), writer=ImageWriter()) isbnBarcode.get_fullcode() else: isbnBarcode = barcode.get_barcode('isbn', str(isbn), writer=ImageWriter()) # title = re.sub('[^A-Za-z0-9\ ]+', '', title) # asciititle = title.decode('utf-8').encode('ascii', 'ignore') # print asciititle filename = isbnBarcode.save('../isbn_barcodes/' + isbn ) conn.close ()
def test_isbn13_checksum(): isbn = get_barcode('isbn13', '978376926085') assert '9783769260854' == isbn.get_fullcode()