def read_qr(frame, file_loc="C:\yash_kumar\qrcode"): ch = 3 if ch == 2: print("Current Folder Location : " + file_loc) import os os.chdir(file_loc) img_list = [] num = 0 for i in os.listdir(): if ".jpg" in i: print(num + 1, '.) ' + i) img_list.append(i) num = num + 1 img_num = int(input("Enter PNG Image number : ")) file = file_loc + "\\" + img_list[img_num - 1] img = cv2.imread(file) detector = cv2.QRCodeDetector() if detector: data, bbox, straight_qrcode = detector.detectAndDecode(img) print(">>>", data) else: print("No Data Found") else: detector = cv2.QRCodeDetector() if detector: data, bbox, straight_qrcode = detector.detectAndDecode(frame) return (data) else: pass
def run(self): """ Read the camera continuosly and add the read code to the result dictionary. """ # initalize the cam try: cap = cv2.VideoCapture(0) # initialize the cv2 QRCode detector detector = cv2.QRCodeDetector() while True: _, img = cap.read() barcodes = pyzbar.decode(img) if barcodes: print("Decoded code =", barcodes[0].data, barcodes[0].data.decode("utf-8")) self.result[self.name] = barcodes[0].data.decode("utf-8") break if cv2.waitKey(1) == ord("q"): break except: print(self.name, "Exception") finally: cap.release() print("released camera") sys.exit(0)
def DetectQRFrmImage(self, inputfile): inputimg = cv.imread(inputfile, cv.IMREAD_COLOR) if inputimg is None: print('ERROR: Can not read image: {}'.format(inputfile)) return print('Run {:s} on image [{:d}x{:d}]'.format(self.getQRModeString(), inputimg.shape[1], inputimg.shape[0])) qrCode = cv.QRCodeDetector() count = 10 timer = cv.TickMeter() for _ in range(count): timer.start() points, decode_info = self.runQR(qrCode, inputimg) timer.stop() fps = count / timer.getTimeSec() print('FPS: {}'.format(fps)) result = inputimg self.drawQRCodeResults(result, points, decode_info, fps) cv.imshow("QR", result) cv.waitKey(1) if self.out != '': outfile = self.fname + self.fext print("Saving Result: {}".format(outfile)) cv.imwrite(outfile, result) print("Press any key to exit ...") cv.waitKey(0) print("Exit")
def scan(p): x = f"{p}.png" img = cv2.imread(x) detector = cv2.QRCodeDetector() data, bbox, straight_qrcode = detector.detectAndDecode(img) z=data.split("-")[1] return(int(z))
def QRReader(index): img = cv2.imread('QRcode_' + str(index) + '.png') detector = cv2.QRCodeDetector() data, bbox, straight_qrcode = detector.detectAndDecode(img) if bbox is not None: print("Reading QR Code\n---------------") print("data:", data) res = json.loads(data) parent_key = str(*res) children_key = (*res[parent_key], ) print(children_key) print("{0}: {1}".format(children_key[0], res[parent_key][children_key[0]])) print("{0}: {1}".format(children_key[1], res[parent_key][children_key[1]])) n_lines = len(bbox) for i in range(n_lines): point1 = tuple(bbox[i][0]) point2 = tuple(bbox[(i + 1) % n_lines][0]) cv2.line(img, point1, point2, color=(255, 0, 0), thickness=5) # display the result cv2.imshow('image', img) cv2.waitKey(2000) cv2.destroyAllWindows()
def __init__(self): # make capture object self._cap = cv2.VideoCapture(0) # make detector object self._detector = cv2.QRCodeDetector()
def detect_qr_codes(filename): def getY(index): return points[index][0][1] img = cv2.imread(filename) Img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) img = cv2.bitwise_not(img) qrDecoder = cv2.QRCodeDetector() retval, decoded_info, points, straight_qrcode = qrDecoder.detectAndDecodeMulti(np.hstack([img, img])) quad_filtered = [] decoded_info_filtered_sorted = [] for i in range(len(points)): if points[i][0][0] < img.shape[1]: quad_filtered.append(i) quad_filtered_sorted = sorted(quad_filtered, key=getY) for i in quad_filtered_sorted: decoded_info_filtered_sorted.append(decoded_info[i]) return decoded_info_filtered_sorted
def qrcode(): print("\n ------------------------------ ") cap = cv2.VideoCapture('video.avi') qrCodeDetector = cv2.QRCodeDetector() dtext = "" while (True): # Capture frame-by-frame _, frame = cap.read() if frame is None: break decodedText, points, _ = qrCodeDetector.detectAndDecode(frame) if points is not None: nrOfPoints = len(points) for i in range(nrOfPoints): nextPointIndex = (i + 1) % nrOfPoints cv2.line(frame, tuple(points[i][0]), tuple(points[nextPointIndex][0]), (255, 0, 0), 5) if decodedText: dtext = decodedText if dtext != "": print(dtext) print("\n ------------------------------ ") return dtext else: print("NO QRCODE!!!!!") print("\n ------------------------------ ") return '0'
def scan(image): qrDecoder = cv2.QRCodeDetector() data, bbox, newImage = qrDecoder.detectAndDecode(image) if len(data) > 0: return data else: print("No QR Code detected")
def get_qr_code_coords(img): """ finds a qr code inside of an image :param img: an image with a visible temp sticker :return: the lower left corner of the qr code, the skewed width & height """ # exploit the qr code to get pos data qr = cv2.QRCodeDetector() img_qr = qr.detect(img) # list for return vals coords = [] # draw little circles on the qr code if not img_qr[1] is None: for coord in img_qr[1]: cv2.circle(img, (coord[0][0], coord[0][1]), 5, (0, 255, 0), -1) coords.append((coord[0][0], coord[0][1])) # decrease the img size, in order to display it on 1920x1080 frame_small = cv2.resize(img, (960, 540)) cv2.imshow('get qr code coordinates', frame_small) # extract the qr code position and skewed height & width qr_lower_left_point = coords[0] qr_height = coords[2][0] - coords[0][0] qr_width = coords[2][1] - coords[0][1] return qr_lower_left_point, qr_height, qr_width
def detect_qr_code(source_path, output_path): try: # read source image inputImage = cv2.imread(source_path) # Create a qrCodeDetector Object qrDecoder = cv2.QRCodeDetector() # Detect and decode the qrcode data,bbox,rectifiedImage = qrDecoder.detectAndDecode(inputImage) if len(data)>0: message = "Decoded Data : {}".format(data) print(message) decode_data = data found = 1 im = display(inputImage,bbox) cv2.imwrite(output_path,im) else: message = "QR Code not detected" print(message) found = 0 decode_data = message except Exception as e: message = "Internal Error: {}".format(e) print(message) found = 0 decode_data = message return (found, decode_data)
def comprobarRutaQR(ruta): #Cualquier cosa que este antes de un punto y termine en png mayusculas o minusculas patron_rutaQR = r'^.+\.[Pp][Nn][Gg]$' er_rutaQR = re.compile(patron_rutaQR) patron_codigoPatrimonial = r'^(\d{2} *[\.\_] *)?ED\_?\d{3} *[\.\_] *B\d{1} *[\.\_] *\-?(\d{1,2}|(EN)|(CU)) *[\.\_] *\d{3} *[\.]? *[A-Za-z0-9]?$' er_codigoPatrimonial = re.compile(patron_codigoPatrimonial) resul = er_rutaQR.fullmatch(ruta) if resul: imagen = cv2.imread(ruta) if imagen is None: print('La imagen no existe.') return False else: detectorQR = cv2.QRCodeDetector() texto, puntos, _ = detectorQR.detectAndDecode(imagen) resul_codigo = er_codigoPatrimonial.fullmatch(texto) if resul_codigo: cod = resul_codigo.group(0) if validaLocacion(cod): return cod return False else: campus = encuentraCampus(locacion) if campus: resul_codigo = er_codigoPatrimonial.fullmatch(campus+texto) if resul_codigo: return True return False else: print('Ruta QR no válida.') return False return False
def mask_qr_only(self, img): detector = cv2.QRCodeDetector() retval, points = detector.detectMulti(img) mask = np.zeros(img.shape, np.uint8) cv2.fillPoly(mask, points.astype(int), 1) img = 255 * (mask == 0) + np.multiply(mask, img) return img
def __init__(self, input_predict=(299, 299, 3), template='template_v5.png'): self.img_rows = 256 self.img_cols = 256 self.channels = 3 self.gf = 16 self.input_predict = input_predict self.img_shape = (self.img_rows, self.img_cols, self.channels) self.input_shape = (self.img_rows, self.img_cols, self.channels) self.predict_input_shape = (64, 64, 3) self.model = load_model('corner.h5') self.emodel = load_model('demo2.h5') self.label = { 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '-1', 0: '0', } self.row_per_page = 7 self.numfeature = 50000 self.detector = cv2.QRCodeDetector() self.template_pil = Image.open('template_v6.png').convert('RGB') self.warp = []
def x_scan(img_path): inputImage = cv2.imread(img_path) def display(im, bbox): n = len(bbox) for j in range(n): cv2.line(im, tuple(bbox[j][0]), tuple(bbox[(j + 1) % n][0]), (255, 0, 0), 3) # Display results cv2.imshow("Results", im) qrDecoder = cv2.QRCodeDetector() # Detect and decode the qrcode data, bbox, rectifiedImage = qrDecoder.detectAndDecode(inputImage) if len(data) > 0: print("Decoded Data : {}".format(data)) display(inputImage, bbox) rectifiedImage = np.uint8(rectifiedImage) cv2.imshow("Rectified QRCode", rectifiedImage) else: print("QR Code not detected") cv2.imshow("Results", inputImage) cv2.waitKey(0) cv2.destroyAllWindows()
def sayori(): # Open the audio file data, rate = sf.read(f"{input_folder}/sayori.chr") # Create the spectrogram of the audio file f, t, Sxx = signal.spectrogram(data, rate, window=signal.get_window( "hann", 2**12), noverlap=2**12 - 2**10) # Plot it in a figure plt.figure(figsize=(6, 6)) plt.pcolormesh(t, f, Sxx, cmap="Greys", shading="gouraud") # Take only the frequencies between 9200 and 23000 plt.ylim(9200, 23000) plt.yscale("log") plt.axis("off") # Save it plt.savefig(f"{output_folder}/sayori.png", bbox_inches="tight") # Post processing img = cv2.imread(f"{output_folder}/sayori.png", 0) # Fill the holes kernel = np.ones((10, 10), np.uint8) img = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel) # Thresholding retval, img = cv2.threshold(img, 127, 255, type=cv2.THRESH_OTSU) # Write back the image cv2.imwrite(f"{output_folder}/sayori.png", img) # Read the qr code detector = cv2.QRCodeDetector() data, bbox, straight_qrcode = detector.detectAndDecode(img) # Save the data into a file open(f"{output_folder}/sayori.txt", "w+").write(data)
def read_qr(): img = cv2.imread('raw', 1) detector = cv2.QRCodeDetector() data, bbox, _ = detector.detectAndDecode(img) if data: print("QR Code detected-->") return data
def process(fn): ''' process ''' image = cv2.imread(fn) qrCodeDetector = cv2.QRCodeDetector() decodedText, _, _ = qrCodeDetector.detectAndDecode(image) if decodedText: print(decodedText)
def dec_str(self, imgarr): qrcoder = cv.QRCodeDetector() codeinfo, points, straight_qrcode = qrcoder.detectAndDecode(imgarr) if codeinfo == '': imgarr = cv.bitwise_not(imgarr) codeinfo, points, straight_qrcode = qrcoder.detectAndDecode(imgarr) return codeinfo
def scan(self): # Capture video from web cam video_capture = cv2.VideoCapture(0) qrCodeDetector = cv2.QRCodeDetector() start_time = time.perf_counter() while True: ret, frame = video_capture.read() # Text is decoded text and points is location of detected qr code text, points, optional = qrCodeDetector.detectAndDecode(frame) # if points is not None: # print(text) cv2.imshow('Scan QR code', frame) stop_time = time.perf_counter() - start_time if cv2.waitKey(1) and stop_time > 5: if text or stop_time > 10: break video_capture.release() cv2.destroyAllWindows() received_data = text.split(" ") for data in received_data: if (len(data) == 16): return data[0:6]
def detectQRCode(img): #cv2.imshow('window',cv2.resize(img,(960,540))) #cv2.waitKey(3) detector = cv2.QRCodeDetector() out, data,_ = detector.detectAndDecode(img) print(out) return out
def findSimilarImages(self): self.allResults = [] qrCodeDetector = cv2.QRCodeDetector() similarFile = open(self.similarImageFile, "w") uniqueFile = open(self.uniqueImageFile, "w") print("Finding similar images and decoding QR codes if any.... ") for (i, imagePath) in enumerate(self.imagePaths): # load the image image = cv2.imread(imagePath) arr = [] # convert image to hash queryHash = dhash(image) queryHash = convert_hash(queryHash) results = self.treePickle.get_all_in_range(queryHash, 21) for (count, (d, h)) in enumerate(results): resultPaths = self.hashPickle.get(h, "") arr.append(resultPaths[0]) if len(arr) > 1: similarFile.write(", ".join(arr) + os.linesep) elif len(arr) == 1: uniqueFile.write(arr[0] + os.linesep) similarFile.close() uniqueFile.close()
def test_tools(): """ basic test whether opencv is able to read the output provided by segno. The tempfile is needed because opencv can not read from a file-like object but needs a path to the image-file. """ ssid = 'xenon' password = '******' security = 'WPA' kind = 'png' # create qr-code and store it in a persistent temporary file stream = tempfile.NamedTemporaryFile(mode='wb', delete=False, suffix=f'.{kind}') fname = stream.name qr_code = segno.helpers.make_wifi(ssid=ssid, password=password, security=security, hidden=False) qr_code.save(out=stream, kind=kind, scale=4) stream.close() assert os.path.exists(fname) is True # test qr-code reading expected_result = f'WIFI:T:{security};S:{ssid};P:{password};;' img = cv2.imread(fname) detector = cv2.QRCodeDetector() result, _, _ = detector.detectAndDecode(img) assert result == expected_result # remove the tempfile os.unlink(fname) assert os.path.exists(fname) is False
def __init__(self, threshold, shrink, crop): """Initializes all attributes of the object""" self.threshold = threshold if self.threshold is not None and self.threshold > 255: logging.warning("Threshold above 255, setting to 255") self.threshold = 255 elif self.threshold is not None and self.threshold < 0: logging.warning("Threshold below 0, setting to 0") self.threshold = 0 self.shrink = shrink self._qr_instance = cv2.QRCodeDetector() if crop is not None: if crop[0][0] > 1: crop[0][0] = 1 if crop[0][0] < 0: crop[0][0] = 0 if crop[0][1] > 1: crop[0][1] = 1 if crop[0][1] < 0: crop[0][1] = 0 if crop[1][0] > 1: crop[1][0] = 1 if crop[1][0] < 0: crop[1][0] = 0 if crop[1][1] > 1: crop[1][1] = 1 if crop[1][1] < 0: crop[1][1] = 0 self.crop = crop
def main(): # get current dir current_dir = os.getcwd() # set target dir target_dir = current_dir + "img/ezy.png" # read img img = cv2.imread(target_dir) # init detector detector = cv2.QRCodeDetector() # detect and decode data, bbox, straight_qrcode = detector.detectAndDecode(img) # if there is qrcode if bbox is not None: print(F"QRCode data:\n{data}") # display the image with line # length of bounding box n_lines = len(bbox) for i in range(n_lines): # draw line point1 = tuple(bbox[i][0]) point2 = tuple(bbox[(i + 1) % n_lines][0]) cv2.line(img, point1, point2, color=(255, 0, 0), thickness=2) # display result cv2.imshow("img", img) cv2.waitKey(0) cv2.destroyAllWindows()
def post_new(request): context = {} context['form'] = PostForm() if request.method == "POST": form = PostForm(request.POST, request.FILES) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.qt = form.cleaned_data['qr'] post.created_date = timezone.now() post.save() print(post.qr.path, pathlib.Path(__file__).parent.absolute()) qwee = post.qr.path imagess = cv2.imread(qwee) detector = cv2.QRCodeDetector() data, bbox, _ = detector.detectAndDecode(imagess) if bbox is not None: text_qr = data else: text_qr = 'не смог прочитать qr-код с изображения' post.textqr = text_qr post.save() return redirect('/') else: form = PostForm() form.author = request.user return render(request, 'add.html', context)
def __init__(self): # Bridge to convert ROS message to openCV self.bridge = CvBridge() # QR detector self.qrDecoder = cv2.QRCodeDetector() # Init the depth array self.l_zArray = np.ones((480, 640)) self.r_zArray = np.ones((480, 640)) # Subscriber to the camera image self.l_image_sub = rospy.Subscriber("/l_forearm_cam/image_color", Image, self.l_callBackQR) self.r_image_sub = rospy.Subscriber("/r_forearm_cam/image_color", Image, self.r_callBackQR) # Subscriber to the camera pointcloud self.pc_sub = rospy.Subscriber("/xtion/depth_registered/points", PointCloud2, self.callbackPC) # Publisher of the visual features coordinates self.l_vf_pub = rospy.Publisher("l_visual_features", visualFeatures, queue_size=1) self.r_vf_pub = rospy.Publisher("r_visual_features", visualFeatures, queue_size=1)
def main(): cap = cv2.VideoCapture(0) detector = cv2.QRCodeDetector() while True: _, img = cap.read() data, bbox, _ = detector.detectAndDecode(img) if (bbox is not None): for i in range(len(bbox)): cv2.line(img, tuple(bbox[i][0]), tuple(bbox[(i + 1) % len(bbox)][0]), color=(255, 0, 255), thickness=2) cv2.putText(img, data, (int(bbox[0][0][0]), int(bbox[0][0][1]) - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2) if data: #print("It says: ", data) cap.release() cv2.destroyAllWindows() return (data) cv2.imshow("Item Scanner", img)
def read_qrcode_live(): import cv2 # initalize the cam cap = cv2.VideoCapture(0) # initialize the cv2 QRCode detector detector = cv2.QRCodeDetector() while True: _, img = cap.read() # detect and decode data, bbox, _ = detector.detectAndDecode(img) # check if there is a QRCode in the image if bbox is not None: # display the image with lines for i in range(len(bbox)): # draw all lines cv2.line(img, tuple(bbox[i][0]), tuple(bbox[(i+1) % len(bbox)][0]), color=(255, 0, 0), thickness=2) if data: print("[+] QR Code detected, data:", data) # display the result cv2.imshow("img", img) if cv2.waitKey(1) == ord("q"): break cap.release() cv2.destroyAllWindows()
def find_qrcode(self): symbols = [pyzbar.ZBarSymbol.QRCODE] decoded_objects = pyzbar.decode(self.image) qr_code_detector_cv2 = cv2.QRCodeDetector() try: decoded_text_cv2, points, _ = qr_code_detector_cv2.detectAndDecode( self.image) except all: decoded_text_cv2 = "" pass for obj in decoded_objects: (x, y, w, h) = obj.rect shift = 5 roi = self.image[y - shift:y + h + shift, x - shift:x + w + shift] buff = io.BytesIO() roi_img = Image.fromarray(roi) roi_img.thumbnail([320, 240], Image.ANTIALIAS) try: roi_img.save(buff, format='PNG') except AttributeError: print("Erro no arquivo: " + self.pdf_path) raise AttributeError self.qr_code_image64 = b64encode(buff.getvalue()) if decoded_objects: self.decoded_text = decoded_objects[0].data.decode("utf-8") return self.decoded_text elif len(decoded_text_cv2) != 0: self.decoded_text = decoded_text_cv2 return self.decoded_text else: return None