# Category: tutorials

## svm python

A common task in Machine Learning is to classify data. Given a data point cloud, sometimes linear classification is impossible. In those cases we can use a Support Vector Machine instead, but an SVM can also work with linear separation.

Related Course:

Dataset
We loading the Iris data, which we’ll later use to classify. This set has many features, but we’ll use only the first two features:

• sepal length
• sepal width
The code below will load the data points on the decision surface.

Support Vector Machine Example
Separating two point clouds is easy with a linear line, but what if they cannot be separated by a linear line?

In that case we can use a kernel, a kernel is a function that a domain-expert provides to a machine learning algorithm (a kernel is not limited to an svm).

The example below shows SVM decision surface using 4 different kernels, of which two are linear kernels.

## python logarithmus

Tipp
Sie können den Python-Interpreter als Taschenrechner verwenden. Dazu starten Sie einfach Python ohne IDE und Dateinamen. Beispiel:

`  Python 2.7.6 (Standard, 22. Juni 2015, 17:58:13)[GCC 4.8.2] auf linux2Geben Sie "help", "copyright", "Credits" oder "Lizenz" für weitere Informationen.>>> 18 * 17306>>> 2 ** 416>>>  `

Related Course:
Python Programming Bootcamp: Go from zero to hero

## Mathematische Funktionen

Python unterstützt eine Vielzahl von mathematischen Funktionen.

## python thumbnail

Inspired by Netflix, we decided to implement a focal point algorithm. If you use the generated thumbnails on mobile websites, it may increase your click-through-rate (CTR) for YouTube videos. Eiterway, it’s a fun experiment.

Related course:
Master Computer Vision with OpenCV

Focal Point

All images have a region of interest, usually a person or face.

This algorithm that finds the region of interest is called a focal point algorithm. Given an input image, a new image (thumbnail) will be created based on the region of interest.

Start with an snapshot image that you want to use as a thumbnail. We use Haar features to find the most interesting region in an image. The haar cascade files can be found here:

Funktion Gibt Beispiel
Abs(x) Der Absolute Wert von x zurückgibt. {% codeblock lang:python line_number:false %} X =-35 X = abs(x) Print(x) {% endcodeblock %}
CMP(x,y) Gibt-1 zurück, wenn X < y
Gibt 0 zurück, wenn x gleich y
Gibt 1 zurück, wenn X > y.
{% codeblock lang:python line_number:false %} X = 6 y = 4 Drucken (cmp(x,y)) {% endcodeblock %}
EXP(x) Kehrt die exponentielle x {% codeblock lang:python line_number:false %} Import-Mathematik X = 6 Drucken (math.exp(x)) {% endcodeblock %}
Log(x) Den natürlichen Logarithmus von x {% codeblock lang:python line_number:false %} Import-Mathematik X = 6 Drucken (math.log(x)) {% endcodeblock %}
log10(x) Der Logarithmus Base-10 x {% codeblock lang:python line_number:false %} Import-Mathematik X = 6 Drucken (math.log10(x)) {% endcodeblock %}
Pow(x,y) Das Ergebnis von X ** y {% codeblock lang:python line_number:false %} Import-Mathematik X = 6 Drucken (math.pow(x,2)) {% endcodeblock %}
sqrt(x) Die Quadratwurzel von x {% codeblock lang:python line_number:false %} Import-Mathematik X = 6 Drucken (math.sqrt(x)) {% endcodeblock %}
Netflix like Thumbnails Python. Source: Google videos.
 `#! /usr/bin/pythonimport cv2bodyCascade = cv2.CascadeClassifier('data/haarcascade_mcs_upperbody.xml')frame = cv2.imread('snapshot.png')frameHeight, frameWidth, frameChannels = frame.shaperegions = bodyCascade.detectMultiScale(frame, 1.8, 2)x,y,w,h = regions[0]cv2.imwrite('thumbnail.png', frame[0:frameHeight,x:x+w])cv2.rectangle(frame,(x,0),(x+w,frameHeight),(0,255,255),6)cv2.imshow("Result",frame)cv2.waitKey(0);`

The image is saved as thumbnail using cv2.imwrite() and finally we show the image and highlight the region of interest with a rectangle. After running you will have a nice thumbnail for mobile webpages or apps.

If you also want to detect both body and face you can use:

Related course:
Master Computer Vision with OpenCV

## Operaciones matemáticas

Sugerencia
Puede utilizar el intérprete de Python como calculadora. Para ello simplemente iniciar Python sin un IDE y un nombre de archivo. Ejemplo:

`  Python 2.7.6 (por defecto, 22 de junio de 2015, 17:58:13)[GCC 4.8.2] de linux2Tipo de "ayuda", "copyright", "créditos" o "licencia" para obtener más información.>>> 18 * 17306>>> 2 ** 416>>>  `

Related Course:
Python Programming Bootcamp: Go from zero to hero

## Funciones matemáticas

Python soporta una amplia variedad de funciones matemáticas.

## Instalar un IDE de Python

Un Entorno de escritorio integrado (IDE) es un software para la programación. Además de edición de texto simple que tienen todo tipo de funciones tales como resaltado de sintaxis, completado de código, pestañas, un explorador de la clase y muchos más.

Related Course:
Python Programming Bootcamp: Go from zero to hero

#### Python online intérpretes

Los intérpretes en línea no funcionen para todo pero funcionarán para la mayoría de los tutoriales para principiantes. Recomiendo usar un IDE desktop o el interprete oficial de Python.

Resumen de IDEs (sólo necesita uno)

Función Devuelve Ejemplo
ABS(x) Devuelve el valor absoluto de x. {% codeblock lang:python line_number:false %} x = -35 x = abs(x) Print (x) {% endcodeblock %}
CMP(x,y) Devuelve -1 Si x < y
Devuelve 0 si x es igual a y
Devuelve 1 Si x &gt; y.
{% codeblock lang:python line_number:false %} x = 6 y = 4 Imprimir (cmp(x,y)) {% endcodeblock %}
exp (x) Devuelve la exponencial de x {% codeblock lang:python line_number:false %} importación matemáticas x = 6 Imprimir (math.exp(x)) {% endcodeblock %}
Cienc El logaritmo natural de x {% codeblock lang:python line_number:false %} importación matemáticas x = 6 Imprimir (math.log(x)) {% endcodeblock %}
log10(x) El logaritmo en base 10 de x {% codeblock lang:python line_number:false %} importación matemáticas x = 6 Imprimir (math.log10(x)) {% endcodeblock %}
Pow(x,y) El resultado de x ** y {% codeblock lang:python line_number:false %} importación matemáticas x = 6 Imprimir (math.pow(x,2)) {% endcodeblock %}
sqrt(x) La raíz cuadrada de x {% codeblock lang:python line_number:false %} importación matemáticas x = 6 Imprimir (math.sqrt(x)) {% endcodeblock %}

## sl4a

Python scripts can be run on Android using the Scripting Layer For Android (SL4A) in combination with a Python interpreter for Android.

Related courses:
You may like:
Building Android Apps in Python Using Kivy

SL4A
The SL4A project makes scripting on Android possible, it supports many programming languages including Python, Perl, Lua, BeanShell, JavaScript, JRuby and shell. The SL4A project has a lot of contributors from Google but it is not an official Google project.

Scripts can access Android specific features such as calling, text message (SMS), take picture, text to speech, bluetooth and many more.

In this article you will learn how to run Python on Android devices using SL4A.

#### SL4A is designed for developers

Keep in mind that SL4A is designed for developers and in alpha quality software.

## Install SL4A

First enable installation of programs from unknown sources. By default Android devices can only install apps from the Google Play Store.

You have to enable the permission ‘Install from Unknown Sources’, by going to Settings -> Security -> Unknown Sources and tap the box.

After you have have updated these settings donwload the SL4A APK. Visit https://github.com/kuri65536/sl4a on your Android device and download the SL4A APK (or use the QR code on the right).

## Install Python 3 for Android

Install the Py4A app. The Python for Android app is built to run solely on

Android devices. You should use this app together with SL4A.

You can pick any version of Py4A, but bare in mind the supported version on Android:

• Python 2 requires Android Device >= 1.6

• Python 3 requires Android Device >= 2.3.1

The git repository is: https://github.com/kuri65536/python-for-android/releases

You could also use the QR code on the right using a QR scanner on your Android device.

Once Py4A is installed, start the app and press install. This will install the Python interpreter.

## SL4A

Open SL4A again. Many scripts will appear (in a list). You can now run Python scripts on your Android Device!

Press on a program such as speak.py A little popup will be shown. Pressing on the terminal icon will start the Python script.

The third button (the pencil) will open an editor. This is not a full blown IDE but a simple editor.
It doesn’t have syntax highlighting.

## Scripting on Android

You may prefer your favorite Python editor whatever it may be (vim/emacs fans here? PyCharm? Atom?)
All scripts are stored in /sl4a/scripts/

#### Note: File extension

If you installed the Python 3 interpreter, the programs will show with a .py3 extension instead of a .py extension.

A simple program (Spaceship Launch):

IDE Autor Plataforma Descripción Precio Descargar
PyCharm JetBrains Windows, Mac OS X, Linux/UNIX Python IDE. Características como: completación de código, inspecciones de código, error sobre la marcha destacando y soluciones rápidas 89 € / 1er año. (\$ 97,90) Descarga PyCharm
Átomo (+ script plugin) GitHub Windows, Mac OS X, Linux/UNIX Python IDE. Necesita descargar el plugin de secuencia de comandos después de instalar el átomo. Gratis. Descargar Atom.
Pythonista OMZ:software Apple iOS (iPhone, iPad) Las características incluyen: resaltado de sintaxis, completado de código, sistema interactivo, módulos estándar y de iOS. € 9. (\$ 9,90) Descargar Pythonista.
Eclipse con PyDev Aleks Totic Windows, Mac OS X, Linux/UNIX Las características incluyen: sintaxis resaltado, refactorización de código, depuración gráfica y mucho más. Gratis Descargar
Eric Python IDE Detlev Offenbach Windows, Linux/UNIX Las características incluyen: resaltado de sintaxis, autocompletado, clase navegador y más. Gratis Descargar
Wing IDE Wingware Windows, Mac OS X, Linux/UNIX Características: Sintaxis resaltado, auto-completado, refactorización, pruebas unitarias y versión controlan. \$45 a \$245 por usuario por licencia. Descargar
Komodo IDE Komodo Windows, Mac OS X, Linux/UNIX Características: Sintaxis, navegador de documentación, ejecutar código en línea, marcadores rápidos y mucho más. € 40 a € 223. (\$99 a \$295). Descargar
Repl.it Amjad Masad, Haya Odeh, Faris Masad y Max Shawabkeh. Web Intérprete de Python Gratis Ejecutar en línea
Ideone Ideone Web Intérprete de Python Gratis Ejecutar en línea
CodePad Hazel de Steven Web Intérprete de Python Gratis Ejecutar en línea
QR: Link to SL4A APK SL4A-Permissions QR Code Python 3 for Android Android Python 3 Install Python-On-Android SL4A-Python-Menu
 `"""TTS Rocket Launch."""__author__ = 'Frank <[email protected]>'import androiddroid = android.Android()message = "Python on Android"droid.ttsSpeak(message)for i in range(10,0,-1): droid.ttsSpeak(str(i))droid.ttsSpeak("We have lift off!")droid.ttsSpeak("rrrrrr")`

## python png

OpenCV (cv2) can be used to extract data from images and do operations on them. We demonstrate some examples of that below:

Related courses:

Image properties
We can extract the width, height and color depth using the code below:

Access pixel data
We can access the pixel data of an image directly using the matrix, example:

To iterate over all pixels in the image you can use:

Image manipulation
You can modify the pixels and pixel channels (r,g,b) directly. In the example below we remove one color channel:

To change the entire image, you’ll have to change all channels:   m[py][px][0], m[py][px][1], m[py][px][2].

Save image
You can save a modified image to the disk using:

## face detection python

In this tutorial you will learn how to apply face detection with Python. As input video we will use a Google Hangouts video. There are tons of Google Hangouts videos around the web and in these videos the face is usually large enough for the software to detect the faces.

Detection of faces is achieved using the OpenCV (Open Computer Vision) library. The most common face detection method is to extract cascades. This technique is known to work well with face detection. You need to have the cascade files (included in OpenCV) in the same directory as your program.

Related course
Master Computer Vision with OpenCV and Python

## Video with Python OpenCV

To analyse the input video we extract each frame.  Each frame is shown for a brief period of time. Start with this basic program:

Upon execution you will see the video played without sound. (OpenCV does not support sound). Inside the while loop we have every video frame inside the variable frame.

## Face detection with OpenCV

We will display a rectangle on top of the face. To avoid flickering of the rectangle, we will show it at it latest known position if the face is not detected.

In this program we simply assumed there is one face in the video screen. We reduced the size of the screen to speed up the processing time. This is fine in most cases because detection will work fine in lower resolutions.  If you want to execute the face detection in “real time”, keeping the computational cycle short is mandatory. An alternative to this implementation is to process first and display later.

A limitation of this technique is that it does not always detect faces and faces that are very small or occluded may not be detected. It may show false positives such as a bag detected as face.  This technique works quite well on certain type of input videos.

## word cloud python

word cloud based on gmail

We have created a python program that generates a wordcloud based on your gmail account. The output may look something like this depending on the contents of your emails.

First you will need a small script that interacts with the gmail service. We have created a small script that interact with gmail. It relies on gmaillib installed and you will need to set: allow “less-secure” applications to access gmail server: https://www.google.com/settings/security/lesssecureapps

Related Course:
Python Programming Bootcamp: Go from zero to hero

Gmail example:

If this script runs successfully you have almost all requirements installed. You will also need the library called wordcloud. We rebuild the system such that we get one long string containing the message bodies, which we feed as input to the wordcloud instance. The variable amount contains the number of mails to fetch. We have set it to 100 but you could set it to all messages using get_inbox_count() or you could simply fetch all emails of the last week.

Final program: