Exemplo n.º 1
0
def image_from_array(img_array, format='png'):
    """Creates an image object from a given numpy array.
    Parameters
    ----------
    img_array : numpy.ndarray
        The image data, which can have 1 or 3 color channels.
    Returns
    -------
    IPython.display.Image
        An image object for plots.
    """
    factor = 1
    if utils.image.is_float_image(img_array):
        factor = 255

    img_data = np.uint8(img_array * factor)
    f = StringIO()
    img_data = utils.image.to_rgb(img_data)
    arr = PIL.Image.fromarray(img_data)
    arr.save(f, format)
    return Image(data=f.getvalue())
Exemplo n.º 2
0
 def criar_imagens_mentais(self, entrada):
     imagem_mental = Image.Image()
     imagem_mental.width = image_setup.WIDTH_EMOTION
     imagem_mental.height = image_setup.HEIGHT_EMOTION
     
     for x in range(0, imagem_mental.width):
         for y in range(0, imagem_mental.height):
       
             if((y*imagem_mental.width + x)>=len(entrada)):
                 break
       
             if (entrada[y*imagem_mental.width + x]):
                 cor = (255, 255, 255)
             else:
                 cor = (0, 0, 0)
       
             imagem_mental.putpixel((x, y), cor)
             y += 1
         x += 1
   
     return imagem_mental
Exemplo n.º 3
0
def runVerification():

    CALIBRATION_DIR = PARENT_DIR / '05 Specimen Images' / '01 Calibration Images' / 'verification'

    verif = DataTree()
    verif.files = DataTree(
        **{
            'front': 'cropped-DSC00600.png',
            'front21': 'cropped-DSC00601.png',
            'front22': 'cropped-DSC00602.png',
            'front23': 'cropped-DSC00603.png',
            'side': 'cropped-DSC00598.png',
            'front_eraser': 'cropped-DSC00594.png',
            'front_eraser_rot': 'cropped-DSC00594 2.png',
            'side_eraser': 'cropped-DSC00596.png',
        })

    verif.files = {
        k: (CALIBRATION_DIR / n).resolve()
        for k, n in verif.files.items()
    }
    verif.files

    dims = DIMS['lg']
    pd = verif.files['front'].parent / 'processed'
    pixel_ratio = DIMS['pixel_ratio']
    pd

    for f, tb in [('front21', (100 + 150, 300 + 550)),
                  ('front22', (100 + 150, 300 + 550))]:
        debug("main", f, tb)
        locations = DataTree(
            front=DataTree(top=DataTree(y=tb[0]), bottom=DataTree(y=tb[1])))
        res, fig = process(pd,
                           verif.files[f],
                           DIMS,
                           'lg',
                           'front',
                           locations=locations)
        display(Image(fig))
Exemplo n.º 4
0
    def handle(self, node: nodes.Node) -> None:
        try:
            drive = self.connect_to_GoogleDrive()
            file_id = url_to_file_id(node['uri'])
            image = Image(drive, file_id,
                          self.app.builder.supported_image_types)

            path = os.path.join(self.imagedir, 'googledrive',
                                file_id + image.extension)
            if os.path.exists(path):
                timestamp = ceil(os.stat(path).st_mtime)
                if timestamp <= image.last_modified:
                    return

            ensuredir(os.path.dirname(path))
            self.env.original_image_uri[path] = node['uri']

            with open(path, 'wb') as f:
                content = image.read()
                if self.config.googledrive_trim_images:
                    content = trim_image(content, image.mimetype)
                f.write(content)

            node['candidates'].pop('?')
            node['candidates'][image.mimetype] = path
            node['uri'] = path
            self.app.env.images.add_file(self.env.docname, path)
        except IOError:
            logger.warning('Fail to download a image: %s (not found)',
                           node['uri'])
        except UnsupportedMimeType as exc:
            logger.warning('Unsupported image: %s (%s)', node['uri'], exc)
        except Exception as exc:
            if isinstance(exc, HttpError) and exc.resp.status == 404:
                logger.warning('Fail to download a image: %s (not found)',
                               node['uri'])
            else:
                logger.warning(
                    'Fail to download a image on Google Drive: %s (%r)',
                    node['uri'], exc)
Exemplo n.º 5
0
    async def test_barrel_distort(base_img_path,
                                  distort_args: Tuple = None,
                                  ctx=None):

        base_img = Image(filename=base_img_path)
        base_img = Manips.magic_rescale(base_img)

        # w, h = base_img.size

        # Changing these values
        # Increasing the value of the first two squeezes the image horizontally
        # Increasing the second two stretches the image so harshly it pulls in outer pixels
        # increasing the third causes intense vertical distortions on the outer edges of the picture
        # Increasing the fourth causes the image to become vertically pinched
        # Zeroing the fourth causes the image to become gigastretched

        # these arguments are perfect for the blown-up sort of look

        if distort_args is None:
            arguments = (0.4, 0.4, 0, 0, 0.5, 0, 0.2, 0.2)
        else:
            arguments = distort_args

        # cursed_stretch_arguments = (0, 0,
        #                             0, 1,
        #                             0, 0,
        #                             -0.7, 1.3)

        # arguments = perfect_expansion_arguments

        if ctx is not None:
            await ctx.send(str(arguments))

        base_img.distort("barrel", arguments)

        img_buffer = np.asarray(bytearray(base_img.make_blob()),
                                dtype=np.uint8)
        retval = cv2.imdecode(img_buffer, cv2.IMREAD_UNCHANGED)
        cv2.imwrite(base_img_path, retval)
        return base_img_path
Exemplo n.º 6
0
    def test_do_save_image__save_enabled(self, mocker):
        grabber = Grabber('http://example.com')

        im = Image.Image()
        mocker.patch.object(im, 'save')

        dummy_save_path = 'some/{Y}/path.jpg'
        dummy_save_path_full = 'some/2017/path.jpg'

        mocker.patch.object(grabber,
                            'get_save_path',
                            return_value=dummy_save_path)
        mocker.patch.object(grabber, 'make_save_path_dirs')
        mocker.patch.object(grabber, 'should_save_image', return_value=True)
        mocker.patch.object(grabber,
                            'format_path',
                            return_value=dummy_save_path_full)

        dummy_result = {
            'image': im,
            'url': 'http://example.com',
            'error': None,
            'requested_at': datetime.now(),
        }

        expected_result = dummy_result.copy()
        expected_result['is_saved'] = True
        expected_result['save_dir'] = grabber.save_dir
        expected_result['save_path'] = dummy_save_path
        expected_result['save_path_full'] = dummy_save_path_full

        result = do_save_image(dummy_result, grabber)

        assert result == expected_result
        grabber.format_path.assert_called_once_with(dummy_save_path, result)
        grabber.get_save_path.assert_called_once_with()
        grabber.make_save_path_dirs.assert_called_once_with(
            dummy_save_path_full)
        grabber.should_save_image.assert_called_with()
        im.save.assert_called_once_with(dummy_save_path_full)
Exemplo n.º 7
0
def create(db):
    form = ImageForm(request.forms.decode())

    # フォームのバリデーション
    if form.validate():

        # Imageインスタンスの作成
        image = Image(
            title=form.title.data,
            file=form.file.data,
        )

        path = os.path.join(os.getcwd(), "static/image", image.file)
        image.lat, image.lon = get_GPS(path)

        # imageを保存
        db.add(image)

        # 一覧画面へリダイレクト
        redirect("/images")
    else:
        return template('edit', form=form, request=request)
Exemplo n.º 8
0
 def do_crop(fname, left, top, width, height):
     if HAS_JPEGTRAN:
         img = JPEGImage(fname)
     else:
         img = Image(filename=fname)
     width = (img.width - left) if width is None else width
     height = (img.height - top) if height is None else height
     if width > (img.width - left):
         width = img.width - left
     if height > (img.height - top):
         width = img.height - top
     if (left, top, width, height) == (0, 0, img.width, img.height):
         self._logger.warn("No-op crop parameters, skipping!")
         return
     self._logger.debug("Cropping \"{0}\" to x:{1} y:{2} w:{3} h:{4}"
                        .format(fname, left, top, width, height))
     cropped = img.crop(left, top, width=width, height=height)
     if HAS_JPEGTRAN:
         cropped.save(fname)
     else:
         img.save(filename=fname)
         img.close()
Exemplo n.º 9
0
    def get_image(self, key):
        """Add an image to the Pikov file.

        Args:
            key (str): Content-based key for image file.

        Returns:
            Image: The image loaded from the Pikov file.

        Raises:
            NotFound: If image with ``key`` is not found.
        """
        with self._connection:
            cursor = self._connection.cursor()
            cursor.execute('SELECT key FROM image WHERE key = ?', (key, ))
            image_row = cursor.fetchone()

            if not image_row:
                raise NotFound(
                    'Could not find image with key "{}"'.format(key))

        return Image(self._connection, key)
Exemplo n.º 10
0
    def overlay_picture_callback(self, instance):
        #print("Time to Overlay Pictures")
        #print("instance.id is:", instance.id)
        #print("instance.background_normal is:", instance.background_normal)
        try:
            self.GUI_widget.remove_widget(self.overlayed_image)
        except:
            print("Widget does not exist!")

        self.overlayed_image = Image(source=instance.background_normal, pos=(906,320)) #considering filtering out white pixel here
        self.overlayed_image.height = 100
        self.overlayed_image.width = 100
        saveImageButton = Button(text="Save Image", pos=(100,1025), font_size=28)
        saveImageButton.size = (200,100)
        self.GUI_widget.add_widget(self.overlayed_image)
        self.GUI_widget.add_widget(saveImageButton)
        self.toggleFlag = False
        saveImageButton.bind(on_press=self.save_overlayed_picture_callback)
        print("self.overlayed_image height width: ", self.overlayed_image.height, self.overlayed_image.width)
        #self.overlayed_image.pos = (100,400)
        #print("Should have added a save button")
        return
Exemplo n.º 11
0
def mediawiki_dict_to_files(session, Base, dest_path, dicts):
    dest_path += '/'
    Image = Base.classes.image
    filenames_ = []
    db_files = session.query(Image.img_name).all()
    for file in db_files:
        print(file.img_name)
        filenames_.append(file.img_name.decode().lower())

    for fd in dicts:
        if fd['file_name'].lower() in filenames_:
            continue

        cpath = dest_path + fd['folder_1'] + '/' + fd['folder_2']
        if not os.path.exists(cpath):
            os.makedirs(cpath)
        copy2(fd['file_path'], cpath)

        new_image = Image(img_name=bytes(fd['file_name'], 'utf-8'),
                          img_size=fd['file_size'],
                          img_width=fd['width'],
                          img_height=fd['height'],
                          img_metadata=b'',
                          img_bits=8,
                          img_media_type='BITMAP',
                          img_major_mime='image',
                          img_minor_mime=bytes(fd['file_format'].lower(),
                                               'utf-8'),
                          img_description=bytes(fd['description'], 'utf-8'),
                          img_user=0,
                          img_user_text=b'',
                          img_timestamp=bytes(mediawiki_currenttime(),
                                              'utf-8'),
                          img_sha1=b'')

        print(fd['file_name'] + ' uploaded.')
        session.add(new_image)

    session.commit()
Exemplo n.º 12
0
    def render(self, mode='human', close=False):

        if close:
          if self.viewer is not None:
            self.viewer.close()
            self.viewer = None
          return

        img = self.model.vae.decoder.predict(np.array([self.z]))[0]

        img = np.array(Image(img).resize(int(np.round(SCREEN_Y*FACTOR)), int(np.round(SCREEN_X*FACTOR))))

        if self.t > 0:
          pass
        if mode == 'rgb_array':
          return img

        elif mode == 'human':
          
          if self.viewer is None:
            self.viewer = rendering.SimpleImageViewer()
          self.viewer.imshow(img)
Exemplo n.º 13
0
def idf_cnn_w2v_brand(doc_id, w1, w2, w3, num_results):
    doc_id = asins.index(df_asins[doc_id])
    idf_w2v_dist = pairwise_distances(w2v_title_weight,
                                      w2v_title_weight[doc_id].reshape(1, -1))
    ex_feat_dist = pairwise_distances(extra_features, extra_features[doc_id])
    cnn_dist = pairwise_distances(
        bottleneck_features_train,
        bottleneck_features_train[doc_id].reshape(1, -1))

    pairwise_dist = (w1 * cnn_dist + w2 * idf_w2v_dist +
                     w3 * ex_feat_dist) / float(w1 + w2 + w3)
    indices = np.argsort(pairwise_dist.flatten())[0:num_results]
    pdists = np.sort(pairwise_dist.flatten())[0:num_results]
    df_indices = list(data.index[indices])
    for i in range(len(indices)):
        rows = data[['medium_image_url',
                     'title']].loc[data['asin'] == asins[indices[i]]]
        for indx, row in rows.iterrows():
            display(Image(url=row['medium_image_url'], embed=True))
            print('Product Title: ', row['title'])
            print('Euclidean Distance from input image:', pdists[i])
            print('Amazon Url: www.amzon.com/dp/' + asins[indices[i]])
Exemplo n.º 14
0
 def make_content(self, content_descriptor):
     # print "make_content: ",content_descriptor['type']
     key = self._generate_key()
     if not isinstance(content_descriptor, type({})):
         return 'invalid'
     if not ('type' in content_descriptor and 'data' in content_descriptor):
         return 'invalid'
         # print "Content seems valid "
     if content_descriptor['type'] == 'plot':
         content = Plot(content_descriptor['data'])
     elif content_descriptor['type'] == 'image':
         content = Image(content_descriptor['data'])
     elif content_descriptor['type'] == 'tipix':
         content = Tipix(content_descriptor['data'])
     elif content_descriptor['type'] == 'graph':
         content = Graph(content_descriptor['data'])
     elif content_descriptor['type'] == 'three_cubes':
         content = ThreeCubes(content_descriptor['data'])
     else:
         return 'nokey'
     self.dict[key] = content
     return key
Exemplo n.º 15
0
 def test_get_neighbours_success(self):
     matrix = [
         [1, 2, 3, 4, 5, 6, 7, 8],
         [1, 2, 3, 4, 5, 6, 7, 8],
         [1, 2, 3, 4, 5, 6, 7, 8],
         [1, 2, 3, 4, 5, 6, 7, 8],
         [1, 2, 3, 4, 5, 6, 7, 8],
         [1, 2, 3, 4, 5, 6, 7, 8],
     ]
     blur_filter = FastBlur(Image.Image())
     blur_filter.width = len(matrix[0])
     blur_filter.height = len(matrix)
     neighbourhood = blur_filter.get_pixel_neighbourhood(3,
                                                         1,
                                                         matrix,
                                                         radius=1)
     expected = [
         [3, 4, 5],
         [3, 4, 5],
         [3, 4, 5],
     ]
     self.assertListEqual(expected, neighbourhood)
Exemplo n.º 16
0
def test_image():
    img = PIL.Image.open(
        BytesIO('darknet_cfg/test_images/test-f17-09-345.jpg'))

    img = np.array(img)
    img = img[:, :, ::-1]  # RGB to BGR

    net = Detector(
        bytes("darknet_cfg/yolov3-tiny.cfg", encoding="utf-8"),
        bytes("darknet_cfg/yolov3-tiny_10000.weights", encoding="utf-8"), 0,
        bytes("darknet_cfg/voc.names", encoding="utf-8"))

    img2 = Image(img)

    results = net.detect(img2)

    results_labels = [x[0].decode("utf-8") for x in results]

    assert "bicycle" in results_labels
    assert "dog" in results_labels
    assert "truck" in results_labels
    assert len(results_labels) == 3
Exemplo n.º 17
0
def go_Cozmo(robot: cozmo.robot.Robot):
    """ Capture an image of the path and show bounding rect of the
        contour of the path.
    """
    log.info('start')
    font = cv2.FONT_HERSHEY_SIMPLEX
    direction = 0
    Images = []
    N_SLICES = 4

    for q in range(N_SLICES):
        Images.append(Image())

    log.info('before true')
    while True:

        #log.info('after true')
        img = np.array(robot.world.latest_image.raw_image)
        array = np.frombuffer(img, dtype='uint8')
        img = cv2.imdecode(array, 1)
        direction = 0
        img = RemoveBackground(img, False)
        #log.info('before image')
        if img is not None:
            log.info('after image')
            t1 = time.clock()
            SlicePart(img, Images, N_SLICES)
            for i in range(N_SLICES):
                direction += Images[i].dir

            log.info(direction)
            fm = RepackImages(Images)
            t2 = time.clock()
            cv2.putText(fm, "Time: " + str((t2 - t1) * 1000) + " ms",
                        (10, 470), font, 0.5, (0, 0, 255), 1, cv2.LINE_AA)
            cv2.imshow("Vision Race", fm)

            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
Exemplo n.º 18
0
def pdf_page_to_png(
    src_pdf,
    resolution=72,
):
    """
    Returns specified PDF page as wand.image.Image png.
    :param PyPDF2.PdfFileReader src_pdf: PDF from which to take pages.
    :param int pagenum: Page number to take.
    :param int resolution: Resolution for resulting png in DPI.
    """
    pagenum = 0
    dst_pdf = PyPDF2.PdfFileWriter()
    dst_pdf.addPage(src_pdf.getPage(pagenum))

    pdf_bytes = io.BytesIO()
    dst_pdf.write(pdf_bytes)
    pdf_bytes.seek(0)

    img = Image(file=pdf_bytes, resolution=resolution)
    img.convert("png")

    return img
Exemplo n.º 19
0
def convert_position_board_to_actual(acc_board):

    board = np.empty((8, 8), dtype=Piece)
    for i in range(64):
        r = 7 - (i // 8)
        c = i - ((i // 8) * 8)
        piece_id = acc_board.piece_at(i)
        if piece_id != None:
            side_id = str(piece_id)
            s = 'W'
            if side_id.islower():
                s = 'B'
            p = calculate_real_position(r, c)
            if side_id.lower() == 'p':
                board[r][c] = Piece((r, c),
                                    Image(Point(p[0], p[1]),
                                          'data/scaled/' + s + 'P.png'),
                                    1 - side_id.islower(), side_id)
            elif side_id.lower() == 'n':
                board[r][c] = Piece((r, c),
                                    Image(Point(p[0], p[1]),
                                          'data/scaled/' + s + 'N.png'),
                                    1 - side_id.islower(), side_id)
            elif side_id.lower() == 'b':
                board[r][c] = Piece((r, c),
                                    Image(Point(p[0], p[1]),
                                          'data/scaled/' + s + 'B.png'),
                                    1 - side_id.islower(), side_id)
            elif side_id.lower() == 'r':
                board[r][c] = Piece((r, c),
                                    Image(Point(p[0], p[1]),
                                          'data/scaled/' + s + 'R.png'),
                                    1 - side_id.islower(), side_id)
            elif side_id.lower() == 'q':
                board[r][c] = Piece((r, c),
                                    Image(Point(p[0], p[1]),
                                          'data/scaled/' + s + 'Q.png'),
                                    1 - side_id.islower(), side_id)
            elif side_id.lower() == 'k':
                board[r][c] = Piece((r, c),
                                    Image(Point(p[0], p[1]),
                                          'data/scaled/' + s + 'K.png'),
                                    1 - side_id.islower(), side_id)
        else:
            board[r][c] = None
    return board
Exemplo n.º 20
0
def create_activation_maps():
    from keras.models import Model
    model, branch_model, head_model = get_trained_model()

    bboxes = get_boxes()

    x = branch_model.layers[-3].output
    branch_model_modified = Model(inputs=branch_model.inputs, outputs=x)
    # print(branch_model_modified.summary())

    start = 10
    end = 50
    image_ids = pd.read_csv(
        '../input/humpback-whale-identification/sample_submission.csv'
    )['Image'].values[start:end]
    images = []
    for image_id in image_ids:
        f = expand_path(image_id)
        bb = bboxes[image_id]
        img_orig = read_cropped_image(f,
                                      bb[0],
                                      bb[1],
                                      bb[2],
                                      bb[3],
                                      img_shape=(BOX_SIZE, BOX_SIZE, 3))
        images.append(img_orig)

    img_line = create_activation_map_for_images(branch_model_modified,
                                                np.array(images),
                                                preprocess_image)

    for i, image_id in enumerate(image_ids):
        img = cv2.cvtColor(img_line[i].astype(np.uint8), cv2.COLOR_RGB2BGR)
        img_path = image_id
        cv2.imwrite(img_path, img)
        print('Heatmap for image: {}'.format(image_id))
        # Image(img_line[i].astype(np.uint8))
        display(Image(filename=img_path))
Exemplo n.º 21
0
    def test_compare(self):
        from rooibos.storage.functions import _imgsizecmp

        class Image:
            def __init__(self, w, h):
                self.width = w
                self.height = h

        data = [Image(w, h) for w in (10, None, 20) for h in (15, 5, None)]

        data = sorted(data, key=cmp_to_key(_imgsizecmp))[::-1]

        self.assertEqual(data[0].width, 20)
        self.assertEqual(data[0].height, 15)

        self.assertEqual(data[1].width, 10)
        self.assertEqual(data[1].height, 15)

        self.assertEqual(data[2].width, 20)
        self.assertEqual(data[2].height, 5)

        self.assertEqual(data[3].width, 10)
        self.assertEqual(data[3].height, 5)
Exemplo n.º 22
0
    def test_push_recent_image(self, mocker):
        ms = MotionSaver()
        ms.save_previous_seconds = 30
        save_previous_seconds_delta = timedelta(seconds=30)
        mocker.patch.object(ms, 'remove_images_older_than')

        image = Image.Image()
        datetime_taken = datetime.now()
        save_path = '/some/path/image.jpg'

        ms.push_recent_image(image, datetime_taken, save_path)

        assert ms.recent_images[0] == {
            'image': image,
            'datetime_taken': datetime_taken,
            'save_path': save_path
        }

        expired_datetime = datetime_taken - save_previous_seconds_delta
        ms.remove_images_older_than.assert_called_once_with(
            ms.recent_images, expired_datetime)

        assert len(ms.recent_images) == 1
Exemplo n.º 23
0
    def __init__(self, input):
        """
        An extension of Image.
        """

        # Check that path exists
        if isinstance(input, str):
            if os.path.exists(input):
                arr = sm.imread(input)
            else:
                raise Exception("Path does not exist: " + input)
        elif isinstance(input, np.ndarray):
            arr = np.array(input)
        else:
            raise TypeError("Exepcted string or array, got:" +
                            str(type(input)))

        # Read file and store each in a separate grayscale image
        self._rows, self._cols, colors = arr.shape
        images = np.split(arr, colors, 2)
        self._images = []
        for image in images:
            self._images.append(Image(np.squeeze(image, axis=2).astype(float)))
Exemplo n.º 24
0
def from_file(file_path):
    """ Creates an Image instance from a png file.
    
    Parameters:
    -----------
    file_path : str
        The path to the png file.
    
    Returns:
    --------
    image : Image
        The image instance
    palette : agb.palette
        The palette of the image
    """
    with open(file_path, 'rb') as f:
        reader = png.Reader(f)
        width, height, data, attributes = reader.read()
        image = Image(None, width, height, depth=attributes['bitdepth'])
        image.data = np.array([*data]).T
        colors = attributes['palette']
        _palette = palette.Palette(colors)
        return image, _palette
Exemplo n.º 25
0
def do_slice(options):
    import os, sys
    fromDir = options.folder
    toDir = options.dest or fromDir
    row = options.row
    col = options.col
    crop_width = options.crop_width
    shrink_width = options.shrink_width
    targets = os.listdir(fromDir)
    errMsgs = []
    for filename in targets:
        try:
            fullFilename = os.path.join(fromDir, filename)
            print('slice %s' % (fullFilename))
            tmp = Image(fullFilename, rows=row, columns=col, dest=toDir,\
                    crop_width=crop_width, shrink_width=shrink_width)
            tmp.slice()
            errMsgs.append('[Success] Slice %s' % (fullFilename))
        except Exception as e:
            print(e)
            errMsgs.append('[Failed] %s' % (str(e)))

    return errMsgs
Exemplo n.º 26
0
    async def image_rotate(self, ctx, *args):
        img_name = await self.trygetImage(ctx, *args)
        if img_name == None:
            img_name = self.lastImgName
            return

        self.lastImgName = img_name

        if img_name == None:
            return

        i = 0
        if "://" in args[0]:
            i += 1

        deg = float(args[i])

        with Image(filename=img_name) as img:
            img.rotate(deg)
            img.save(filename=img_name)

        await ctx.send(file=discord.File(img_name))
        os.remove(img_name)
Exemplo n.º 27
0
    def _infer_custom_type_and_encode(data: Iterable) -> Tuple[Iterable, Optional[FeatureType]]:
        """Implement type inference for custom objects like PIL.Image.Image -> Image type.

        This function is only used for custom python objects that can't be direclty passed to build
        an Arrow array. In such cases is infers the feature type to use, and it encodes the data so
        that they can be passed to an Arrow array.

        Args:
            data (Iterable): array of data to infer the type, e.g. a list of PIL images.

        Returns:
            Tuple[Iterable, Optional[FeatureType]]: a tuple with:
                - the (possibly encoded) array, if the inferred feature type requires encoding
                - the inferred feature type if the array is made of supported custom objects like
                    PIL images, else None.
        """
        if config.PIL_AVAILABLE and "PIL" in sys.modules:
            import PIL.Image

            non_null_idx, non_null_value = first_non_null_value(data)
            if isinstance(non_null_value, PIL.Image.Image):
                return [Image().encode_example(value) if value is not None else None for value in data], Image()
        return data, None
Exemplo n.º 28
0
def test_image_verify(setup_test, caplog):
    c = Camera(sw_cam=True)

    stream = BytesIO()
    # "Rewind" the stream to the beginning so we can read its content
    stream.seek(0)
    f = FakePiCamera()
    f.capture(stream)
    stream.seek(0)
    image = Image.open(stream)
    image.save("should-not-be-required.jpg")
    fn = Path("test_image_verify.jpg")
    c.save_image(image, fn)
    assert Path(fn).is_file()

    c = Camera(sw_cam=True)

    image = Image.Image()
    fn = Path("test_image_dud.jpg")
    caplog.clear()
    c.save_image(image, fn)
    assert not Path(fn).is_file()
    assert "Image has zero width or height" in caplog.text
Exemplo n.º 29
0
    def build_svg(self, outfile):

        # background image
        bg_image = PIL.Image.open(self.image_filename)
        width, height = bg_image.size

        # build a svg object, which size is the same as background
        svg = Svg(width=width, height=height)

        # add background image
        png_link = bg_image.filename
        if self.mode == 'online':
            path = os.path.basename(self.image_filename).split('.')[0]
            png_link = '{}/get/{}/image'.format(KEGGRest.KEGG_API_URL, path)
        elif self.mode == 'base64':
            with safe_open(self.image_filename, 'rb') as f:
                png_link = 'data:image/png;base64,' + base64.b64encode(
                    f.read())

        im = Image(x=0, y=0, width=width, height=height)
        im.set_xlink_href(png_link)
        svg.addElement(im)

        for shape, position, url, title in self.conf_data:
            a = A(target='new_window')
            a.set_xlink_title(title)
            a.set_xlink_href(KEGGRest.KEGG_BASE_URL + url)

            # check gene, and add a highlighted rect or circle
            color = get_gene_color(title, self.genedict)
            child = self.add_child(shape, position, color)
            if child:
                a.addElement(child)

            svg.addElement(a)

        svg.save(outfile, encoding='UTF-8', standalone='no')
Exemplo n.º 30
0
def extract_div(prefix, prefiximage, text, logfunction, temp_folder):
    exp = re.compile("(<div +lang=\\\"latex(_inline)?\\\">((.|\\n)+?)</div>)")
    res = exp.findall(text)
    images = []
    for a, inline, b, c in res:
        logfunction("    ------------ converting (div), prefix ", prefix)
        logfunction("    latex: " + b.strip("\n ").replace("\n", " "))
        cont = get_latex_contraction(b)
        image = prefix + cont + ".gif"
        if not os.path.exists(image):
            if False:
                # using an external service to get the latex image
                url = get_url_latex(b, gif=True)
                svg = get_svg_or_gif(url)
                logfunction("    writing: " + image)
                f = open(image, "wb")
                f.write(svg)
                f.close()
            else:
                # using a local installation of miktex
                image, size = convert_short_latex_into_png(
                    b,
                    temp_folder=temp_folder,
                    fLOG=logfunction,
                    final_name=image)

            images.append(image)
        else:
            from PIL import Image
            im = Image(image)
            size = im.size
        logfunction("    replacing: " + image)
        text = text_replace_div_gif(text, a, b, image, prefiximage,
                                    len(inline) > 0, size)

    return len(res), text, images