Capture the specified image.
170641
function captureImage(page) {
        if (DEBUG && !page.phantom) inspectArgs("captureImage: ", page);

        if (option.selector) {
            let getElement = [ "function () {",
                , "document.body.bgColor = 'white';"
                , `var elem = document.querySelector('${option.selector}');`
                , "return (elem !== null) ? elem.getBoundingClientRect() : null; };"
            ].join("");

            return page.evaluateJavaScript(getElement);
        }
    }
1352484
def _decode_png(self, encoded_observation):
    """"""
    return self._session.obj.run(
        self._decoded_image_t.obj,
        feed_dict={self._encoded_image_p.obj: encoded_observation}
    )
411938
def set_image(self, user, image_path):
        """"""
        _, ext = os.path.splitext(image_path)
        shutil.copy(image_path, self._custom_image_path(user, ext))
605834
def get_exif_data(self, image):
        """"""
        exif_data = {}
        info = image._getexif()
        if info:
            for tag, value in info.items():
                decoded = TAGS.get(tag, tag)
                if decoded == "GPSInfo":
                    gps_data = {}
                    for t in value:
                        sub_decoded = GPSTAGS.get(t, t)
                        gps_data[sub_decoded] = value[t]

                    exif_data[decoded] = gps_data
                else:
                    exif_data[decoded] = value

        return exif_data
663181
def _insertImage(self, filename=None, pixmap=None, stream=None, overlay=1, matrix=None, _imgname=None, _imgpointer=None):
        """"""
        return _fitz.Page__insertImage(self, filename, pixmap, stream, overlay, matrix, _imgname, _imgpointer)
146588
def get_thumbnail(self, original, size, crop, options):
        
        try:
            image = self.create(original, size, crop, options)
        except ThumbnailError:
            image = None
        finally:
            self.cleanup(original)
        return image
1046328
def _load_img(handle, target_dtype=np.float32, size=None, **kwargs):
    """"""

    image_pil = PIL.Image.open(handle, **kwargs)

    # resize the image to the requested size, if one was specified
    if size is not None:
        if len(size) > 2:
            size = size[:2]
            log.warning("`_load_img()` received size: {}, trimming to first two dims!".format(size))
        image_pil = image_pil.resize(size, resample=PIL.Image.LANCZOS)

    image_array = np.asarray(image_pil)

    # remove alpha channel if it contains no information
    # if image_array.shape[-1] > 3 and 'A' not in image_pil.mode:
    # image_array = image_array[..., :-1]

    image_dtype = image_array.dtype
    image_max_value = np.iinfo(image_dtype).max  # ...for uint8 that's 255, etc.

    # using np.divide should avoid an extra copy compared to doing division first
    ndimage = np.divide(image_array, image_max_value, dtype=target_dtype)

    rank = len(ndimage.shape)
    if rank == 3:
        return ndimage
    elif rank == 2:
        return np.repeat(np.expand_dims(ndimage, axis=2), 3, axis=2)
    else:
        message = "Loaded image has more dimensions than expected: {}".format(rank)
        raise NotImplementedError(message)
1303713
def capture(url, path, opts = {})
      begin
        # Default settings
        width   = opts.fetch(:width, 120)
        height  = opts.fetch(:height, 90)
        gravity = opts.fetch(:gravity, "north")
        quality = opts.fetch(:quality, 85)
        full = opts.fetch(:full, true)
        selector = opts.fetch(:selector, nil)
        allowed_status_codes = opts.fetch(:allowed_status_codes, [])

        # Reset session before visiting url
        Capybara.reset_sessions! unless @session_started
        @session_started = false

        # Open page
        visit url

        # Timeout
        sleep opts[:timeout] if opts[:timeout]

        # Check response code
        status_code = page.driver.status_code.to_i
        unless valid_status_code?(status_code, allowed_status_codes)
          fail WebshotError, "Could not fetch page: #{url.inspect}, error code: #{page.driver.status_code}"
        end

        tmp = Tempfile.new(["webshot", ".png"])
        tmp.close
        begin
          screenshot_opts = { full: full }
          screenshot_opts = screenshot_opts.merge({ selector: selector }) if selector

          # Save screenshot to file
          page.driver.save_screenshot(tmp.path, screenshot_opts)

          # Resize screenshot
          thumb = MiniMagick::Image.open(tmp.path)
          if block_given?
            # Customize MiniMagick options
            yield thumb
          else
            thumb.combine_options do |c|
              c.thumbnail "#{width}x"
              c.background "white"
              c.extent "#{width}x#{height}"
              c.gravity gravity
              c.quality quality
            end
          end

          # Save thumbnail
          thumb.write path
          thumb
        ensure
          tmp.unlink
        end
      rescue Capybara::Poltergeist::StatusFailError, Capybara::Poltergeist::BrowserError, Capybara::Poltergeist::DeadClient, Capybara::Poltergeist::TimeoutError, Errno::EPIPE => e
        # TODO: Handle Errno::EPIPE and Errno::ECONNRESET
        raise WebshotError.new("Capybara error: #{e.message.inspect}")
      end
    end
924645
def get_image(self, id):
        """"""
        url = self._base_url + "/3/image/{0}".format(id)
        resp = self._send_request(url)
        return Image(resp, self)
871655
def set_image(self, image):
        
        imwidth, imheight = image.size
        if imwidth != 8 or imheight != 16:
            raise ValueError('Image must be an 8x16 pixels in size.')
        # Convert image to 1 bit color and grab all the pixels.
        pix = image.convert('1').load()
        # Loop through each pixel and write the display buffer pixel.
        for x in xrange(8):
            for y in xrange(16):
                color = pix[(x, y)]
                # Handle the color of the pixel, off or on.
                if color == 0:
                    self.set_pixel(x, y, 0)
                else:
                    self.set_pixel(x, y, 1)
33295
def image_get(auth=None, **kwargs):
    '''
    
    '''
    cloud = get_operator_cloud(auth)
    kwargs = _clean_kwargs(**kwargs)
    return cloud.get_image(**kwargs)
551200
async def get_image(
        self,
        input_source: str,
        output_format: str = IMAGE_JPEG,
        extra_cmd: Optional[str] = None,
        timeout: int = 15,
    ) -> Optional[bytes]:
        """"""
        command = ["-an", "-frames:v", "1", "-c:v", output_format]

        # open input for capture 1 frame
        is_open = await self.open(
            cmd=command,
            input_source=input_source,
            output="-f image2pipe -",
            extra_cmd=extra_cmd,
        )

        # error after open?
        if not is_open:
            _LOGGER.warning("Error starting FFmpeg.")
            return None

        # read image
        try:
            proc_func = functools.partial(self._proc.communicate, timeout=timeout)
            image, _ = await self._loop.run_in_executor(None, proc_func)
            return image

        except (subprocess.TimeoutExpired, ValueError):
            _LOGGER.warning("Timeout reading image.")
            self.kill()
            return None
508135
def find_image(self, image, configuration):
        """"""
        images = configuration["images"]
        available = list(images.keys())

        if not image:
            info = {}
            if available:
                info["available"] = available
            raise BadOption("Please use --image to specify an image", **info)

        if image not in images:
            raise BadOption("No such image", wanted=image, available=available)
1209389
def image(self, image):
        
        if image.mode != '1':
            raise ValueError('Image must be in mode 1.')
        imwidth, imheight = image.size
        if imwidth != self.width or imheight != self.height:
            raise ValueError('Image must be same dimensions as display ({0}x{1}).' \
                .format(self.width, self.height))
        # Grab all the pixels from the image, faster than getpixel.
        pix = image.load()
        # Iterate through the memory pages
        index = 0
        for page in range(self._pages):
            # Iterate through all x axis columns.
            for x in range(self.width):
                # Set the bits for the column of pixels at the current position.
                bits = 0
                # Don't use range here as it's a bit slow
                for bit in [0, 1, 2, 3, 4, 5, 6, 7]:
                    bits = bits << 1
                    bits |= 0 if pix[(x, page*8+7-bit)] == 0 else 1
                # Update buffer byte and increment to next byte.
                self._buffer[index] = bits
                index += 1
1252427
def format_image(self, image, image_format, **kwargs):
        """"""

        if image_format in ('png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp'):
            if image_format != 'webp' and FORCE_WEBP:
                # Always return WebP when supported by the browser
                accept = self.request.META['HTTP_ACCEPT'].split(',')
                if 'image/webp' in accept:
                    image = image.convert('RGBA')
                    image_format = 'webp'
                    kwargs = {'lossless': True}

            if image_format == 'png':
                kwargs['optimize'] = True
            elif image_format == 'jpg':
                image.convert('RGB')
                kwargs['progressive'] = True

            buffer = six.BytesIO()
            image.save(buffer, image_format, **kwargs)
            return buffer.getvalue(), "image/{}".format(image_format)
        else:
            raise ValueError('Unsupported format: {}'.format(image_format))
96720
def ensure_image(name, url, images_root, md5, untar_to=None):
    """"""
    image_dir_path = os.path.join(images_root, name)
    mkdir(image_dir_path)
    image_file_path = os.path.join(image_dir_path, os.path.basename(url))
    ensure_file(url, image_file_path, md5)
    if untar_to:
        prepare_image(image_file_path, untar_to)
384299
def imdecode(image_path):
    """"""
    import os
    assert os.path.exists(image_path), image_path + ' not found'
    im = cv2.imread(image_path)
    return im