def process_tube(tube_dict): global badcount tube_img = tube_dict['image'] if SHOW_IMAGES: cv2.imshow('tube', tube_img) if not tube_img.shape or tube_img.shape[0] < 50 or tube_img.shape[1] < 50: del tube_dict['image'] tube_dict['data'] = None return tube_dict #if there aren't many contours this is probably an empty well, so don't waste time #trying to process it tube_thr = cv2.adaptiveThreshold(tube_img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\ cv2.THRESH_BINARY,301,0) #print('done with adaptive threshold') tube_erode = cv2.erode(tube_thr, tube_erosion_kernel, iterations=1) #print('eroded tube') contours, _ = cv2.findContours(tube_erode, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) if len(contours) < MIN_CONTOURS_IN_MATRIX: del tube_dict['image'] tube_dict['data'] = None return tube_dict data = process_matrix(tube_img, HARRIS_BLOCK_SIZE, HARRIS_THRESH_FACTOR) if not data: #if this failed, just run on uncropped tube data = decode(tube_img) if not data: #try again, but adaptive threshold rack_blur = cv2.GaussianBlur(tube_img, (5, 5), 0) tube_thr = cv2.adaptiveThreshold(rack_blur,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\ cv2.THRESH_BINARY_INV,301,\ FAILSAFE_ADAPTIVE_THRESH_FACTOR) data = decode(tube_thr) if not data: #try again, but threshold tube _, tube_thr = cv2.threshold( tube_img, FAILSAFE_THRESH_FACTOR * tube_img.max(), 255, cv2.THRESH_BINARY) data = decode(tube_thr) #finally, if it really couldn't find it if not data: badcount += 1 cv2.imwrite(f'images/badkek{badcount}.jpg', tube_img) #don't need image anymore, but do want result of decode del tube_dict['image'] tube_dict['data'] = int(data[0].data) if data else None return tube_dict
def readDMX(cls): offset = [96,69] # Create a new plot figure = pyplot.figure() axes = mplot3d.Axes3D(figure, proj_type = 'ortho') # Load the STL files and add the vectors to the plot extractedCode = mesh.Mesh.from_file('../stl/extractedCode.stl', calculate_normals = False) extractedCode.rotate([0,0,1],math.radians(-offset[1])) extractedCode.rotate([1,0,0],math.radians(-offset[0])) axes.add_collection3d(mplot3d.art3d.Poly3DCollection(extractedCode.vectors, facecolors='black', edgecolors='black')) # Auto scale to the mesh size scale = extractedCode.points.flatten(-1) axes.auto_scale_xyz(scale, scale, scale) # axes.autoscale() axes.view_init(elev=90, azim=0) # Show the plot to the screen # pyplot.show(figure) figure.savefig('../images/scannedSTL.png') result = str(decode(cv2.imread('../images/scannedSTL.png'))[0][0]) result = re.findall("\d{2}",result) cls.mod = int(result[0]) print(cls.mod) cls.multi = int(result[1]) print(cls.multi)
def scanImage(file_path): with open(file_path, 'rb') as image_file: image = Image.open(image_file) image.load() # Scan the image for barcodes # Returns a "Fail" string or a string number if successful try: codes = decode(image) if str(codes) == "[]": # Fail State is [] return "Fail" else: # Success State is [Decoded(data=b'1', rect=Rect(left=105, top=92, width=-62, height=-62))] success_state = str(codes) print(success_state) _, usr_id, _ = success_state.split("\'") print(usr_id) return usr_id # Only gets called if the value is an string number except AssertionError: return "The File is not an image"
def process_frame(self, frame): """ This method does all the frame processing work """ # Convert to gray frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Invert colors (if needed) if self.invert is True: frame = cv2.bitwise_not(frame) # Figure out dimensions of the frame height, width = frame.shape[:2] # Analyze the frame results = [] results += pyzbar.decode((frame.tobytes(), width, height)) results += pylibdmtx.decode((frame.tobytes(), width, height), timeout=100) if len(results): # logging.debug(f'results: {results}') for result in results: # Save result of the barcode capture self.save_capture(result.data) return frame
def CodeReader(imname): print('test on:',imname) image = cv2.imread(imname) barcodestemp = decode(image) if len(barcodestemp)== 0: # find the barcodes in the image and decode each of the barcodes barcodes = pyzbar.decode(image) model = 'QRCODE' else: barcodes = barcodestemp model = 'DATAMATRIX' for barcode in barcodes: (x, y, w, h) = barcode.rect cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 2) info = barcode.data.decode(encoding="GBK", errors="strict") text = "[Type]: {} \n[Info]: {} ".format(model,info)#UTF-8 不能编码部分中文字符,会提示超出utf-8范围,所以用GBK cv2.putText(image, info, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2) print(text) print('\n') cv2.imshow('Barcode', image) cv2.waitKey(0)
def decode(imgcv2): results = [] try: st = datetime.datetime.now() img = Image.fromarray(imgcv2) if img.mode != 'RGB': img = img.convert('RGB') results = pylibdmtx.decode( img, timeout=80, max_count=1, corrections=3) end = datetime.datetime.now() if len(results) > 0: # print code, end - st time = end - st print "time:", str(time)[6:] except Exception as e: print("---------------------") print("Exception args:", e.args) import traceback traceback.print_exc() pass return results
def get_barcodes(self): images = pdf2image.convert_from_path(self.j_doc["source"]["document"], dpi=self.dpi) area = self.j_doc["source"]["barcode"]["area"] outdir = self._getOutputDirectory(self.j_doc) barcodeimages = [] i = 0 for image in images: i = i + 1 text = decode(image.crop(self._getBarcodeArea(area, image.size))) file_path = outdir + self._getFilePrefix() + str(i) + ".png" if len(text) == 1: barcode = (text[0].data).decode("utf-8") else: barcode = None barcodeimages.append({"file": file_path, "barcode": barcode}) if len(outdir) != 0: image.save(file_path) return {"pages": barcodeimages}
def find_code(src): results = [] resultnames = [ "perspcorrect", "perspthresh", "thresh", "eroded", "dilated", "rotated1", "rotated2", "original" ] # orig, rotated, sharp ##### CORRECT ROTATION ##### im = cv2.imread(src) im = cv2.flip(im, 1) imp = fix_perspective(im) grayp = cv2.cvtColor(imp, cv2.COLOR_BGR2GRAY) gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) __, tho = cv2.threshold(grayp, 100, 255, 0) __, th = cv2.threshold(gray, 100, 255, 0) ker = np.ones((3, 3)) er = cv2.erode(th, ker, iterations=3) contours = cv2.findContours(er, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[-2] contour_sorted = sorted(contours, key=cv2.contourArea) rect = cv2.minAreaRect(contour_sorted[-2]) #print(rect) angle = rect[2] rot = imutils.rotate(im, angle) rot2 = imutils.rotate(im, angle * -1) #### THRESHOLD #### gray = cv2.cvtColor(rot, cv2.COLOR_BGR2GRAY) __, th1 = cv2.threshold(gray, 100, 255, 0) #### ERODE #### ker = np.ones((3, 3)) er = cv2.erode(th1, ker) ### DILATE #### dil = cv2.dilate(th1, ker) results.append(cv2.resize(imp, (0, 0), fx=.5, fy=.5)) results.append(cv2.resize(tho, (0, 0), fx=.5, fy=.5)) results.append(cv2.resize(th1, (0, 0), fx=.5, fy=.5)) results.append(cv2.resize(er, (0, 0), fx=.5, fy=.5)) results.append(cv2.resize(dil, (0, 0), fx=.5, fy=.5)) results.append(cv2.resize(rot, (0, 0), fx=.5, fy=.5)) results.append(cv2.resize(rot2, (0, 0), fx=.5, fy=.5)) results.append(cv2.resize(im, (0, 0), fx=.5, fy=.5)) for i, value in enumerate(results): code = "none" cv2.imwrite('images/' + resultnames[i] + '.jpg', value) print("testing " + resultnames[i]) dec = pylibdmtx.decode(value) if len(dec) > 0: code = dec[0].data.decode("utf-8") print(resultnames[i], code) return code print(" failed")
async def parse_pdf(file): codes = [] try: file_bytes = await file.read() mat = fitz.Matrix(zoom, zoom) doc = fitz.open("pdf", file_bytes) for i, page in enumerate(doc.pages()): pix = page.getPixmap(matrix=mat, alpha=True) bytes_image = pix.getImageData("png") image = Image.open(BytesIO(bytes_image)) for xy in xys: try: cropped = image.crop(xy) t = decode(cropped.convert('L'))[0].data.decode('utf-8') codes.append(t) except IndexError: pass doc.close() except Exception as e: print(e) return "Error" return {"codes": codes, "n": len(codes)}
def identify_barcodes(self): for i in range(len(self.opencv_images)): print("Identify barcodes") image_height = self.opencv_images[i].shape[0] try: barcodes = pylibdmtx.decode(self.opencv_images[i], timeout=5000) except: logging.debug("pylibdmtx could not be loaded", exc_info=True) return self.barcodes.extend(barcodes) #Add barcode as placehoder for barcode in barcodes: print(barcode) x = barcode.rect.left y = image_height - barcode.rect.top - barcode.rect.height h = barcode.rect.height w = barcode.rect.width barcode_mask = { "page": i + 1, "x": x, "y": y, "height": h, "width": w } self.placeholders.append(barcode_mask) pass
def func_detectData_matrix(self): var_position = [] tmp_font = cv2.FONT_HERSHEY_PLAIN var_decodedObjects = pylibdmtx.decode(self.var_img_thred) self.tmp_img = self.var_img[self.var_y0_2Dcode:self.var_y1_2Dcode, self.var_x0_2Dcode:self.var_x1_2Dcode] self.var_strDataMatrix = "" for obj in var_decodedObjects: if len(str(obj.data)) != 0: self.var_strDataMatrix = obj.data.decode('utf-8') x, y, w, h = obj.rect cv2.rectangle(self.tmp_img, (x, y), (x + w, y + h), (0, 0, 255), 2) cv2.putText(self.tmp_img, self.var_strDataMatrix, (10, 10), tmp_font, 1, (255, 0, 0), 1) var_position.append(self.var_x0_2Dcode + x + 0.5 * w) var_position.append(self.var_y0_2Dcode + y + 0.5 * h) self.var_img[self.var_y0_2Dcode:self.var_y1_2Dcode, self.var_x0_2Dcode:self.var_x1_2Dcode] = self.tmp_img print(self.var_strDataMatrix) if len(self.var_strDataMatrix) == 0: self.var_strDataMatrix = "Khong phat hien" return self.var_strDataMatrix, self.var_img, var_position
def process(self, inframe, outframe): # Get the next camera image (may block until it is captured) as OpenCV BGR: inimg = inframe.getCvBGR() # Start measuring image processing time (NOTE: does not account for input conversion time): self.timer.start() # Create dark-gray (value 80) image for the bottom panel, 40 pixels tall: msgbox = np.zeros((40, inimg.shape[1], 3), dtype = np.uint8) + 80 # Find and decode any DataMatrix symbols: dec = decode(inimg) # Draw the results in the input image (which we will copy to output): y = 13 for d in dec: cv2.rectangle(inimg, (d.rect.left, d.rect.top), (d.rect.left+d.rect.width-1, d.rect.top+d.rect.height-1), (255,0,0), 2) cv2.putText(msgbox, d.data.decode("utf-8"), (3, y), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,255,255)) y = y + 12 # Create our output image as a copy of the input plus our message box: outimg = np.vstack((inimg, msgbox)) # Write a title: cv2.putText(outimg, "JeVois Python DataMatrix", (3, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,255,255)) # Write frames/s info from our timer into the edge map (NOTE: does not account for output conversion time): fps = self.timer.stop() cv2.putText(outimg, fps, (3, inimg.shape[0] - 6), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,255,255)) # Convert our OpenCv output image to video output format and send to host over USB: outframe.sendCv(outimg)
def _assert_encoded_data(self, expected_data, encoded): # Check encoded data image = Image.frombytes('RGB', (encoded.width, encoded.height), encoded.pixels) decoded = decode(image) self.assertEqual(1, len(decoded)) self.assertEqual(expected_data, decoded[0].data)
def decodeQrDataMatrix(self, img): d = decode(img) if len(d) >= 1: data = d[0].data dataDecoded = data.decode('utf-8') return dataDecoded else: return "unknown"
def decode_datamatrix(gray, resizeshape, k1, k2): th, res = cv2.threshold(gray, 0, 255, cv2.THRESH_OTSU) binary = cv2.resize(res, resizeshape, interpolation=cv2.INTER_NEAREST) kernel1 = cv2.getStructuringElement(cv2.MORPH_RECT, k1) kernel2 = cv2.getStructuringElement(cv2.MORPH_RECT, k2) final = cv2.morphologyEx(binary, cv2.MORPH_DILATE, kernel1, iterations=1) decode_str = decode(Image.fromarray(final)) if decode_str == []: finalretry = cv2.morphologyEx(binary, cv2.MORPH_DILATE, kernel2, iterations=1) decode_str_retry = decode(Image.fromarray(finalretry)) if decode_str_retry == []: return None else: return str(decode_str_retry[0][0])[2:-1] else: return str(decode_str[0][0])[2:-1]
def decode(img): height = img.shape[0] width = img.shape[1] code = pylibdmtx.decode(img, **libdmtx_params) code = code[0].data.decode('utf-8') if code else False if code and re.match('(\w\w)?\d{10}', code): return code else: return None
def readDataMatrix(): path, dirs, files = next(os.walk("./matrices")) fileCount = len(files) file = open("./DecodedText.txt", "w") finalString = "" for i in range(0, (fileCount - 2)): decodeString = str( decode(Image.open('./matrices/matrix' + str(i) + '.png'))) decodeString = decodeString.replace('\\n', '\n') finalString += decodeString[16:(16 + splitLength)] # Special case for last matrix decodeString = str( decode(Image.open('./matrices/matrix' + str(fileCount - 2) + '.png'))) decodeString = decodeString.replace('\\n', '\n') finalString += decodeString[16:len(decodeString) - 50] file.write(finalString) file.close()
def decode_thread(pp_more): #work around becuase skimage no longer returns numpy array and pylibdmtx expects that well = array(pp_more['well']) if well.shape[0] > 0 and well.shape[1] > 0: # try shrink res = decode(well, timeout=10, shrink=2, max_count=1) if res and res[0].data.decode().isnumeric(): return {**pp_more['pp'], 'barcode': res[0].data.decode()} # try defaults res = decode(well, timeout=10, max_count=1) if res and res[0].data.decode().isnumeric(): return {**pp_more['pp'], 'barcode': res[0].data.decode()} # try threshold res = decode(well, timeout=10, threshold=100, max_count=1) if res and res[0].data.decode().isnumeric(): return {**pp_more['pp'], 'barcode': res[0].data.decode()} # give it more time # try shrink res = decode(well, timeout=100, shrink=2, max_count=1) if res and res[0].data.decode().isnumeric(): return {**pp_more['pp'], 'barcode': res[0].data.decode()} # try defaults res = decode(well, timeout=100, max_count=1) if res and res[0].data.decode().isnumeric(): return {**pp_more['pp'], 'barcode': res[0].data.decode()} # try threshold res = decode(well, timeout=100, threshold=100, max_count=1) if res and res[0].data.decode().isnumeric(): return {**pp_more['pp'], 'barcode': res[0].data.decode()} return {**pp_more['pp'], 'barcode': "failed"}
def scanner(frame): # try to detect barcode decoded = pyzbar.decode(frame) if decoded != []: # scanned barcode data = str(decoded[0][0])[2:-1] return data # try to detect data matrix decoded = pylibdmtx.decode(frame) if decoded != []: # scanned dtmx data = decoded[0][0].decode('utf-8') return data return "nothing detected"
def decode_panel(panel): px, py = panel.size p = None for size in [100, 200]: print(size) panel_resize = panel.resize((size, int(size * py / px))) res = decode(panel_resize, max_count=1) if res and len(res[0].data.decode()) == 10 and res[0].data.decode( ).isnumeric(): p = res[0].data.decode() return p return p
def read_datamatrix(self): datamatrix = self.raw_img[QR_ROW_MIN:QR_ROW_MAX, QR_COL_MIN:QR_COL_MAX] plt.imshow(datamatrix) plt.show() try: content = pylibdmtx.decode(datamatrix, timeout=QR_TIMEOUT)[0][0] print 'qr content', content self.test_id = content[:5] self.paper_id = content[5:8] except Exception as e: print '[WARNING] Cannot decode datamatrix:', e self.test_id = None self.paper_id = None
def detect(frame): ##using pylibdmtx ans = decode(frame) if len(ans) != 0: print "Decode 2D Barcode", ans return True ##using zbar if len(ans) == 0: ans = scanner.scan(frame) if len(ans) == 0: return False print "Decode barcode", ans return True return False
def __get_datamatrix_data(img): info = [] for i in range(1, 5): barcode_x_scale = 1 / i barcode_image = cv2.resize(img, (0, 0), fx=barcode_x_scale, fy=1) info = pylibdmtx.decode(barcode_image) if len(info) == 0: continue else: break for barcode in info: return barcode.data.decode("UTF-8")
def lambda_handler(event, context): image_filename = event['filename'] osr = openslide.open_slide(os.path.join(FS_PATH, image_filename)) # get image id from tiff tags; create output folder image_id = osr.properties.get(PROPERTY_NAME_APERIO_IMAGEID) # Extract label and thumbnail images label = osr.associated_images.get(u'label').convert('RGB') # decode slide id from 2D Data Matrix barcode in label image label_data = pylibdmtx.decode(label) if len(label_data) != 1: logger.error('Bad label data') return slide_id = label_data[0].data.decode('ascii') # get metadata width, height = osr.dimensions scan_date = osr.properties.get(PROPERTY_NAME_APERIO_DATE) scan_time = osr.properties.get(PROPERTY_NAME_APERIO_TIME) scan_timezone = osr.properties.get(PROPERTY_NAME_APERIO_TZ) scandate = datetime.strptime(f'{scan_date} {scan_time} {scan_timezone}', '%m/%d/%y %H:%M:%S %Z%z') metadata = { 'Filename': image_filename.strip(), 'ImageID': image_id.strip(), 'SlideID': slide_id.strip(), 'width': width, 'height': height, 'ScanDate': scandate.isoformat(), 'MPP': osr.properties.get(PROPERTY_NAME_APERIO_MPP), 'AppMag': osr.properties.get(PROPERTY_NAME_APERIO_APPMAG), 'lastModified': datetime.now(timezone.utc).isoformat(timespec='milliseconds'), } # TODO: put metadata logger.info(f'Uploaded metadata for {image_filename}')
def get_decoded_value(output_image_file, code_type): try: info = [] #bar code if 'bar' in code_type.lower(): info = pyzbar.decode(Image.open(output_image_file)) #Data Matrix code if 'matrix' in code_type.lower(): info = pylibdmtx.decode(Image.open(output_image_file)) #converting bytes to string decoded_value = (info[0].data).decode("utf-8") return (decoded_value) except: return ""
def getScanResult(): QR_Image = getScreenImage() QRCode = zbar.decode(QR_Image) DataMatrix = decode(QR_Image) # print(dir(QRCode), QRCode._len_, QRCode.sizeof(), QRCode.index) print(QRCode, type(QRCode), QR_Image.data, type(QR_Image)) # 判断数组是否为空,为空则表示未扫描到QRCode二维码 if QRCode: QR_DATA = (QRCode[0].data).decode('utf-8') elif DataMatrix: QR_DATA = (DataMatrix[0].data).decode('utf-8') else: QR_DATA = "未识别!!!" # 弹框提示结果 easygui.msgbox(QR_DATA) # 将结果自动拷贝到剪切板 pyperclip.copy(QR_DATA)
def ReaderWorker(frame_shared, a_arr, b_arr, camera_width, camera_height): last_a_update = 0 last_b_update = 0 a_center_y = -1 b_center_y = -1 a_top = -1 b_top = -1 while True: frame = np.array(frame_shared[:], dtype=np.uint8).reshape(camera_height, camera_width) # 5秒間バーコードを検出できなかったら初期化する if last_a_update + 5 < time.time() or last_b_update + 5 < time.time(): a_center = -1 b_center = -1 ret, preprocessed = cv2.threshold(frame, 170, 255, cv2.THRESH_BINARY) codedata = decode(preprocessed, timeout=300, max_count=2, shape=DmtxSymbolSize.DmtxSymbolSquareAuto) for d in codedata: if d.data == b'A': a_center = int(d.rect.left + d.rect.width / 2) a_center_y = camera_height - int(d.rect.top + d.rect.height / 2) a_top = camera_height - d.rect.top - d.rect.height last_a_update = time.time() if d.data == b'B' or d.data == b'C' or d.data == b'D': b_center = int(d.rect.left + d.rect.width / 2) b_center_y = camera_height - int(d.rect.top + d.rect.height / 2) b_top = camera_height - d.rect.top - d.rect.height last_b_update = time.time() a_arr[0] = a_center a_arr[1] = a_center_y a_arr[2] = a_top b_arr[0] = b_center b_arr[1] = b_center_y b_arr[2] = b_top
def extract_pdf_datamatrix(self): uuid_set = str(uuid.uuid4().fields[-1])[:5] image_folder = os.path.dirname(self.path) image_file = os.path.join(image_folder, 'image%s.png' % uuid_set) pages = Image(filename=self.path) page = pages.sequence[0] # Check first page with Image(page) as img: img.format = 'png' img.background_color = Color('white') img.alpha_channel = 'remove' img.save(filename=image_file) datamatrix = pylibdmtx.decode(Img.open(image_file)) os.remove(image_file) return datamatrix and datamatrix[0].data.decode() or False
def Decoding(self): # # #h, w = img.shape[:2] #result = decode((img[:, :, :1].tobytes(), w, h), timeout = self.timeout) result = decode(self.img, timeout=self.timeout, max_count=self.maxcount) if result: # Success Decoding decode_object = result[0] print("MCR Result : {0}".format(result)) msg = ("Decoded.data = {0}".format(decode_object.data)) return msg else: # Fail Decoding msg = ("Decoding Fail !") return msg
def read_datamatrix(self): """ Reads the content datamatrix on the paper. """ datamatrix_region = self.thr_img[ DATAMATRIX_REGION[0]:DATAMATRIX_REGION[1], DATAMATRIX_REGION[2]:DATAMATRIX_REGION[3]] try: content = decode(datamatrix_region, timeout=READ_DATAMATRIX_TIMEOUT)[0][0] self.test_id = content[:DATAMATRIX_SPLIT] self.paper_id = content[DATAMATRIX_SPLIT:] except: self.test_id = '?????' self.paper_id = '???' self.metadata += 'Could not decode datamatrix.\n' if DEBUG: print('Test id: %s\tPaper id: %s' % (self.test_id, self.paper_id))