Example #1
0
def readQR(img):
    # img = filterBlack(img, [0, 0, 0], [180, 255, 110]) # 110
    originImg = img
    for range02 in [[180, 255, 105], [180, 255, 110]]:
        img = filterBlackOriginImg(originImg, [0, 0, 0], range02)
        # H, W, _ = img.shape
        # img = cv2.resize(img, (W * 2, H * 2))
        img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        cv2.imshow("img" + str(np.random.randint(10000)), img)
        cv2.waitKey(10)
        img = Image.fromarray(img)
        w, h = img.size
        version = platform.python_version_tuple()
        if int(version[2]) >= 10:
            zbarImg = zbar.Image(w, h, 'Y800', img.tobytes())
        else:
            zbarImg = zbar.Image(w, h, 'Y800', img.tostring())
        scanner = zbar.ImageScanner()
        barCodeCount = scanner.scan(zbarImg)
        resultCode = -1
        for scanResult in zbarImg:
            resultCode = scanResult.data
            break
        del zbarImg
        if resultCode != -1:
            return resultCode
    return resultCode
Example #2
0
def process_image():
    global zbar_string, crop_string
    global message, zbar_decoded_count, crop_decoded_count
    #przetworzenie obrazu do zdekodowania przez zbar
    rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    i = Image.fromarray(rgb, 'RGB').convert('L')
    width, height = i.size
    raw = i.tostring()
    image = zbar.Image(width, height, 'Y800', raw)
    scanner.scan(image)
    for symbol in image:
        zbar_decoded_count = zbar_decoded_count + 1
        message = symbol.data

    #reczne wycinanie kodu z obrazu
    #przetworzenie obrazu do rozpoznania krawedzi
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    thresh = 200
    im_bw = cv2.threshold(gray, thresh, 255, cv2.THRESH_BINARY)[1]
    contours, hierarchy = cv2.findContours(im_bw, cv2.RETR_TREE,
                                           cv2.CHAIN_APPROX_SIMPLE)
    new = np.zeros((1, 1, 3), np.uint8)
    angle = 0
    if (len(contours) > 0):
        areas = [cv2.contourArea(c) for c in contours]
        max_index = np.argmax(areas)
        cnt = contours[max_index]
        rect = cv2.minAreaRect(cnt)
        x, y, w, h = cv2.boundingRect(cnt)
        new = frame[y:y + h, x:x + w]
        angle = rect[2]

    #jesli wykryto i zapisano kod do nowej tablicy
    #wyswietl wyciety obszar i wyslij go do dekodera
    if np.any(new != 0):
        rgb2 = cv2.cvtColor(show_rotated(new, angle), cv2.COLOR_BGR2RGB)
        i2 = Image.fromarray(rgb2, 'RGB').convert('L')
        width, height = i2.size
        raw2 = i2.tostring()
        image2 = zbar.Image(width, height, 'Y800', raw2)
        scanner.scan(image2)

        for symbol in image2:
            crop_decoded_count = crop_decoded_count + 1

    zbar_string = "zbar: " + str(zbar_decoded_count)
    crop_string = "crop: " + str(crop_decoded_count)
    del (image)
Example #3
0
def image_data_to_state_estimate(raw_bytes, request_id):
    scanner = zbar.ImageScanner()

    img = Image.open(io.BytesIO(raw_bytes))

    # Uncomment for testing
    # img = Image.open('qr_code.png')

    # Save a copy of image
    file = open('downlinked_images/' + str(request_id).zfill(10) + '.jpg',
                'wb')
    file.write(raw_bytes)

    frame = img.convert("RGB")
    gray = cv2.cvtColor(np.array(frame), cv2.COLOR_BGR2GRAY, dstCn=0)
    pil_img = Image.fromarray(gray)
    width, height = pil_img.size
    pil_bytes = pil_img.tobytes()

    # Read QR code
    zImg = zbar.Image(width, height, 'Y800', pil_bytes)
    scanner.scan(zImg)

    if len(zImg.symbols) > 0:
        # do something useful with results
        symbol = list(zImg.symbols)[0]
        print('Decoded symbol with data: %s' % symbol.data)
        print(symbol.type)
        print(symbol.location)

        return get_state_estimate_from_point_locations(symbol.location)

    else:
        print('No QR codes found!')
        return ''
Example #4
0
def qr_readerDEPRECATED(capture, drone):
    while True:
        # To quit this program & land drone press q
        if cv2.waitKey(1) & 0xFF == ord('q'):
            drone.land()
            break

        # Breaks down the video into frames
        ret, frame = capture.read()

        # Displays the current frame
        cv2.imshow('Current', frame)

        # Converts image to grayscale.
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        # Uses PIL to convert the grayscale image into a ndary array that ZBar can understand.
        image = Image.fromarray(gray)

        width, height = image.size
        zbar_image = zbar.Image(width, height, 'Y800', image.tobytes())

        # Scans the zbar image.
        scanner = zbar.ImageScanner()
        scanner.scan(zbar_image)

        # Prints data from image.
        for decoded in zbar_image:
            print("QR: " + decoded.data)
            return decoded.data
Example #5
0
def callback(data):
    # print('received an image')
    # define picture to_down' coefficient of ratio
    scaling_factor = 0.5
    global count, bridge
    count = count + 1
    if count == 1:
        count = 0
        cv_img = bridge.imgmsg_to_cv2(data, "bgr8")
        cv2.imshow("frame", cv_img)
        # qrcode scanner
        scanner = zbar.ImageScanner()
        scanner.parse_config('enable')
        pil = pImage.fromarray(cv_img).convert('L')
        width, height = pil.size
        raw = pil.tobytes()
        image = zbar.Image(width, height, 'Y800', raw)
        scanner.scan(image)
        cmd_puber = rospy.Publisher('sci/qr_cmd', String, queue_size = 10)   
        for symbol in image:
            cmd_data = unicode(symbol.data, 'utf-8')
            cmd_puber.publish(cmd_data)
        cv2.waitKey(10)
    else:
        pass
Example #6
0
 def _next_frame(self):
     while self.qr_frames and self.current_frame >= self.qr_frames[0][1]:
         self.qr_frames.pop(0)
     ret, frame = self.source.read()
     if not ret:
         return None
     if not self.qr_frames or self.current_frame < self.qr_frames[0][0]:
         if self.qr_frames:
             self.range_first = True
             self.source.set(cv2.cv.CV_CAP_PROP_POS_FRAMES,
                             self.qr_frames[0][0])
             self.current_frame = self.qr_frames[0][0]
         return frame
     gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
     h, w = gray.shape
     scanner = zbar.ImageScanner()
     scanner.parse_config('enable')
     image = zbar.Image(w, h, 'Y800', gray.tostring())
     if scanner.scan(image):
         for symbol in image:
             if self.last_symbol != symbol.data:
                 self.last_symbol = symbol.data
                 self.check_symbol(self.last_symbol)
     self.current_frame += 1
     return frame
Example #7
0
def read_barcode(image_name):
    # create a reader
    scanner = zbar.ImageScanner()

    # configure the reader
    scanner.parse_config('enable')

    # obtain image data
    pil = Image.open(image_name).convert('L')
    width, height = pil.size
    raw = pil.tobytes()

    # wrap image data
    image = zbar.Image(width, height, 'Y800', raw)

    # scan the image for barcodes
    scanner.scan(image)

    # extract results
    ret_val = ''
    for symbol in image:
        # do something useful with results
        print(symbol.data)
        ret_val = symbol.data
        break

    # clean up
    del (image)

    # return barcode string
    return ret_val
Example #8
0
def scan_qr(BUZZ, RED):
    tmp = 0
    for frame in camera.capture_continuous(raw, format='bgr', use_video_port=True):
        img = frame.array
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        image = Image.fromarray(gray)
        width, height = image.size
        z_img = zbar.Image(width, height, 'Y800', image.tobytes())
        scanner = zbar.ImageScanner()
        res = scanner.scan(z_img)
        print res
        if res > 0:
            for decoded in z_img:
                raw.truncate(0)
                return decoded.data
            break
        elif res == -1:
            led_error(RED)
            buzz_error(BUZZ)
            raw.truncate(0)
            continue
        else:
            if tmp == 0:
                start = time.time()
                tmp += 1
            else:
                if time.time() - start > 5:
                    raw.truncate(0)
                    break
            raw.truncate(0)
def main():
    capture = cv2.VideoCapture('D:/Dropbox/python/drone_code_chn/teszt.mp4')
    ## capture = cv2.VideoCapture("D:/Dropbox/python/drone_code_chn/test.mp4")
    index = 0
    while True:
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

        # Framelteti a videot
        ret, frame = capture.read()

        # Megjelenit egy framet
        cv2.imshow('Current', frame)

        # openCV gray konvertalas
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        # Gray a ZBAR-hoz
        image = Image.fromarray(gray)
        width, height = image.size
        zbar_image = zbar.Image(width, height, 'Y800', image.tobytes())

        # ZBAR image vizsgalat
        scanner = zbar.ImageScanner()
        scanner.scan(zbar_image)

        # Adatkiiratas
        for decoded in zbar_image:
            index += 1
            print(str(index) + ". " + decoded.data)
Example #10
0
def str2qr_terminal(data, is_send):
    """
    @brief      convert string to qrcode matrix and outprint
    @param      data   The string
    """
    cm = ConfigManager()
    file_dir = cm.getpath('qrcode_path')
    with open(file_dir, 'wb') as f:
        f.write(data)

    if is_send:
        p = multiprocessing.Process(target=send_login_mail, args=(file_dir, ))
        p.start()

    scanner = zbar.ImageScanner()
    scanner.parse_config('enable')
    pil = Image.open(file_dir).convert('L')
    width, height = pil.size
    raw = pil.tobytes()
    image = zbar.Image(width, height, 'Y800', raw)
    scanner.scan(image)
    text = ''
    for symbol in image:
        text += symbol.data
    del image

    echo('二维码表示地址:%s\n' % text)

    qr = qrcode.QRCode()
    qr.border = 1
    qr.add_data(text)
    mat = qr.get_matrix()
    print_qr(mat)
Example #11
0
class image_converter:
    def __init__(self):
        self.image_pub = rospy.Publisher("image_topic_2", Image)

        cv.NamedWindow("Image window", 1)
        self.bridge = CvBridge()
        self.image_sub = rospy.Subscriber("/camera/rgb/image_color", Image,
                                          self.callback)

    def callback(self, data):
        try:
            cv_image = self.bridge.imgmsg_to_cv(data, "rgb8")
        except CvBridgeError, e:
            print e

        (cols, rows) = cv.GetSize(cv_image)

        gris = cv.CreateImage(cv.GetSize(cv_image), cv.IPL_DEPTH_8U, 1)
        cv.CvtColor(cv_image, gris, cv.CV_RGB2GRAY)
        scanner = zbar.ImageScanner()
        scanner.parse_config('enable')

        raw = gris.tostring()

        image = zbar.Image(cols, rows, 'Y800', raw)

        scanner.scan(image)

        for symbol in image:
            print symbol.data

        cv.ShowImage("Image window", cv_image)

        cv.WaitKey(3)
Example #12
0
def getQR(imgargrgb):  #{{{
    """read QR code from image"""
    imgarg = imgargrgb.convert('L')
    # create a reader
    scanner = zbar.ImageScanner()

    # configure the reader
    scanner.parse_config('enable')

    # obtain image data
    width, height = imgarg.size
    raw = imgarg.tostring()

    # wrap image data
    image = zbar.Image(width, height, 'Y800', raw)

    # scan the image for barcodes
    scanner.scan(image)

    # extract results
    for symbol in image:
        # do something useful with results
        print 'decoded', symbol.type, 'symbol', '"%s"' % symbol.data
        return symbol.data

    # clean up
    del (image)
Example #13
0
 def getContentFromQrcode(self, url):
     result = []
     try:
         # 图片地址替换成你的qrcode图片地址
         # create a reader
         scanner = zbar.ImageScanner()
         # configure the reader
         scanner.parse_config('enable')
         # obtain image data
         imgfile = cStringIO.StringIO(urllib.urlopen(url).read())
         pil = Image.open(imgfile).convert('L')
         width, height = pil.size
         raw = pil.tobytes()
         # wrap image data
         image = zbar.Image(width, height, 'Y800', raw)
         # scan the image for barcodes
         scanner.scan(image)
         # extract results
         for symbol in image:
             # do something useful with results
             print 'decoded', symbol.type, 'symbol', '"%s"' % symbol.data
             result.append(symbol.data)
         # clean up
         del (image)
     except Exception as e:
         logging.error('%s  get Qrcode failed!' % url)
     return result
Example #14
0
	def from_pil(scanner,pil):
		ret = []
		try:
			#pil = pil.convert('L')
			width, height = pil.size
			raw = pil.tobytes()

			# wrap image data
			image = zbar.Image(width, height, 'Y800', raw)

			# scan the image for barcodes
			scanner.scan(image)

			# extract results
			for symbol in image:
			# do something useful with results
				ret.append((symbol.type, symbol.data))

		# clean up
			del image
			del raw
		except:
			pass

		return ret
Example #15
0
def main():
    '''
    Capture webcam video utilizing OpenCV. The video is then broken down into frames which
    are constantly displayed. The frame is then converted to grayscale for better contrast. Afterwards, the image
    is transformed into a numpy array using PIL. This is needed to create zbar image. This zbar image is then scanned
    utilizing zbar's image scanner and will then print the decodeed message of any QR or bar code. To quit the program,
    press "q".
    :return:
    '''
    logging.info('starting')
    # Begin capturing video. You can modify what video source to use with VideoCapture's argument. It's currently set
    # to be your webcam.
    capture = cv2.VideoCapture(0)
    previous_control = 'play'
    while True:
        # To quit this program press q.
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

        # Breaks down the video into frames
        _, frame = capture.read()

        # Displays the current frame
        #if logging.getLogger().isEnabledFor(logging.VERBOSE):
        #    cv2.imshow('Current', frame)

        # Converts image to grayscale.
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        # Uses PIL to convert the grayscale image into a ndary array that ZBar can understand.
        image = Image.fromarray(gray)
        width, height = image.size
        zbar_image = zbar.Image(width, height, 'Y800', image.tobytes())

        # Scans the zbar image.
        scanner = zbar.ImageScanner()
        scanner.scan(zbar_image)

        # Prints data from image.
        for decoded in zbar_image:
            logging.debug(decoded.data)
            # TODO sleep that thing
            control = decoded.data
            if control == previous_control:
                logging.debug("same control")
                continue
            else:
                logging.info('new control: %r', control)
                previous_control = control
                if control == "play":
                    play()
                elif control == "pause":
                    pause()
                elif control == "next":
                    next_track()
                elif control == "previous":
                    previous_track()
                elif re.match(r"^spotify:", control):
                    logging.info('Play spotify uri: %r', control)
                    play_backend_uri(control)
Example #16
0
def qrScan(imgs):
    sequence = ['U', 'R', 'F', 'D', 'L', 'B']
    result = []

    # Initialize QR_Code
    scanner = zbar.ImageScanner()
    scanner.parse_config('enable')

    # Load image
    # Convert grayscale
    for seq in sequence:
        src_img = imgs[seq]
        rows, cols = src_img.shape[:2]  
        for i in range(1, 5, 1):
            gray_img = cv2.cvtColor(src_img, cv2.COLOR_BGR2GRAY)
            image = zbar.Image(cols, rows, 'Y800', gray_img.tostring())  
            scanResult = scanner.scan(image)
#            print "scanResult[%d]" % (scanResult)
            if (scanResult == 0):
                # Scan failed.
                src_img = rotateCenter(src_img)
            else:
                break

        for symbol in image:  
            result.append(symbol.data)

    return result
Example #17
0
def scanner_procces(frame, set_zbar):
    set_width = 100.0 / 100
    set_height = 90.0 / 100

    coord_x = int(frame.width * (1 - set_width) / 2)
    coord_y = int(frame.height * (1 - set_height) / 2)
    width = int(frame.width * set_width)
    height = int(frame.height * set_height)

    get_sub = cv.GetSubRect(frame,
                            (coord_x + 1, coord_y + 1, width - 1, height - 1))

    cv.Rectangle(frame, (coord_x, coord_y),
                 (coord_x + width, coord_y + height), (255, 0, 0))

    cm_im = cv.CreateImage((get_sub.width, get_sub.height), cv.IPL_DEPTH_8U, 1)
    cv.ConvertImage(get_sub, cm_im)
    image = zbar.Image(cm_im.width, cm_im.height, 'Y800', cm_im.tostring())

    set_zbar.scan(image)
    for symbol in image:
        print '\033[1;32mResult : %s symbol "%s" \033[1;m' % (symbol.type,
                                                              symbol.data)

    cv.ShowImage("webcame", frame)
    #cv.ShowImage("webcame2", get_sub)
    cv.WaitKey(10)
Example #18
0
def tracking():
    while True:
        ret, output = cap.read()
        if not ret:
            continue
        gray = cv2.cvtColor(output, cv2.COLOR_BGR2GRAY, dstCn=0)
        pil = Image.fromarray(gray)
        width, height = pil.size
        raw = pil.tobytes()
        image = zbar.Image(width, height, 'Y800', raw)
        scanner.scan(image)
        # open file to write information about qrcode
        f = open("data.txt", "w")
        #write in the file
        for symbol in image:
            f.write(str(symbol.data) + "\n")
            (x1, y1) = symbol.location[0]
            (x2, y2) = symbol.location[1]
            (x3, y3) = symbol.location[2]
            (x4, y4) = symbol.location[3]
            (X, Y) = ((x1 + x2 + x3 + x4) / 4, (y1 + y2 + y3 + y4) / 4)
            f.write(str(X) + " " + str(Y) + "\n")
            n = len(symbol.location)
            for j in range(0, n):
                cv2.line(output, symbol.location[j],
                         symbol.location[(j + 1) % n], (0, 0, 255), 2)

        cv2.imshow("Tracking", output)

        # Wait for the magic key
        k = cv2.waitKey(1) & 0xff
        if k == 27: break
Example #19
0
def decode(im):

    # Create zbar scanner
    scanner = zbar.ImageScanner()

    # Configure scanner
    scanner.parse_config('enable')

    # Convert image to grayscale
    imGray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)

    # Find height and width
    height, width = imGray.shape

    # Get raw image bytes
    raw = imGray.tobytes()

    # Wrap image data in a zbar image
    decodedObjects = zbar.Image(width, height, 'Y800', raw)

    # Scan the image for barcodes and QRCodes
    scanner.scan(decodedObjects)

    # Print results
    for decodedObject in decodedObjects:
        print('Type : ', decodedObject.type)
        print('Data :', decodedObject.data, '\n')

    # Return decoded object
    return decodedObjects
Example #20
0
def decode_qrcode(path):
    """
    解析二维码信息
    @参数 path: 二维码图片路径
    @return: 二维码信息
    """
    # 创建图片扫描对象
    scanner = zbar.ImageScanner()
    # 设置对象属性
    scanner.parse_config('enable')
    # 打开含有二维码的图片
    img = Image.open(path).convert('L')
    # 获取图片的尺寸
    width, height = img.size
    # 建立zbar图片对象并扫描转换为字节信息
    qrCode = zbar.Image(width, height, 'Y800', img.tobytes())
    scanner.scan(qrCode)
    # 组装解码信息
    data = ''
    for s in qrCode:
        data += s.data
    # 删除图片对象
    del img
    # 输出解码结果
    return data
Example #21
0
 def overview(self):
     tot_frames = int(self.source.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT))
     fps = int(self.source.get(cv2.cv.CV_CAP_PROP_FPS))
     start = None
     ranges = []
     scan = (b + o for b in range(0, tot_frames, 3 * fps) for o in range(3))
     for frame_idx in scan:
         if start and frame_idx - start < 3:
             continue  # 3s segment already in range
         self.source.set(cv2.cv.CV_CAP_PROP_POS_FRAMES, frame_idx)
         ret, frame = self.source.read()
         if not ret:
             break
         gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
         h, w = gray.shape
         scanner = zbar.ImageScanner()
         scanner.parse_config('enable')
         image = zbar.Image(w, h, 'Y800', gray.tostring())
         if scanner.scan(image):
             if start is None:
                 start = frame_idx
         elif start is not None:
             ranges.append((start, frame_idx))
             start = None
         cv2.imshow('frame', gray)
         key = cv2.waitKey(1)
         if key & 0xFF in (27, ord('q')):
             break
     if start is not None:
         ranges.append((start, frame_idx))
     self.qr_frames = [(max(s - 3 * fps, 0), e) for (s, e) in ranges]
     self.total_ranges = len(ranges)
     self.source.set(cv2.cv.CV_CAP_PROP_POS_FRAMES, 0)
Example #22
0
def barcode(image):
    # create a reader
    scanner = zbar.ImageScanner()

    # configure the reader
    scanner.parse_config('enable')

    # obtain image data
    width, height = image.shape
    raw = image.tobytes()

    image = zbar.Image(width, height, 'Y800', raw)

    # scan the image for barcodes
    scanner.scan(image)

    # extract results
    for symbol in image:
        # do something useful with results
        print('format:', symbol.type, '| data:', '"%s"' % symbol.data)
    # clean up
    print(
        '-----------------------------------------------------------------------'
    )
    del (image)
    def _getImage(self):
        """
        Main loop to get and analyze an image.
        """
        # Get the image
        pepperImage = self.vid.getImageRemote(self.videoClient)

        if pepperImage is not None:
            # Convert the image
            # im = Image.fromstring("L", (pepperImage[0], pepperImage[1]), str(bytearray(pepperImage[6])))
            im = Image.frombytes("L", (pepperImage[0], pepperImage[1]),
                                 str(bytearray(pepperImage[6])))
            # Analyze the image
            zImage = zbar.Image(im.size[0], im.size[1], 'Y800', im.tobytes())

            # Check if a barcode is detected
            if self.scanner.scan(zImage) > 0:
                # Get the first result (we assume only one barcode is shown at the same time)
                results = self.scanner.get_results()
                for sym in results:
                    sym_type = str(sym.type)
                    sym_data = str(sym.data)

                self.logger.info("\tType : %s" % sym_type)
                self.logger.info("\tData : %s" % sym_data)
                # Raise the signal
                self.onBarcodeDetected(sym_type, sym_data)
Example #24
0
    def scan_image(self, img_scan, x_start, y_start):
        crop_width, crop_height = img_scan.size
        zbar_img = zbar.Image(crop_width, crop_height, 'Y800',
                              img_scan.tostring())

        # scan the image for barcodes
        self.scanner.scan(zbar_img)

        # Create a draw object
        draw = ImageDraw.Draw(self.image)
        draw_crop = ImageDraw.Draw(img_scan)

        for symbol in zbar_img:
            top_left = (symbol.location[0][0] + x_start,
                        symbol.location[0][1] + y_start)
            bottom_left = (symbol.location[1][0] + x_start,
                           symbol.location[1][1] + y_start)
            bottom_right = (symbol.location[2][0] + x_start,
                            symbol.location[2][1] + y_start)
            top_right = (symbol.location[3][0] + x_start,
                         symbol.location[3][1] + y_start)
            self.informations.append(
                kanban.Information(
                    symbol.data,
                    (top_left, bottom_left, bottom_right, top_right)))
            draw.rectangle([(top_left), (bottom_right)], fill="black")
            draw_crop.rectangle([symbol.location[0], symbol.location[2]],
                                fill="black")
        if len(zbar_img.symbols) > 0:
            self.scan_image(img_scan, x_start, y_start)
Example #25
0
    def scheduled_scan(self, dt):
        camera = self.ids['camera']
        scanner = zbar.ImageScanner()
        scanner.parse_config('enable')
        timestr = time.strftime("%Y%m%d_%H%M%S")
        # app_folder = os.path.dirname(os.path.abspath(__file__))
        # print(app_folder)
        tc = App.get_running_app()
        app_folder = tc.user_data_dir
        if not os.path.exists(app_folder):
            os.makedirs(app_folder)
        camera.export_to_png(app_folder + "/IMG_{}.jpg".format(timestr))
        pil = Image.open(app_folder +
                         "/IMG_{}.jpg".format(timestr)).convert('L')
        width, height = pil.size
        try:
            raw = pil.tostring()
        except (AttributeError, NotImplementedError):
            raw = pil.tobytes()
        image = zbar.Image(width, height, 'Y800', raw)

        scanner.scan(image)

        for symbol in image:
            print 'decoded', symbol.type, symbol.data
            label = self.ids.result
            label.text = str(symbol.type) + '\n\n' + str(symbol.data)
            self.switch_to(self.ids.sc3head)
            # self.ids.camera.play = False
            break
        else:
            os.remove(app_folder + "/IMG_{}.jpg".format(timestr))
            print("Found nothing.")
            Clock.schedule_once(self.scheduled_scan, 1.0 / 2)
        del (image)
Example #26
0
def main():
    capture = cv2.VideoCapture(0)
    while True:
        # To quit this program press q.
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

        # Breaks down the video into frames
        ret, frame = capture.read()

        # Displays the current frame
        #cv2.imshow('Current', frame)

        # Converts image to grayscale.
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        # Uses PIL to convert the grayscale image into a ndary array that ZBar can understand.
        image = Image.fromarray(gray)
        width, height = image.size

        zbar_image = zbar.Image(width, height, 'Y800', image.tobytes())

        scanner = zbar.ImageScanner()
        scanner.scan(zbar_image)  # Prints data from image.
        for decoded in zbar_image:
            print(decoded.data)
def scan_barcode(img):
    gray = img.convert('L')
    ow, oh = gray.size  # Original dimensions
    symbols = {}

    scanner = zbar.ImageScanner()
    for type in symtypes:
        scanner.set_config(type, zbar.Config.ENABLE, 1)

    # Try scaling the image at different sizes. In high-resolution scans, scan
    # or print artifacts can confuse the scanner.
    for scale in TRY_SCALES:
        w = int(ow * scale)
        h = int(oh * scale)

        if scale == 1:
            img = gray
        else:
            if max(h, w) < 400:
                # Resolution too low, give up. (We always try at scale==1)
                break
            img = gray.resize((w, h), Image.BICUBIC)
            assert gray.size != img.size

        zimg = zbar.Image(w, h, 'Y800', img.tostring())
        scanner.scan(zimg)
        for sym in zimg.symbols:
            # For any (type, data) combination keep only the one with the best quality
            key = (sym.type, sym.data)
            if key not in symbols or symbols[key]['quality'] < sym.quality:
                symbols[key] = {'type': sym.type, 'data': sym.data, 'quality': sym.quality, 'scale': scale}

    return symbols.values()
Example #28
0
def qrr():
    logger.info('Executing POST')

    if request.files.get('image'):
        image_bytes = request.files.get('image').file.read()
    else:
        image_bytes = request.body.read()

    if len(image_bytes) <= 0:
        return {'error': 'Unable to decode posted image!'}

    pil = Image.open(io.BytesIO(image_bytes)).convert('L')
    width, height = pil.size

    # wrap image data
    raw = pil.tobytes()
    image = zbar.Image(width, height, 'Y800', raw)

    # scan the image for barcodes
    config.scanner.scan(image)

    results = {}

    for symbol in image:
        #print dir(symbol)

        results['type'] = str(symbol.type)
        results['data'] = symbol.data
        results['location'] = symbol.location
        results['quality'] = symbol.quality
        results['count'] = symbol.count
        #results['components'] = symbol.components

    response.content_type = 'application/json'
    return json.dumps(results)
Example #29
0
 def decode(self, filename=None):
     self.filename = filename or self.filename
     if self.filename:
         scanner = zbar.ImageScanner()
         # configure the reader
         scanner.parse_config('enable')
         # obtain image data
         pil = Image.open(self.filename).convert('L')
         width, height = pil.size
         raw = pil.tobytes()
         # wrap image data
         image = zbar.Image(width, height, 'Y800', raw)
         # scan the image for barcodes
         result = scanner.scan(image)
         # extract results
         if result == 0:
             return False
         else:
             for symbol in image:
                 pass
             # clean up
             del (image)
             # Assuming data is encoded in utf8
             self.data = symbol.data.decode(u'utf-8')
             self.data_type = self.data_recognise()
             return True
     else:
         return False
Example #30
0
 def __readImage(self, img):
     pil = Image.open(img).crop(self.bar_region).convert('L')
     if s.debug_mode: pil.save('debug.jpg')
     # obtain image data
     width, height = pil.size
     raw = pil.tostring()
     return zbar.Image(width, height, 'Y800', raw)