Attention on image feature with question as query.
3902
def attn(image_feat,
         query,
         hparams,
         name="attn",
         save_weights_to=None,
         make_image_summary=True):
  """"""
  with tf.variable_scope(name, "attn", values=[image_feat, query]):
    total_key_depth = hparams.attention_key_channels or hparams.hidden_size
    total_value_depth = hparams.attention_value_channels or hparams.hidden_size
    num_heads = hparams.num_heads
    query = tf.expand_dims(query, 1)
    q, k, v = common_attention.compute_qkv(
        query,
        image_feat,
        total_key_depth,
        total_value_depth,
    )
    q = common_attention.split_heads(q, num_heads)
    k = common_attention.split_heads(k, num_heads)
    v = common_attention.split_heads(v, num_heads)

    if hparams.scale_dotproduct:
      key_depth_per_head = total_key_depth // num_heads
      q *= key_depth_per_head**-0.5

    # image_feat is input as v
    x = common_attention.dot_product_attention(
        q, k, v, None,
        dropout_rate=hparams.attention_dropout,
        image_shapes=None,
        save_weights_to=save_weights_to,
        make_image_summary=make_image_summary)
    x = common_attention.combine_heads(x)

    return tf.squeeze(x, axis=1)
676356
def avail_images():
    '''
    
    '''
    response = _query('grid', 'image/list')

    ret = {}
    for item in response['list']:
        name = item['friendlyName']
        ret[name] = item

    return ret
194021
def image_query_record(self, imagename=None):
        """"""

        if imagename:
            with get_image_conn() as conn:
                result = conn.execute("SELECT * FROM image WHERE "
                                      "imagename=?", (imagename,))
                image_list = result.fetchall()
            if not image_list:
                obj_desc = "Image with name: %s" % imagename
                raise exception.SDKObjectNotExistError(obj_desc=obj_desc,
                                                   modID=self._module_id)
        else:
            with get_image_conn() as conn:
                result = conn.execute("SELECT * FROM image")
                image_list = result.fetchall()

        # Map each image record to be a dict, with the key is the field name in
        # image DB
        image_keys_list = ['imagename', 'imageosdistro', 'md5sum',
                      'disk_size_units', 'image_size_in_bytes', 'type',
                      'comments']

        image_result = []
        for item in image_list:
            image_item = dict(zip(image_keys_list, item))
            image_result.append(image_item)
        return image_result
732653
def search(self, terms):
        
        images   = {}
        response = self._request_builder('GET', 'search', params={'q': terms})

        if self._validate_response(response):
            body = json.loads(response.content.decode('utf-8'))['results']
            for image in body:
                images[image['name']] = image

        return images
857258
def process_question(self):
        
        # Process question
        self.question, question_files = self.set_images(self.question)

        # Process answers
        answers = []
        answer_files = []
        answer_index = 0
        for answer in self.answers:
            processed_string, afiles = self.set_images(answer['answer'])
            answers.append({"answer": processed_string, "correct": answer['correct'], "order": answer_index})
            answer_index += 1
            answer_files += afiles
        self.answers = answers

        # Process hints
        hints = []
        hint_files = []
        hint_index = 0
        for hint in self.hints:
            processed_string, hfiles = self.set_images(hint)
            hints.append({"hint": processed_string, "order": hint_index})
            hint_index += 1
            hint_files += hfiles
        self.hints = hints

        self.files += question_files + answer_files + hint_files
        return [f.filename for f in self.files]
585715
def make_response(self, image, size, mode, filename=None, *args, **kwargs):
        
        try:
            fmt = get_format(image)
        except IOError:
            # not a known image file
            raise NotFound()

        self.content_type = "image/png" if fmt == "PNG" else "image/jpeg"
        ext = "." + str(fmt.lower())

        if not filename:
            filename = "image"
        if not filename.lower().endswith(ext):
            filename += ext
        self.filename = filename

        if size:
            image = resize(image, size, size, mode=mode)
            if mode == CROP:
                assert get_size(image) == (size, size)
        else:
            image = image.read()

        return make_response(image)
450639
def question_encoder(question, hparams, name="encoder"):
  """"""
  with tf.variable_scope(name, "encoder", values=[question]):
    question = common_layers.flatten4d3d(question)
    padding = common_attention.embedding_to_padding(question)
    length = common_attention.padding_to_length(padding)

    max_question_length = hparams.max_question_length
    question = question[:, :max_question_length, :]
    actual_question_length = common_layers.shape_list(question)[1]
    length = tf.minimum(length, max_question_length)
    padding = [[0, 0],
               [0, max_question_length-actual_question_length],
               [0, 0]]
    question = tf.pad(question, padding)
    question_shape = question.get_shape().as_list()
    question_shape[1] = max_question_length
    question.set_shape(question_shape)

    # apply tanh dropout on question embedding
    question = tf.tanh(question)
    question = tf.nn.dropout(question, keep_prob=1.-hparams.dropout)

    question = [question[:, i, :] for i in range(max_question_length)]

    # rnn_layers = [_get_rnn_cell(hparams)
    #               for _ in range(hparams.num_rnn_layers)]
    # rnn_multi_cell = tf.nn.rnn_cell.MultiRNNCell(rnn_layers)
    rnn_cell = _get_rnn_cell(hparams)
    # outputs, _ = tf.nn.dynamic_rnn(
    #     rnn_cell, question, length, dtype=tf.float32)
    _, state = tf.nn.static_rnn(rnn_cell, question, sequence_length=length,
                                dtype=tf.float32)
    # outputs = [tf.expand_dims(output, axis=1) for output in outputs]
    # outputs = tf.concat(outputs, axis=1)

    # utils.collect_named_outputs("vqa_attention_debug", "question_output",
    #                             outputs)
    # utils.collect_named_outputs("vqa_attention_debug", "question_state",
    #                             state.h)

    # batch_size = common_layers.shape_list(outputs)[0]
    # row_indices = tf.range(batch_size)
    # # length - 1 as index
    # indices = tf.transpose([row_indices, tf.maximum(length-1, 0)])
    # last_output = tf.gather_nd(outputs, indices)

    # utils.collect_named_outputs("vqa_attention_debug",
    #                             "question_final_output", last_output)

  return state.h
890105
def focus_next_matching(self, querystring):
        """"""
        self.focus_property(lambda x: x._message.matches(querystring),
                            self._tree.next_position)
1058682
def display(self, display_before=False):
        """"""
        try:
            copy = self.image.copy()
        except AttributeError:
            raise Exception("You need to set the Filter.image attribute for displaying")
        copy = BrightnessProcessor(brightness=0.6).process(copy)
        s, g = self._input, self.good_segments_indexes
        draw_segments(copy, s[g], (0, 255, 0))
        draw_segments(copy, s[True ^ g], (0, 0, 255))
        show_image_and_wait_for_key(copy, "segments filtered by " + self.__class__.__name__)
422103
def function(self,p):
        """"""
        int_index=int(len(p.generators)*wrap(0,1.0,p.index))
        pg=p.generators[int_index]

        image_array = pg(xdensity=p.xdensity,ydensity=p.ydensity,bounds=p.bounds,
                         x=p.x+p.size*(pg.x*np.cos(p.orientation)-pg.y*np.sin(p.orientation)),
                         y=p.y+p.size*(pg.x*np.sin(p.orientation)+pg.y*np.cos(p.orientation)),
                         orientation=pg.orientation+p.orientation,size=pg.size*p.size,
                         scale=pg.scale*p.scale,offset=pg.offset+p.offset)

        return image_array
190739
def _set_imageinfo_data(self):
        
        data = self._load_response('imageinfo')
        pages = data['query'].get('pages')

        normalized = []
        if 'normalized' in data['query']:
            normalized = data['query']['normalized']

        for page in pages:
            title = page.get('title')
            imageinfo = page.get('imageinfo')
            if imageinfo:
                self.__pull_image_info(title, imageinfo, normalized)

        # Mark missing imageinfo to prevent duplicate requests
        for img in self.data['image']:
            if 'url' not in img:
                img['url'] = 'MISSED'
721183
function loadImage(title, imageURI) {
  var img = new Image();
  img.src = imageURI;
  var deferred = when.defer();
  img.onload = deferred.resolve;
  return deferred.promise.then(function() {
    return {
      title: title,
      image: img,
      imageUrl: imageURI,
      imageWidth: img.width,
      imageHeight: img.height
    };
  });
}
1357249
def get(img, light=False):
    """"""
    colors = gen_colors(img)
    return adjust(colors, light)
222733
public void showMe(Answer<T> callback) {
        CalculusTask<T> task = new CalculusTask(image,calculus,callback);

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {

            if(executor == null) {
                executor = AsyncTask.THREAD_POOL_EXECUTOR;
            }

            task.executeOnExecutor(executor);
        } else {
            task.execute();
        }

    }
675416
def _parse_image(self):
        
        image = {
            'title': self._channel.find('./image/title').text,
            'width': int(self._channel.find('./image/width').text),
            'height': int(self._channel.find('./image/height').text),
            'link': self._channel.find('./image/link').text,
            'url': self._channel.find('./image/url').text
        }

        return Image(image)
1362424
def _match_auto(self, screen, search_img, threshold):
        
        # 1. try template first
        ret = ac.find_template(screen, search_img)
        if ret and ret['confidence'] > threshold:
            return FindPoint(ret['result'], ret['confidence'], consts.IMAGE_MATCH_METHOD_TMPL, matched=True)

        # 2. try sift
        ret = ac.find_sift(screen, search_img, min_match_count=10)
        if ret is None:
            return None

        matches, total = ret['confidence']
        if 1.0*matches/total > 0.5: # FIXME(ssx): sift just write here
            return FindPoint(ret['result'], ret['confidence'], consts.IMAGE_MATCH_METHOD_SIFT, matched=True)
        return None
629292
def image_search(auth=None, **kwargs):
    '''
    
    '''
    cloud = get_operator_cloud(auth)
    kwargs = _clean_kwargs(**kwargs)
    return cloud.search_images(**kwargs)