Focus Stacking automated with Linux

June 1, 2014 Posted by José Juan Escudero

 Focus Stacking is a digital image processing technique which combines multiple images taken at different focus distances to give a resulting image with a greater depth of field  than any of the individual source images. Focus stacking can be used in any situation where individual images have a very shallow depth of field, is especially used in extreme macro photography. There are two basic ways to make this technique, change the focus or change the distance to the subject.  In this article, I not explain the technique, in Internet have a lot of great explains of this technique, for example the Pat David article that inspire me to write this article.

In this case we will change the focus, which is not the best option but if it does not require large investments to automate. This article has two parts, the first capture the images and the second the processing.

I. Automated capture

For the first part we use DslrDashboard, is a software for remote control or our camera in Android, actually is multiplatform (Linux, Windows y mac). Allows the control by USB port or by wifi, this last with the NIKON wifi modules, or connected to a server with installed DslrDashboard, for example a old mobile, a raspberry pi or a router with OpenWRT firmware installed, or a specific module like the Total Remoto MK-1

For advanced use, and better explains of all the features, I recommed read the Instant Guide to DSLR Dashboard by Dmitr Popov


  • A devices with DslrDashboard
  • A camera supported by DslrDashboard(Nikon y Canon have a lot of models supported)
  • A tripod

To start, connect the camera to the device, in my case I use my tablet with usb otg, select the closet focus point and hit the Autofocus button. Now we have to see how many steps we need to focus, so we use manual focus controls on the bottom of the Live View.

Live view

Live view

The arrows buttons on the bottom side, the double go to the end and the simple move the focus ring the number of defined steps, these are indicated by the number  between controls and can be varied with the attached slider.

Depends of your lens, the number of steps change, you select a round number, not too small and changes the focus with the simple arrow until you see with the far side focused. Each time you press the button is a shot to make with the selected focus step. If you appreciate the images not have the correct dof reduce the focus step.

Focus stacking parameters

Focus stacking parameters

With these numbers in mind, reset the focus, and then press the button for focus stacking, enter the number of shots to be taken (the number of keystrokes that realizasteis before) and the focus step selected. Select direction according to how you made the initial focus and hit the start button. The camera started working and the display will indicate the number of photography that is performing. Once the process is complete the software will return to its initial position.

Clossing focus

Clossing focus

No limit focus

No limit focus

With this, we are ending the capture, upload the images to a directory in you computer to start the next part.

II. Process automatization

To make focus stacking exist specialized software like Zere Stacker, probably the best, but not is open source  (for testing exist a trial version for 30 days), so the best way to do this with open source software is used enfuse, a wonderful piece of software that has multiple uses, the best is review the documentation for see the possibilities. The articles of Edu Perez y Patrick David have a good explain in the use of enfuse for focus stacking.

As the complete process can be tedious, requiring several steps and they are slow, I decided to automate with script to perform the entire process transparently. The script makes the raw revealed, the alignment and the fusion of images.


  • Dcraw for the raw process
  • Hugin for align the images
  • Enfuse for fusion the images


Copy the file in the bin directory of the user home and assign the execution permission with  chmod +x


The scrip need all

The script requires that the images are all the same type, it supports jpg or raw files, are processed in a directory and is need they does not contain any other files. The process will create two directories, tmp for store the process files to make the stacking and  out  for save the output image, the process files and the output image are TIFF of 16 bit to maintain the highest quality. To run it,  just execute in the directory of images to be processed this command .


  • -a Align images (Optional, but recomended )
  • -q Quiet
  • -h Display the help
  • -d Parameters for process with dcraw, quoted the parameters. “-4 -T” is required for Tiff. By default use “-4 -T -w -p embed” .
  • -w  “Contrast Window Size” for enfuse
  • -e “Contrast Edge Scale” for enfuse
  • -g “Gray proyector” for enfuse

A good starting point  to adjust the result is to read David Pat’s article, which explains how these parameters work.

For example I using this parameters in the sample process: -a -g l-star -e 0.3 .

Result processed

Result processed


Download “Focus Stacking Script” – Downloaded 42 times – 4 kB


CBT Service Menu 1.4 lanzado

January 7, 2012 Posted by José Juan Escudero

A new version of Comic Book Transformer Service Menu is available for download.New Features in this version:

  • Compress files without the directory structure
  •  New profiles:
  • Android Tablet: 800×1280
  • Kindle DXG: 824×1200
  • Crop Double pages in single pages, if possible to control in the script
  • Fix bug with spaces in directory name for scale options (more…)
  • Linux embebido

    September 25, 2011 Posted by José Juan Escudero

    I write this article because all the statistics i see about the use of operating systems never see reality. All the statistics say that the desktop is used very little, I don’t know how obtained this data, but it seems a very low percentage for what I see daily. In  server is in first place, thanks to Internet servers and infrastructure servers in enterprise environments. In mobile environment dominates the market with Android, but there are other alternative like WebOS or maemo/ meego, badly exploited by the manufacturers.
    But I never see the number of devices containing Linux over other systems, in this case the difference would be overwhelming, virtually everyone with access to electronic devices using Linux in their daily lives. If I look around, I can see a TV, a router. a PVR and a A/V Receviver using linux. Virtually any electronic device that uses the network or have to process audio or video using an embedded linux.

    Most manufacturers do not usually advertise, but you can know perfectly well that all tend to attach a copy of the GPL with their manuals. It is curious that this does not publish more so, even in wikipedia only talk about phones, as this means that virtually everyone uses Linux in their daily lives and therefore the use of Linux is far superior to any other system operating on the planet.

    The good thing is that users do not have problems and advanced users can make changes, in some cases even with the consent of the manufacturer, to increase the functionality of the device to achieve functionality that are only available on new devices, so reducing named “planned obsolescence” and make much better her investment.

    So if linux will work perfectly in your living room, why not prove that you work on your pc ? and abandon once and systems that limit you and force you to do what you require and not what you want.


    CBT Service Menu 1.3.0 disponible

    February 20, 2011 Posted by José Juan Escudero

    A new version of Comic Book Transformer Service Menu is available for download.

    New Features in this version:

    • CB7 full support. Require the p7zip package.
    • Custom scaled for comic.


    Download “Comic book Transformer Service Menu V1.3.0” cbt_servicemenu_1.3.0.tar.gz – Downloaded 113 times – 2 kB

    New Version of CBT Service Menu

    February 12, 2011 Posted by José Juan Escudero

    A new Version of the Comic Book Transformer Service Menu for KDE is avaible now. This version fixes several bugs and included the following new features:

    • Progressbar for multi files transform
    • Convert pdf to CBR and CBZ
    • Scale for tablets 600 x 1024

    For more information see the original post


    Download “Comic book Transformer Service Menu V1.3” cbt_servicemenu_1.2.0.tar.gz – Downloaded 281 times – 2 kB

    Comic Book Transformer KDE Service Menu

    August 28, 2010 Posted by José Juan Escudero

    This KDE4 Service Menu is designed to make more easy the generation of Comic Book files in CBR, CBZ or PDF Formats. Provide options to scale to different resolutions and transform to gray for use in ebooks.


    • Convert Images directories to CBR, CBZ o PDF files
    • Convert  CBR o CBZ files in  PDF
    • Transform to gray scale
    • Scale to 1024×768 or 800×600


    In Dolphin select a directory or CBR, CBZ file, in actions menu select Comic Book Transformer. In the new menu select the output format for your file.

    Menu of Comic Book Transformer

    In you need transformation options, select the item ending in [...options] for your output type.

    Options for The transformation

    Select the type of the output transformation an press Accept. A dialog  inform you with the result of the transformation.


    Install this packages

    • Zip
    • Unzip
    • Rar
    • Unrar
    • ImageMagick


    Untar the file

    Home installation:

    - place the desktop files in $(kde4-config –localprefix)/share/kde4/services/ServiceMenus/
    - place the cb_servicemenu script file in a directory in your path (I have ~/bin)

    System-wide installation:

    - place the desktop files in $(kde4-config –prefix)/share/kde4/services/ServiceMenus/
    - place the cb_servicemenu script file in /usr/bin/ or /usr/local/bin/


    Last version

    Versiones anteriores


    Generador de documentación en formato DITA

    August 7, 2010 Posted by José Juan Escudero

    This project is intended to generate documentation of standard models in the DITA output format. There are currently no open source tools to facilitate this work and that’s the main reason for initiating this project.

    The choice of DITA as the output format is due to its flexibility as it is designed for generating technical documentation, because this is simpler than docbook and is better suited to my goals.

    The project consists in a library to make more easy the creation of documents XML.This library is based in JDOM XML.

    For the generation be made independent modules for each type of element to generate. These modules will eclipse plugins that will run the creation of the documentation from the IDE. The modules are designed to develop at the moment are:

    • DataBase
    • XSD – XML Schema

    Links of the project

    DITA XML Editors

    DITA Links

    Mi Flickr

    July 3, 2010 Posted by José Juan Escudero


    Jardin Japones en Toulouse

    July 3, 2010 Posted by José Juan Escudero

    [nggallery id=2]

    Configurando Mythtv Backend

    November 25, 2008 Posted by José Juan Escudero

    Bueno, pues comenzamos… ahora sabremos si todos los pasos previos estan bien realizados.

    Antes de empezar, seria conveniente que comprobasemos que el equipo detecta correctamente nuestra tarjeta de television TDT. Hay dos maneras, la primera seria tan sencillo como ir a Yast2–>Hardware–>TV Card. Si todo ha ido bien, al abrir “TV Card” os tiene que aparecer la tarjeta de video auto detectada por el sistema. Podeis pulsar el boton edit para apuntar algunos parametros que pueden sernos utilies en la configuracion de mythtv.

    Os aparecerá la tarjeta detectada, si pulsais siguiente, os aparecerá la tarjeta de sonido a la cual queremos conectarla, en el siguiete cuadro os aparecera LIRC. LIRC es el módulo que os ayudara a manejar Mythtv con vuestro mando a distancia y ya os adelanto que esta tarea es un autentico infierno!!!!. Fijáos en la lineas que aparenen al final de la configuracion en la parte inferior…

    Un último paso que os recomiendo antes de empezar, es que en la carpeta home del usuario que gestionará mythtv (en mi caso el usuario tambien se llama mythtv), creeis varias carpetas para ordenarlo un poco (ej: video, fotos, storage etz)

    Bueno, comenzamos con el mythtv.

    Desde el entorno gráfico poder poner en buscar ” mythtv” y os apareceran varios resultados, ejecuraremos “mythtv setup”. Para ejecutar este comando, tendremos que estar seguros de que el servicio mythbackend está detenido. Para ello desde la linea de comandos:

    cd /etc/init.d

    ./mythbackend status

    y tiene que mostrar el servicio como unused

    Visto esto, ya podemos empezar, bien ejecutando “mythtv setup” desde el entorno gráfico ó desde la linea de comandos con el comando “mythtvsetup”

    Es normal que tras ejecutar este comando por primera vez, tarde un poco, no os preocupeis!

    Os aparecerá un menu numerado con seis opciones. La verdad es que la configuración será intuitiva y tendremos que recorrer los numeros uno a uno.

    Empezamos con el primero “GENERAL”

    1. El primer cuadro os mostrara la ip de vuestro servidor, posiblemente con, aqui no es conveniente tocar nada
    2. El segundo cuadro hace referencia a la zona en la que se va a utilizar mythtv, tendremos que cambiar el formato de tv por “PAL-BG” y el formato de VBI por PAL teletex (aunque la verdad es que yo no utilizo esto. La tabla de transferencia de canales la tendremos que poner en “europe-west”.De momento pondremos el xmltv en none.
    3. El tercer cuadro tiene poco que configurar, quizá sea interesante marcar el cuadro que empieza por “Delate files…” si tenemos un sistema muy lento…(un disco duro ide y una maquina corta Ej: un pIII 1GHz), auque tampoco pasa nada si no lo marcamos, lo único que hay que tener en cuenta es que cuando borre archivos de grabacion grandes, la cosa no es inmediata….
    4. El cuarto cuadro lo dejamos tal cual
    5. El quinto tambien lo podemos dejar tal cual para una configuracion basica.. (prestar atencion al comando sudo para apagar el equipo… teneis que dale permiso al usuario mythtv para apagra el equipo…)
    6. El sexto cuadro si quereis tambien lo podeis dejar tal cual… se utiliza para lanzar un paquete y despertar a otros equipos, pero en un entorno sencillito no nos vale
    7. Del septimo cuadro hay tres puntos que nos pueden resultar interesantes:
    • La primera es el uso de CPU.Si nuestro equipo no es muy allá, seria recomendable ponerlo en bajo, si nos sobra maquina, podremos modificar este valor
    • Permitir deteccion de anuncio: Yo no he logrado que esto funcione bien, y creo que en españa es dificil, por que las cadenas emplean muchas tecnicas para evitarlo, pero… no esta de mas ponerlo
    • Permitir tareas de recodificacion: Esto nos permitira recomprimir los videos grabados para que ocupen menos espacione nuestro disco, hay que marcarlo.

    Los dos cuadros restantes, los podemos dejar tal cual de momento.

    La segunda pestaña es “CAPTURADORAS”

    Tras pulsarla, lo primero que nos aparecerá es (nueva capturadora)

    Pulsamos intro y nos aparece un cuadro con informacion varia. Lo primero que tendremos que hacer es serleccionar el tipo de tarjeta: En nuestro caso “capturadora DVB DTV (v3.X)

    Los valores que muestra suelen ser válidos, pero yo suelo cambiar el parametro “time out Señal (mseg)” por 1500, para que a la hora de buscar canales, se tome su tiempo.

    Cuando ya lo tengamos, pulsamos terminar, aparecera una nueva entrada [dvb:0] , pulsamos esc para ir a menu principal

    La tercera pestaña es “FUENTES DE VIDEO”

    Al igual que en el paso anterior, nos aparece un menú de creación, pero en este caso de fuente de video

    Rellenamos el cambo del nombre con uno que nos inventemos, por ejemplo DVB y en listenings grabbers, ponemos “Transmitted guide only EIT”. En tabla de frecuencias ponemos otra vez “europe-west” y terminamos.

    La siguiente opcion es “CONEXIONES”

    Aqui enlazará las configuraciones que hemos realizado previamente, entramos en la que nos muestra por defecto.

    Le asignamos un nombre (ej: TDT), en fuente de video, le ponemos la creada previamente DVB. Ahora podremos ir a “buscar canales”. En la siguiente pestaña simplemente tendremos que cambiar el pais por el nuestr, españa y a buscar canales!!! no os olvideis de tener conectado el cable de antena!.

    Con los canales detectados, podemos pulsar siguiente y sin cambiar nada, terminar.

    La opcion quinta es opcional “EDITOR DE CANALES”

    Esta opcion es muy intuitiva y no voy a hablar de ella, simplemente decir que lo que mas me gusta es “icon download”

    Última opcion “STORAGE DIRECTORIES”

    Antes de finalezar tendremos que crear un directorio de almacenamiento por defecto. Entramos en la opcion storage directories y veremos varias opciones

    Create LiveTV group– grupo de almacenamiento para programas livetv guardados, segun ponemos la tele, mythtv se pone a grabar, con este grupo le podemos poner una ubicacion especifica

    Create DB Backup Group — CREO que es una ubicacion para almacenar la base de datos de Mythtv

    Bueno, nosotros entraremos en la opcion “por defecto”, y le daremos a “add directory”

    Nos aparece un cuadro en el que tenemos que introducir una ruta, en mi caso sera la de una carpeta que ya me he creado previamente en /home/mythtv/storage

    Y ya hemos terminado!!! Al salir nos avisa de una tarea que tenemos que realizar!, y es ejecutar mythfilldatabase, no olvideis hacerlo. Yo lo hago antes y despues de arrancar el backend…

    Bueno, pues arrancamos el backend y lo dejamos listo para que arranque en reinicio:

    yast2–>System–>system services y arrancar el servicio mythbackend.

    Si todo ha ido bien, ahora podemos ejecutar el “mythtv frontend”, lo podemos buscar directamente desde el entorno grafico.