I have started working with Kivy recently and have encountered a problem. I need to make a button/thumbnail with a URL image as background. I got some help on the Kivy user forum here but am still a little stuck. Here is my code just for that part:
for image_set, image_type in zip(categorized_images, image_types):
layout = GridLayout(cols=2, size_hint=(None, None))
layout.bind(minimum_height=layout.setter('height'))
scroll_view = ScrollView(size_hint=(None, None), size=(320, 200))
section = AccordionItem(title='%s' % image_type)
layout.add_widget(back_button1)
for image_path in image_set:
layout.add_widget(AsyncImage(source="http://www.example/"'%s' % image_path,\
size_hint=(None, None), size=(160, 160)))
scroll_view.add_widget(layout)
section.add_widget(scroll_view)
accordion.add_widget(section)
What I have now is just a bunch of images being created, but I need thumbnails to be created that will lead to the full sized images. Besides that I have the builder.load_string part and the ButtonBehavior class part mentioned in the Kivy link. I just don't know how to implement in that "for loop". Is it possible to treat the UrlBut instance as a widget?
Thumbnail to Full Image
Make UrlBut create and store a thumbnail when it is instantiated. You can do this with PIL, follow this tutorial http://andrius.miasnikovas.lt/2010/04/creating-thumbnails-from-photos-with-python-pil/
Then, have the on_press method (or equivalent) create a pop-up or overlay that contains the full size image.
Treating the UrlBut as a Widget
Read this: http://kivy.org/docs/api-kivy.lang.html#syntax-of-template
The Kivy docs say that a template defined in the kv file may be instantiated within your Python code like this (I am adapting the example given at that link):
Your kv language template:
[UrlBut#ButtonBehavior+AsyncImage]:
source: ctx.source
button_grab: True
on_press: eval(ctx.on_press)
Then in Python, you can instantiate the template with:
from kivy.lang import Builder
urlbut1 = Builder.template('UrlBut',source='http://lorempixel.com/400/200')
# create a second template with a different image
urlbut2 = Builder.template('UrlBut', source='http://lorempixel.com/400/200')
# and use urlbut1 and urlbut2 as other widgets.
Then, you could automate this with a for-loop:
for image_path in image_set:
layout.add_widget(Builder.template('UrlBut',source="http://www.example/"'%s' % image_path)
Related
I am having some trouble including a Plot-object (produced by jetbrains.letsPlot() + geomHistogram()) within the activity.xml for a Kotlin Android app. I am familiar with basic activity elements but I don't know which one to use in this case and I can not figure it out using https://github.com/JetBrains/lets-plot.
Any help is very appreciated!
You can use Android' WebView to display a plot.
jetbrains.letsPlot() + geomHistogram() produces a Figure object.
First you will have to convert it to a simple Map object using toSpec() method:
val spec = when (plot) {
is Plot -> plot.toSpec()
else -> (plot as GGBunch).toSpec()
}
Next, you will generate a string (plot HTML representation) using PlotHtmlHelper:
val html = PlotHtmlHelper.getStaticDisplayHtmlForRawSpec(spec)
This way you can generate a web page and load it to WebView. The page should also contain a script tag for loading the Lets-Plot JS library.
The code could look similar to this (but with a newer library version - 2.2.1 currently): https://github.com/JetBrains/lets-plot-kotlin/blob/master/demo/browser/src/main/kotlin/frontendContextDemo/BrowserDemoFrontendContext.kt
If you are using Kotlin/JS you may want to take a look at this example as well: https://github.com/alshan/lets-plot-mini-apps/blob/main/js-ir-frontend-app/src/main/kotlin/Main.kt
I use the randomforest estimator, implemented in tensorflow, to predict if a text is english or not. I saved my model (A dataset with 2k samples and 2 class labels 0/1 (Not English/English)) using the following code (train_input_fn function return features and class labels):
model_path='test/'
TensorForestEstimator(params, model_dir='model/')
estimator.fit(input_fn=train_input_fn, max_steps=1)
After running the above code, the graph.pbtxt and checkpoints are saved in the model folder. Now I want to use it on Android. I have 2 problems:
As the first step, I need to freeze the graph and checkpoints to a .pb file to use it on Android. I tried freeze_graph (I used the code here: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/tools/freeze_graph.py). When I call the freeze_graph in my mode, I get the following error and the code cannot create the final .pb graph:
File "/Users/XXXXXXX/freeze_graph.py", line 105, in freeze_graph
_ = tf.import_graph_def(input_graph_def, name="")
File "/anaconda/envs/tensorflow/lib/python2.7/site-packages/tensorflow/python/framework/importer.py", line 258, in import_graph_def
op_def = op_dict[node.op]
KeyError: u'CountExtremelyRandomStats'
this is how I call freeze_graph:
def save_model_android():
checkpoint_state_name = "model.ckpt-1"
input_graph_name = "graph.pbtxt"
output_graph_name = "output_graph.pb"
checkpoint_path = os.path.join(model_path, checkpoint_state_name)
input_graph_path = os.path.join(model_path, input_graph_name)
input_saver_def_path = None
input_binary = False
output_node_names = "output"
restore_op_name = "save/restore_all"
filename_tensor_name = "save/Const:0"
output_graph_path = os.path.join(model_path, output_graph_name)
clear_devices = True
freeze_graph.freeze_graph(input_graph_path, input_saver_def_path,
input_binary, checkpoint_path,
output_node_names, restore_op_name,
filename_tensor_name, output_graph_path,
clear_devices, "")
I also tried the freezing on the iris dataset in "tf.contrib.learn.datasets.load_iris". I get the same error. So I believe it is not related to the dataset.
As a second step, I need to use the .pb file on the phone to predict a text. I found the camera demo example by google and it contains a lot of code. I wonder if there is a step by step tutorial how to use a Tensorflow model on Android by passing a feature vector and get the class label.
Thanks, in advance!
UPDATE
By using the recent version of tensorflow (0.12), the problem is solved. However, now, the problem is that what I should pass to output_node_names ??? How can I get what are the output nodes in the graph ?
Re (1) it looks like you are running freeze_graph on a build of tensorflow which does not have access to contrib ops. Maybe try explicitly importing tensorforest before calling freeze_graph?
Re (2) I don't know of a simpler example.
CountExtremelyRandomStats is one of TensorForest's custom ops, and exists in tensorflow/contrib. As was pointed out, TF switched to including contrib ops by default at some point. I don't think there's an easy way to include the contrib custom ops in the global registry in the previous releases, because TensorForest uses the method of building a .so file that is included as a data file which is loaded at runtime (a method that was the standard when TensorForest was created, but may not be any longer). So there are no easily-included python build rules that will properly link in the C++ custom ops. You can try including tensorflow/contrib/tensor_forest:ops_lib as a dep in your build rule, but I don't think it will work.
In any case, you can try installing the nightly build of tensorflow. The alternative includes modifying how tensorforest custom ops are built, which is pretty nasty.
It's me again!
Well, that's really strange.
I'using kivy for make an App for Android.
I can use the camera, but or the app resets or do something strange.
Here is the problem:
def chamar_camera(nome,pc,objeto,label_passa,instance):
agora = datetime.now()
nome_arquivo = '%s_%s_%.4i_%.2i_%.2i_%.2i_%.2i_%.2i.jpg' % (nome,pc,agora.year,agora.month,agora.day,agora.hour,agora.minute,agora.second)
# Option 1 - These two lines work:
#def sair():print 'oi'
#camera.take_picture(nome_arquivo, sair)
# Option 2 - These two lines work too:
def sair(label_passa,nome_arquivo):print 'oi'
camera.take_picture(nome_arquivo,on_complete=sair(label_passa,nome_arquivo))
# Option 3 - But these don't:
#def sair(label_passa,nome_arquivo):label_passa.text = nome_arquivo
#camera.take_picture(nome_arquivo, on_complete=sair(label_passa,nome_arquivo))
def on_pause(self):return True
def on_resume(self):pass
On option 3, I write a text (nome_arquivo) on a label widget (label_passa), but what happens is that the text is wrote before the camera be activated. So the camera appear, I can take a picture and the App restarts. I also tried just a "def sair(): pass", but this doesn't work. The only thing working is an "print", but on my app I need to write something in that label and update an sqlite database. Any idea why the function is being called before the camera action?
Thanks!
on_pause and on_resume should be defined as methods of your App class, not (as you have here) functions defined locally within the chamar_camera function.
I want to show image (png,jpg etc) in dynamically created (as per requirement and fully through coding) TImage component, at runtime in C++ builder xe8 (not delphi). But I dont want to use opendialogbox (suggested in many web sites). I want to run this app on my android device. I tried to use LoadFromFile(), it crashes the app on android, but when I run this on windows, its running smoothly. I am just a beginner to c++ builder. So guys pls help. Thanx in advance for any kind of help.Here is what I did.
void __fastcall TForm1::TForm1(TComponent* Owner)
{
TImage* img = new TImage(this);
img->Parent = this;
img->Bitmap->LoadFromFile("D:\\res\\profile.png");
}
Did you see what is the error?
If you run the program with the provided by you code I assume the error would be that the file is not found, because there is no such directory "D:\" in android.
One way to set the path is to write a static path which points to your image. For example : "/storage/sdcard0/DCIM/Camera/MyImage.jpg";
The second way is to include the <System.IOUtils.hpp> header and to use some built-in functions like:
System::Ioutils::TPath::GetPicturesPath();
System::Ioutils::TPath::GetAlarmsPath();
You can check them out, they might be useful.
I'd like to know how can I show simple and short data (eg: temperature data from a running script) in Android desktop using SL4A. My script gets temperature data from a web, and I tried showing it via notify, via toast and via dialogs, but I´d like it to remain accesible on the screen.
I undestand that webview is an option but I can´t write the xml code for a simple text box, as I undestand I should.
Is this right? Where could I get a (very) simple code example in xml to show text on screen (not full screen)?
Thanks!
I just re-read your question there are a few examples of full screen webviews however as far as I understand it webview is kind of an all or nothing deal. If you want to us Xml look into the Fullscreenwrapper2 as it allows you to use similar xml layouts to native java apps, from there you can look for examples of xml layouts and modify to fit.
Do you want a widget or just a dialog box? if you just want a dialog box you can just use a dialogCreateAlert
import android
droid = android.Android()
title=("Your Tittle")
content=("Your content")
droid.dialogCreateAlert(title, content)
droid.dialogShow()
However if you want it on a widget the simplest soloution I have found is to use a minimalistic text widget you can pass the data either through tasker or directly using a local intent.
Through Tasker:
import android, time
droid = android.Android()
class Task():
SET_VARIABLE = 547
def new_task(self):
self.action_cnt = 0
self.extras = {'version_number': '1.0', 'task_name': 'task' + str(time.time()), 'task_priority': 9 }
def set_var(self, varname, value):
self.action_cnt += 1
self.extras['action' + str(self.action_cnt)] = {'action': self.SET_VARIABLE, 'arg:1': varname, 'arg:2': value, 'arg:3': False, 'arg:4': False, 'arg:5': False}
def run_task(self):
taskIntent = droid.makeIntent('net.dinglisch.android.tasker.ACTION_TASK', None, None, self.extras).result
droid.sendBroadcastIntent(taskIntent)
def set_var_now(self, varname, value):
self.new_task()
self.set_var(varname, value)
self.run_task()
t = Task()
t.set_var_now("%Var", "Your variable value")
Directly via a Local intent (You select this in MT by using a Local variable field):
import android
droid = android.Android()
activity = 'com.twofortyfouram.locale.intent.action.FIRE_SETTING'
extras = {}
extras['de.devmil.minimaltext.locale.extras.VAR_NAME'] = 'Your Variable name'
extras['de.devmil.minimaltext.locale.extras.VAR_TEXT'] = 'Your Variable content'
packagename = 'de.devmil.minimaltext'
classname = 'de.devmil.minimaltext.locale.LocaleFireReceiver'
intent = droid.makeIntent(activity, None, None, extras, None, packagename, classname).result
droid.sendBroadcastIntent(intent)