Return run-length encoding string from `img`.
492942
def rle_encode(img:NPArrayMask)->str:
    ""
    pixels = np.concatenate([[0], img.flatten() , [0]])
    runs = np.where(pixels[1:] != pixels[:-1])[0] + 1
    runs[1::2] -= runs[::2]
    return ' '.join(str(x) for x in runs)
939647
public static String toInlineImage(final BufferedImage img, final String alt) {
    return com.simiacryptus.util.Util.toInlineImage(new LabeledObject<>(img, alt));
  }
476949
def from_image(cls, img_filename, mipmap=False, **kwargs):
        """"""
        img = pyglet.image.load(img_filename)
        tex = img.get_mipmapped_texture() if mipmap else img.get_texture()
        gl.glBindTexture(gl.GL_TEXTURE_2D, 0)
        return cls(id=tex.id, data=tex, mipmap=mipmap, **kwargs)
213457
def ansi_len(string):
    """"""
    return len(string) - wcswidth(re.compile(r'\x1b[^m]*m').sub('', string))
1262963
def _get_string(data, position, obj_end, dummy):
    """"""
    length = _UNPACK_INT(data[position:position + 4])[0]
    position += 4
    if length < 1 or obj_end - position < length:
        raise InvalidBSON("invalid string length")
    end = position + length - 1
    if data[end:end + 1] != b"\x00":
        raise InvalidBSON("invalid end of string")
    return _utf_8_decode(data[position:end], None, True)[0], end + 1
148911
def encode2(self):
        """"""
        buf = BytesIO()
        self.fig.savefig(buf, format='png', bbox_inches='tight', dpi=100)
        buf.seek(0)
        string = b64encode(buf.read())
        return '<img src="data:image/png;base64,{0}">'.format(urlquote(string))
774948
private static int getTrimmedHeight(BufferedImage img) {
    int width = img.getWidth();
    int height = img.getHeight();
    int trimmedHeight = 0;

    for (int i = 0; i < width; i++) {
      for (int j = height - 1; j >= 0; j--) {
        if (img.getRGB(i, j) != Color.WHITE.getRGB() && j > trimmedHeight) {
          trimmedHeight = j;
          break;
        }
      }
    }

    return trimmedHeight;
  }
347058
def decode_and_resize(image_str_tensor):
  """"""

  # These constants are set by Inception v3's expectations.
  height = 299
  width = 299
  channels = 3

  image = tf.image.decode_jpeg(image_str_tensor, channels=channels)
  # Note resize expects a batch_size, but tf_map supresses that index,
  # thus we have to expand then squeeze.  Resize returns float32 in the
  # range [0, uint8_max]
  image = tf.expand_dims(image, 0)
  image = tf.image.resize_bilinear(image, [height, width], align_corners=False)
  image = tf.squeeze(image, squeeze_dims=[0])
  image = tf.cast(image, dtype=tf.uint8)
  return image
724973
def bytes_to_string(raw):
    """"""
    ret = bytes()
    for byte in raw:
        if byte == 0x00:
            return ret.decode("utf-8")
        ret += bytes([byte])
    return ret.decode("utf-8")
1107751
def get_dimensions(filenames):
    """"""

    dims = []
    for filename in filenames:
        implemented = False
        with open(filename, 'rb') as fp:

            img_types = (PNGFile, GIFFile, JPEGFile)
            for img_type in img_types:
                sig = str(getattr(img_type, 'SIGNATURE')[0])
                magic = fp.read(len(sig))
                fp.seek(0)
                if magic == sig:
                    cls = img_type.__name__.split('.')[-1]
                    img = getattr(img_type, cls)(fp)
                    x, y = img.size
                    dims.append((x, y, img.content_type, filename))
                    implemented = True
                    break
            if not implemented:
                # might want to fail silently, or print error to stdout...
                print('cannot handle file: %s' % filename)
                raise NotImplementedError
    return dims
921138
def guessImageMetadataFromData(img_data):
    
    format, width, height = None, None, None
    img_stream = io.BytesIO(img_data)
    try:
      img = PIL.Image.open(img_stream)
    except IOError:
      format = imghdr.what(None, h=img_data)
      format = SUPPORTED_IMG_FORMATS.get(format, None)
    else:
      format = img.format.lower()
      format = SUPPORTED_IMG_FORMATS.get(format, None)
      width, height = img.size
    return format, width, height
1015110
def rgChromaticity(img):
    '''
    
    '''
    out = _calc(img)
    if img.dtype == np.uint8:
        out = (255 * out).astype(np.uint8)
    return out
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
956367
def run_length_encode(in_array):
    """"""
    if(len(in_array)==0):
        return []
    curr_ans = in_array[0]
    out_array = [curr_ans]
    counter = 1
    for in_int in in_array[1:]:
        if in_int == curr_ans:
            counter+=1
        else:
            out_array.append(counter)
            out_array.append(in_int)
            curr_ans = in_int
            counter = 1
    # Add the final counter
    out_array.append(counter)
    return out_array
172180
def image_shape(img):
    ''''''
    if hasattr(img, 'shape'):
        return (img.shape[1], img.shape[0])
    return (img.width, img.height)
156346
def hexdump(src, length=8):
    
    if not src:
        return str(src)
    src = input_validate_str(src, 'src')
    offset = 0
    result = ''
    for this in group(src, length):
        hex_s = ' '.join(["%02x" % ord(x) for x in this])
        result += "%04X   %s\n" % (offset, hex_s)
        offset += length
    return result
234531
def to_bytes(self):
		
		chunks = [PNG_SIGN]
		chunks.extend(c[1] for c in self.chunks)
		return b"".join(chunks)