Showing posts with label kivy. Show all posts
Showing posts with label kivy. Show all posts

Wednesday, January 17, 2018

Kivy: what is the proper method for animating images with canvas?

Leave a Comment

I am not fully understanding how to use canvas correctly for images with animations.

See the attached snippet, where I load an animated icon into an Image and do both: (1) add_widget the Image (2) create a Rectangle canvas instruction with a texture = Image's texture

The Image animates The Rectangle texture does not

I have read through all of the Kivy manual and read through Image and Canvas and I get the idea that Image is a nice high level class with all of this image animation handling and Canvas is more of a raw low-level drawing canvas.

So here is my question - what is the Kivy-correct architecture for handling animations on a Canvas? I looked at Animation but that seems for more matrix-like animations such as translation, scaling, rotation.

Here is what I am doing now: I have game with large map window and then a bunch of game UX in helper windows The game UX helper windows I do all the kivy layouts and such and use generally Images and so my icons are animating nicely

However in the game map, I am using canvas:

Drawing all of my game objects using this paradigm:

r=Rectangle(texture=some_Image.texture) map.canvas.add(r) 

When the world needs to be re-drawn:

1) map.canvas.clear()

2) draw all of the stuff in their new positions and states (to be faster, I should just track the dirty objects and locations and just draw those, but to be honest I am getting fantastic fps even with this nuclear-level clear on each draw)

This is of course a lot faster and lighter weight than creating and destroying hundreds of widget-classes - what map canvas is for - right?

But the problem is that my icons with animations in a zip file are not animating

Q: Am I thinking of canvas wrong? Should I instead be adding an Image for each of my game objects instead? (And take advantage of all the animated image support?)

from kivy.uix.relativelayout import RelativeLayout from kivy.uix.image import Image from kivy.app import App from kivy.graphics import Rectangle   class MainApp(App):     def __init__(self, **kwargs):         super().__init__(**kwargs)         self.root = RelativeLayout()          # use any zip file of an animated image         self.animated_icon = Image(source='factory_icon.zip')          # If I add an Image, the icon animates         self.root.add_widget(self.animated_icon)          # If I add the Image's texture on to a Rectangle instruction, no animation         r = Rectangle(texture=self.animated_icon.texture, size=(100, 100), pos=(100, 100))         self.root.canvas.add(r)      def build(self):         return self.root   if __name__ == '__main__':     MainApp().run() 

1 Answers

Answers 1

Image.texture property changes in time. It schedules internally methods to update it as the animation goes. This change doesn't propagate to your rectangle because you created it with texture value captured at a very certain point in time, between updates. Consider this example (I use a .gif file for the animation, but the principle should be the same):

from kivy.uix.relativelayout import RelativeLayout from kivy.uix.image import Image from kivy.app import App from kivy.graphics import Rectangle   class MainApp(App):     def __init__(self, **kwargs):         super(MainApp, self).__init__(**kwargs)         self.root = RelativeLayout()          animated_icon = Image(source='test.gif')         animated_icon.bind(texture=self.update_texture)          self.r = Rectangle(texture=animated_icon.texture, size=(500, 255), pos=(100, 100))         self.root.canvas.add(self.r)      def update_texture(self, instance, value):         self.r.texture = value      def build(self):         return self.root   if __name__ == '__main__':     MainApp().run() 

Here I bind my own update_texture method to image's texture property so every time it changes I can update the rectangle accordingly.

Read More

Saturday, December 2, 2017

How do I solve Kivy error: Bad Window (invalid Window parameter)?

Leave a Comment

I installed Kivy and Cython. I am using VirtualBox and Arch Linux with Gnome as my Display Manager. Upon creating the following app,

from kivy.app import App from kivy.uix.button import Button  class CalcApp(App):     def build(self):         return Button(text="Hello World")  if __name__ == '__main__':     CalcApp().run() 

I receive the following error

[INFO   ] [Logger      ] Record log in /home/kyle/.kivy/logs/kivy_17-10-19_40.txt [INFO   ] [Kivy        ] v1.10.0 [INFO   ] [Python      ] v3.6.2 (default, Jul 20 2017, 03:52:27)  [GCC 7.1.1 20170630] [INFO   ] [Factory     ] 194 symbols loaded [INFO   ] [Image       ] Providers: img_tex, img_dds, img_sdl2, img_gif (img_pil, img_ffpyplayer ignored) [INFO   ] [Text        ] Provider: sdl2 [INFO   ] [OSC         ] using <multiprocessing> for socket [INFO   ] [Window      ] Provider: sdl2(['window_egl_rpi'] ignored) X Error of failed request:  BadWindow (invalid Window parameter)   Major opcode of failed request:  4 (X_DestroyWindow)   Resource id in failed request:  0x0   Serial number of failed request:  151   Current serial number in output stream:  152 

If I run the command unset DISPLAY it works as intended, but without the option to minimize, maximize and close window that normally are available.

Is there a way to fix this error so I won't need to type unset DISPLAY every time a new terminal window is open and have it look like a normal window?

1 Answers

Answers 1

Take a look at this issue on Github, it seems likely to be the same problem: https://github.com/kivy/kivy/issues/5476

For posterity (and in case the link breaks), it's likely a multi-sampling issue.

Try these fixes:

  • Use another desktop environment where the multi sampling works
  • downgrade sdl2 to 2.0.5
  • upgrade sdl2 to 2.0.7
  • disable multisampling in kivy (can be done by editing ~/.kivy/config.ini and setting multisampling to 0
Read More

Tuesday, October 31, 2017

Starting Kivy service on bootup (Android)

Leave a Comment

I'm trying to start my kivy app's service on bootup.

I'm sure that my service is ok because it works when I start my app. But on bootup I have a problem.

I've read this article and tried to make it:

package net.saband.myapp;  import android.content.BroadcastReceiver; import android.content.Intent; import android.content.Context; import org.kivy.android.PythonActivity;  public class MyBroadcastReceiver extends BroadcastReceiver {     public void onReceive(Context context, Intent intent) {         Intent ix = new Intent(context, PythonActivity.class);         ix.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);         context.startActivity(ix);     } } 

It works but starts the app but not the service. So I've studied some questions on StackOverflow and changed my code for this:

package net.saband.myapp;  import android.content.BroadcastReceiver; import android.content.Intent; import android.content.Context; import net.saband.myapp.ServiceMyservice;  public class MyBroadcastReceiver extends BroadcastReceiver {     public void onReceive(Context context, Intent intent) {         Intent ix = new Intent(context, ServiceMyservice.class);         ix.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);         context.startService(ix);     } } 

... and got an error:

10-21 19:16:44.784  1513  1569 I ActivityManager: Start proc 6334:net.saband.myapp:service_myservice/u0a116 for service net.saband.myapp/.ServiceMyservice 10-21 19:16:44.786  6334  6334 I art     : Late-enabling -Xcheck:jni 10-21 19:16:44.885  6334  6334 D AndroidRuntime: Shutting down VM 10-21 19:16:44.888  6334  6334 E AndroidRuntime: FATAL EXCEPTION: main 10-21 19:16:44.888  6334  6334 E AndroidRuntime: Process: net.saband.myapp:service_myservice, PID: 6334 10-21 19:16:44.888  6334  6334 E AndroidRuntime: Theme: themes:{} 10-21 19:16:44.888  6334  6334 E AndroidRuntime: java.lang.RuntimeException: Unable to start service net.saband.myapp.ServiceMyservice@8c96929 with Intent { cmp=net.saband.myapp/.ServiceMyservice }: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference 

Can you please explain me what's wrong and what should I do to start the service? Thanks!

UPDATED

By request of @Juggernaut I add my service code:

from time import sleep  if __name__ == '__main__':     while True:         print "myapp service"         sleep(5) 

It works when I run app because app calls the service:

def __start_service(self):     if platform == 'android':         service = autoclass('net.saband.myapp.ServiceMyservice')         mActivity = autoclass('org.kivy.android.PythonActivity').mActivity         argument = ''         service.start(mActivity, argument) 

1 Answers

Answers 1

It seems that Service or Activity that you try to start is not initialized. You didn't paste your AndroidManifest, so I'll write what it's supposed to have.

The first thing is that you should have permission added to run on boot:

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/> 

The second thing is that you should define your receiver in Manifest:

    <receiver android:name=".MyBroadcastReceiver"               android:enabled="false">         <intent-filter>             <action android:name="android.intent.action.BOOT_COMPLETED"/>         </intent-filter>     </receiver> 

The third thing is that you should define your service or activity you try to start, e.g:

    <activity android:name=".PythonActivity" />     <service android:name=".ServiceMyservice" android:exported="false"/> 
Read More

Monday, June 12, 2017

Why is kivy read_pixel not returning expected color?

Leave a Comment

I am trying to create markers on an image that would allow a user to select colors, mark features etc. Ultimately I would like to have the corresponding image pixel for further use via opencv.

I'm having a lot of trouble getting the expected color under the touch and it sometimes returns colors like magenta which are not even in the example image.

I am pretty sure the problem is with how I am converting the touch position to the values I am handing to the read_pixel function.

I have tried many different solutions without success so I think there is something I am missing here.

main.py

from kivy.app import App from kivy.properties import ListProperty, ObjectProperty from kivy.uix.image import AsyncImage from kivy.uix.relativelayout import RelativeLayout from kivy.uix.widget import Widget from kivy.uix.screenmanager import ScreenManager, Screen   class Marker(Widget):     selected_color = ListProperty([0,1,0])      def __init__(self, **kwargs):         super(Marker, self).__init__(**kwargs)         self.selected_pos = None      def on_touch_down(self, touch):         if self.collide_point(*touch.pos):             print("Touched at Marker: {0}".format(touch.spos))      def on_touch_move(self, touch):         self.set_position_from_touch(touch.spos)      def set_position_from_touch(self, spos):         # print("touch: {0}".format(touch))         self.image = self.parent.parent.image         x = spos[0] * self.image.width         y = spos[1] * self.image.height          # setting position of the widget relative to touch         self.pos = (x-self.width/2, y-self.height*(2/3))         # self.pos = (x, y)          print("widget position : {0}".format(self.pos))         # converting widget position to pixel(row, column of         selected_pixel = self.image.to_row_col(self.pos)         print("selected Pixel: {0}".format(selected_pixel))          try:             self.selected_color = self.image._coreimage.read_pixel(                 selected_pixel[0],                 selected_pixel[1])                 # this skips conversion and just uses pos                 # self.pos[0],                 # self.pos[1])         except IndexError:             print("position out of range")   class MarkerManager(RelativeLayout):     def __init__(self, **kwargs):         super(MarkerManager, self).__init__(**kwargs)         self.marker_mode = None         self.features = []      def on_touch_down(self, touch):         if self.collide_point(*touch.pos):             child_touched = False             print("Touched: {0}".format(touch))             if self.children:                 for child in self.children[:]:                     if child.collide_point(touch.pos[0], touch.pos[1]):                         child_touched = True                         child.dispatch('on_touch_down', touch)             if not child_touched:                 print("Touched only Image at: {0}".format(touch.spos))                 marker = Marker()                 self.features.append(marker)                 self.add_widget(marker)                 marker.set_position_from_touch(touch.spos)  class SelectedImage(AsyncImage):     def __init__(self, **kwargs):         super(SelectedImage, self).__init__(**kwargs)         self.allow_stretch=True         self.keep_ratio=False      def to_row_col(self, pos):         pixels_x = self._coreimage.width         pixels_y = self._coreimage.height         pixel_x = (pos[0] / self.width) * pixels_x         # pixel_y = (pos[1] / self.height) * self.pixels_y         pixel_y = (1 - (pos[1] / self.height)) * pixels_y         # should correspond to row column of image         return [int(pixel_x), int(pixel_y)]  class ImageScreen(Screen):     image = ObjectProperty()     manager = ObjectProperty()     def __init__(self, **kwargs):         super(ImageScreen, self).__init__(**kwargs)  class PointsSelectorApp(App):     def build(self):         return ImageScreen()  if __name__ == "__main__":     PointsSelectorApp().run() 

pointsselector.kv

<ImageScreen>:     image: image_id     manager: manager_id      SelectedImage:         id: image_id         source: "rainbow_checkerboard.jpg"         keep_data: True      MarkerManager:         id: manager_id   <Marker>:     size_hint: None, None     size: "40dp", "40dp"     canvas:         Color:             rgb: self.selected_color         Ellipse:             pos: self.pos[0]+self.width/4, self.pos[1]+self.height/3 #            pos: self.pos[0], self.pos[1]             size: self.width*.6, self.height*.6 

here is my image i have been using to test with "rainbow_checkerboard.jpg"

my test image

1 Answers

Answers 1

I believe this is a bug in the Kivy itself. Particularly I think that line 901 at the kivy/core/image/__init__.py

    index = y * data.width * size + x * size     raw = bytearray(data.data[index:index + size])     color = [c / 255.0 for c in raw] 

is wrong. It should be

    index = y * data.rowlength + x * size 

instead.

Important thing here is that for performance reasons bitmap images in memory are alligned at 4 bytes addresses. Thus there is an explicit data.rowlength field. Usually that line works fine because images are typically well alligned so that data.rowlength = data.width * size. But your particular image is different: it uses 3-bytes RGB format (no alpha) and its width is odd 561 i.e. data.width * size = 1683 and so data.rowlength should be rounded up to 1684, which it actually is but that code doesn't take it into account. It means that often you read colors from two consecutive pixels and with RGB components randomly rotated.

Additionally since you use JPEG format for your image, borders between "cells" are not really strict. If you zoom in really hard, you can see some compression artifacts such as these from around bottom-left corner.

JPEG Artifacts

Those artifacts mutliplied by the aforementioned random color components rotation bug give you very strange (seemingly non-existent) colors.

Possible workarounds

  1. Change your image so that it is pre-aligned in the memory and the bug doesn't affect you (for example use mutliple of 4 as width)
  2. Submit a bug or even a pull request to the Kivy and wait for it to be fixed
  3. Patch kivy/core/image/__init__.py file locally (I tried it and it seems to work fine).
Read More

Sunday, March 26, 2017

Tensorflow on Android with Python bindings?

Leave a Comment

I am trying to build Tensorflow core with Python bindings for Android - to be used from a Kivy app in Android, but not sure how to get the Python bindings working.

Compiling the Tensorflow core for Android works with the following:

bazel build -c opt \   --crosstool_top=//external:android/crosstool \   --cpu=armeabi-v7a \   --host_crosstool_top=@bazel_tools//tools/cpp:toolchain \   --verbose_failures \   //tensorflow/core:android_tensorflow_lib 

Does anybody know how to add Python bindings to it? Is that even possible?

I have read the documentations, did lots of searching, but no luck finding anything about this. I saw that lot of other people are also interested in getting Tensorflow working on Kivy (both for Android and iOS), but nobody seems to have done it so far. People only got as far as saying that we would need an python-for-android recipe built, but the first step for a recipe is to build for Android with Python bindings, hence the question above.

1 Answers

Answers 1

Note: I have never worked with Tensorflow


Judging from pypi the only dependency problem here might be NumPy, but there's a recipe for it. So, we have NumPy, but there's no recipe for the Tensorflow itself. What now?

The answer is in the documentation on how to make a recipe.

First I'd look at the already working recipes, to actually understand how they work, especially the ones that work with C/C++ and not with Cython as it's a little bit easier to make a recipe for Cython (more even if you made the code).

These are the recipes I consider a basic stone for creating a recipe for Tensorflow:

Each of them has a part that will help you to assemble a working recipe. Now, there's a problem with the bindings. There are manylinux wheels, but those most likely won't help you on Android (like at all) in the state they are. Therefore you'll need to build from source (obviously) and they have a whole folder related to that part.

That leads us to your piece of bazel code. In build_pip_package.sh there's a lot of lines related to the bazel thingy.

So, after you understand how the recipes work there are two possibilities:

  • your piece of code actually does something and builds it for android
  • your code is worthless

If your code actually works, there's a good chance you'll be able to combine the already made setup.py file into a simple-looking recipe hopefully just with another platform check (and using the correct bazel binary I presume). As there already is setup.py file, the package files should be moved to the Python that's compiled for Android.

On the other hand if the piece of code you pasted above is worthless, then you'll probably end up with compiling the code yourself + reinventing their setup.py just for the P4A as a recipe. If you aren't familiar with the compilation steps required for building from source, I really don't envy you the process.


Also it might be a good thing to mention the size of the final APK. You can see Tensorflow on PyPI with just a small wheel of 13MB for Windows. Manylinux wheels, however, are huge (37-42MB) and I think you'll end up with a size inbetween those two for Android if you plan to install anything else than Tensorflow itself. There's always NumPy you'll have to drag with it to the phone as a dependency. So that gives you ~50MB+ APK file, which might not be really desired (depends on you).

This piece of code related to Python in their repo might help you too.

Read More

Monday, April 25, 2016

`pip install pygments` incomplete install when run as build phase in XCode

Leave a Comment

I am running the command:

pip -v install pygments==2.0.2 --force-reinstall --ignore-installed --target . 

as part of my build process in a Kivy iOS project. When I run the command myself in the terminal, pygments is installed correctly. When XCode runs it, the pygments package does not install any files in the pygments/formatters directory.

I have verified that the same pip is used for my user and when XCode runs pip.

Output when I install pygments:

(rdoherty.local) %% pip -v install pygments==2.0.2 --force-reinstall --ignore-installed --target .                                       ~/Documents/projects/kivy-ios/racecapture-ios/YourApp (master) Downloading/unpacking pygments==2.0.2   Could not fetch URL https://pypi.python.org/simple/pygments/2.0.2: 404 Client Error: Not Found   Will skip URL https://pypi.python.org/simple/pygments/2.0.2 when looking for download links for pygments==2.0.2   [snip]   Using version 2.0.2 (newest of versions: 2.0.2, 2.0.2)   Downloading Pygments-2.0.2-py2-none-any.whl (672kB):   Downloading from URL https://pypi.python.org/packages/2.7/P/Pygments/Pygments-2.0.2-py2-none-any.whl#md5=98f29db02f4b22f58a2d3f60646e1e1f (from https://pypi.python.org/simple/pygments/) ...Downloading Pygments-2.0.2-py2-none-any.whl (672kB): 672kB downloaded Installing collected packages: pygments Successfully installed pygments 

Output when Xcode runs the exact same command:

Downloading/unpacking pygments==2.0.2   Could not fetch URL https://pypi.python.org/simple/pygments/2.0.2: 404 Client Error: Not Found   [snip]   Using version 2.0.2 (newest of versions: 2.0.2, 2.0.2)   Downloading from URL https://pypi.python.org/packages/2.7/P/Pygments/Pygments-2.0.2-py2-none-any.whl#md5=98f29db02f4b22f58a2d3f60646e1e1f (from https://pypi.python.org/simple/pygments/) Installing collected packages: pygments Successfully installed pygments 

I have downloaded the file that pip downloads and verified it contains files in the formatters directory. I have verified that the same pip program is being used for both myself and XCode:

(rdoherty.local) %% which pip                                                                                                            ~/Documents/projects/kivy-ios/racecapture-ios/YourApp (master) /usr/local/bin/pip 

How or why would pip incorrectly unzip or install pygments when run in an Xcode build phase vs directly?

1 Answers

Answers 1

This was a PEBKAC issue. Kivy iOS projects have a few default build steps and one of them is to delete all *.py files in your app's directory. Normally this is fine because there is a step before this that compiles all the .py files to .pyc. But my build steps had the pip install command running after the compilation step. So all .py files were being removed inside the Pygments directory before they were compiled to .pyc.

Read More