No Description

arrays-GreenScreen.md 35KB

English | Español

Arreglos - Pantalla Verde

main1.png main2.png main3.png

Los arreglos de datos (arrays) nos facilitan guardar y trabajar con grupos de datos del mismo tipo. Los datos se guardan en espacios de memoria consecutivos a los que se puede acceder utilizando el nombre del arreglo e índices o suscritos que indican la posición en que se encuentra el dato. Las estructuras de repetición nos proveen una manera simple de acceder a los datos de un arreglo. En la experiencia de laboratorio de hoy practicarás el uso de ciclos anidados en la manipulación de arreglos bi-dimensionales usando técnicas de “pantalla verde”.

Objetivos:

  1. Practicar el acceso y manipulación de datos en un arreglo.

  2. Aplicar ciclos anidados para implementar técnicas de “pantalla verde”.

  3. Utilizar expresiones aritméticas y estructuras de selección para transformar colores de píxeles.

  4. Acceder píxeles en una imagen y descomponerlos en sus componentes rojo, azul y verde.

Pre-Lab:

Antes de llegar al laboratorio debes:

  1. Haber repasado los conceptos básicos relacionados a estructuras de repetición, ciclos anidados y arreglos bi-dimensionales.

  2. Conocer los métodos básicos de QImage para manipular los pixeles de las imágenes.

  3. Haber estudiado los conceptos e instrucciones para la sesión de laboratorio.

  4. Haber tomado el quiz Pre-Lab que se encuentra en Moodle.



Tecnología de pantalla verde (“Green Screen”)

En esta experiencia de laboratorio, aprenderás los conceptos y destrezas básicas de la tecnología de pantalla verde que se usa en boletines informativos de televisión, películas, juegos de video y otros. La composición de pantalla verde, o composición cromática, es una técnica que se usa para combinar dos imágenes o cuadros de video [1]. Esta técnica de post-producción crea efectos especiales al componer dos imágenes o transmisiones de video sustituyendo el área de un color sólido por otra imágen [2]. La composición cromática se puede hacer con imágenes de objetos sobre fondos de cualquier color que sean uniformes y diferentes a los de la imagen. Los fondos azules y verdes son los que se usan con más frecuencia porque se distinguen con más facilidad de los tonos de la mayoría de los colores de piel humanos.

Para esta experiencia de laboratorio te proveemos un interfaz gráfico (GUI) simple que permite al usuario cargar una imagen con un objeto sobre un fondo de color sólido (preferiblemente azul o verde) y una imagen para sustituir el fondo. Tu tarea es crear e implementar una función que cree una tercera imagen compuesta en la cual, a la imagen del objeto con el fondo de color sólido se le removerá el color de fondo y el objeto aparecerá sobre la imagen que será el nuevo fondo. La Figura 1 muestra un ejemplo de los resultados esperados.


figure1.png

Figura 1. Ejemplo de los resultados esperados. El objeto de interés es la mano con las gafas.


Con el propósito de ilustrar el procedimiento, llamemos la imagen del objeto con el fondo de color sólido imagen A, y supongamos que el color sólido en el fondo tiene un “RGB” 0x00ff00 (verde puro). Llamemos imagen B a la imagen que usaremos para el fondo, un fondo que resulte interesante. Para este ejemplo, supongamos también que los tamaños de ambas imágenes son iguales (mismo ancho y alto).

Para producir la imagen compuesta (imagen C), podríamos comenzar copiando toda la imagen B que usaremos de fondo a la imagen C. Luego, para insertar solo el objeto que nos interesa en la imagen compuesta podemos recorrer la imagen A píxel por píxel. Compararíamos el color de cada píxel p en la imagen A con el color de fondo 0x00ff00. Si son similares, el píxel de la imagen A corresponde al color sólido de fondo y dejamos el píxel de la imagen C como está (el fondo nuevo). Si el color de p no es similar a 0x00ff00, modificamos el píxel correspondiente en la imagen C, copiando el color del píxel del objeto a la imagen compuesta. Esto se ilustra en la Figura 2.


figure2.png

Figura 2. Ilustración de cómo el algoritmo decide cuáles píxeles de la imagen A incluir en la imagen C.



Píxeles

Al elemento más pequeño de una imagen se le llama un píxel. Esta unidad consiste de un solo color. Como cada color es una combinación de tonalidades de los colores primarios rojo, verde y azul, se codifica como un entero sin signo cuyos bytes representan los tonos de rojo, verde y azul del pixel (Figura 3). A esta combinación se le llama el RGB del color por las siglas de “Red-Green-Blue”. Por ejemplo un píxel de color rojo (puro) tiene una representación RGB 0x00ff0000, mientras que un píxel de color blanco tiene una representación RGB de 0x00FFFFFF (ya que el color blanco es la combinación de los tonos rojo, verde y azul en toda su intensidad).


figure3.png

Figura 3. Distribución de bits para las tonalidades de rojo, verde y azul dentro de la representación RGB. Cada tonalidad puede tener valores entre 0x00 (los ocho bits en 0) y 0xFF (los 8 bits en 1).


En Qt se utiliza el tipo QRgb para representar valores RGB. Utilizando ciertas funciones que describimos abajo podemos obtener los componentes rojo, verde y azul del valor QRgb del píxel y así manipular imágenes.

Biblioteca

La experiencia de laboratorio de hoy utilizará la clase QImage. Esta clase permite acceder a los datos de los pixeles de una imagen para poder manipularla. La documentación de la clase QImage se encuentra en http://doc.qt.io/qt-4.8/qimage.html.

El código que te proveemos contiene los siguiente objetos de la clase QImage:

  • originalImage // contiene la información de la imagen original que vas a editar
  • editedImage // contendrá la imagen editada

Los objetos de clase QImage tienen los siguiente métodos que serán útiles para la experiencia de laboratorio de hoy:

  • width() // devuelve el valor entero del ancho de la imagen
  • height() // devuelve el valor entero de la altura de la imagen
  • pixel(i, j) // devuelve el QRgb del píxel en la posición (i,j)
  • setPixel(i,j, pixel) // modifica el valor del píxel en la posición (i, j) al valor píxel QRgb

Las siguientes funciones son útiles para trabajar con datos de tipo QRgb:

  • qRed(pixel) // devuelve el tono del color rojo del píxel
  • qGreen(pixel) // devuelve el tono del color verde del píxel
  • qBlue(pixel) // devuelve el tono del color azul del píxel
  • qRgb(int red, int green, int blue) // devuelve un píxel QRgb compuesto de los valores de rojo, verde y azul recibidos.

Ejemplos:

  1. QRgb myRgb = qRgb(0xff, 0x00, 0xff);: Asigna a myRgb el valor 0xff00ff que representa el color figure4.png

    Nota que el valor 0xff00ff representa los valores 0xff, 0x0, 0xff, que corresponden a los componentes rojo, verde y azul de myRgb.

  2. Si la siguiente imagen 4 x 4 de píxeles representa el objeto originalImage,

    ejemplo.png

entonces originalImage.pixel(2,1) devuelve un valor rgb que representa el color azul (0x0000ff).

  1. La siguiente instrucción asigna el color rojo al píxel en posición (2,3) en la imagen editada:

editedImage.setPixel(2,3,qRgb(0xff,0x00,0x00));.

  1. La siguiente instrucción le asigna a greenContent el valor del tono de verde que contiene el pixel (1,1) de originalImage:

int greenContent = qGreen(originalImage.pixel(1,1));.

  1. El siguiente programa crea un objeto de clase QImage e imprime los componentes rojo, verde y azul del pixel en el centro de la imagen. La imagen utilizada es la que se especifica dentro del paréntesis durante la creación del objeto, esto es, el archivo chuck.png.

#include <QImage>
#include <iostream>

using namespace std;
int main() {
    QImage myImage(“/Users/rarce/Downloads/chuck.png”);
    QRgb    centralPixel;

    centralPixel = myImage.pixel(myImage.width() / 2, myImage.height() / 2);

    cout    << hex;

    cout    << “Los componentes rojo, verde y azul del pixel central son: “
        << qRed(centralPixel) << “, “
        << qGreen(centralPixel) << “, “
        << qBlue(centralPixel) << endl;
    return 0;
}

Midiendo la similaridad de los colores de los pixeles

Observa la Figura 4 abajo. Aunque el fondo en la imagen A parece uniforme, realmente incluye píxeles de diferentes colores (aunque parecidos).


figure5.png

Figura 4. Lo que puede parecer un color sólido, realmente no lo es.


Por esto, en lugar de solo considerar como parte del fondo sólido los píxeles cuyo color es exactamente 0x00FF00, medimos la distancia del valor del color del píxel al valor del color puro. Una distancia pequeña significa que el color es casi verde puro. La ecuación para la distancia es:

$$distancia = \sqrt{(P_R-S_R)^2+(P_G-S_G)^2+(P_B-S_B)^2},$$

donde $$P_R, P_G, P_B$$ son los valores de los componentes rojo, verde y azul del píxel bajo consideración, y $$S_R, S_G, S_B$$ son los valores de los componentes rojo, verde y azul del fondo sólido. En nuestro ejemplo, $$S_R=S_B=0$$ y $$S_G=255$$.



Sesión de laboratorio:

En el laboratorio de hoy, comenzando con una imagen con un objeto de interés sobre un fondo de color sólido y una imagen para utilizar como fondo, definirás e implantarás una función que cree una tercera imagen compuesta en la cual, a la imagen del objeto de interés se le removerá el color de fondo y aparecerá sobre la imagen para el fondo.

Estarás trabajando con el archivo Filter.cpp. Lo que sigue es un resumen de las variables en este archivo.

  • objectImage: referencia a la imagen del objeto de interés y fondo sólido
  • backgroundImage: referencia a la imagen para el fondo
  • mergedImage: referencia a la imagen compuesta
  • threshold: valor umbral usado para comparar las distancias entre el valor del color del píxel de la imagen con el objeto sobre fondo sólido. En el código que se provee, el valor del umbral se lee del valor de la barra deslizable.
  • ghost: valor Booleano utilizado para aplicar el filtro “fantasma” a los pixeles.
  • (x, y): coordenadas de un pixel de la imagen del objeto sobre fondo sólido. El valor por defecto es (0,0).
  • (offset_x, offset_y): coordenadas de la imagen compuesta en donde la esquina superior izquierda de la imagen del objeto sobre fondo sólido será insertada. El valor por defecto es (0,0).

Ejercicio 1: Crear imagen compuesta

Instrucciones

  1. Carga a QtCreator el proyecto GreenScreen haciendo doble “click” en el archivo GreenScreen.pro en el directorio Documents/eip/Arrays-GreenScreen de tu computadora. También puedes ir a http://bitbucket.org/eip-uprrp/arrays-greenscreen para descargar la carpeta Arrays-GreenScreen a tu computadora.

  2. Compila y corre el programa. El código que te proveemos crea la interfaz de la Figura 5. Los botones Select Image y Select Background Image ya han sido programados.


    figure6.png

    Figura 5. Interfaz de la aplicación GreenScreen.


  3. Marca el botón para cargar una imagen del objeto de interés sobre fondo sólido, luego marca el botón para seleccionar la imagen para el fondo. El directorio con los archivos fuente contiene una carpeta llamada landscapes que contiene imágenes de fondo, y una carpeta llamada green_background que contiene imágenes de objetos sobre fondo de color sólido.

  4. Tu primera tarea es completar la función MergeImages en el archivo Filter.cpp. La función MergeImages se invoca cuando el usuario marca el botón Merge Images y cuando se desliza la barra. La función MergeImages recibe las referencias a la imagen con objeto de interés y fondo sólido, la imagen para el fondo y la imagen compuesta, un valor umbral, las coordenadas (x,y) de un píxel de la imagen del objeto sobre fondo sólido, y las coordenadas (offset_x, offset_y) de la imagen compuesta.

Para este ejercicio puedes ignorar el filtro “fantasma” ghost y las coordenadas (offset_x, offset_y), y solo componer la imagen con el objeto de interés en la imagen de fondo, comenzando en la posición (0,0).

Algoritmo

  1. Adquiere el valor del color sólido. El color sólido será el color del píxel en la posición (x,y) en la imagen del objeto sobre fondo sólido. El valor por defecto para (x,y) es (0,0).

  2. Para todas las posiciones (i,j), adquiere el valor del color del píxel en la posición (i,j) de la imagen con el objeto. Computa la distancia entre el color de la imagen con el objeto y el valor del color sólido. Si la distancia entre el color sólido y el color del píxel de la imagen es mayor que que el valor umbral, cambia el valor del color del píxel en la posición (i,j) de la imagen de fondo al valor del color de la imagen con el objeto.

Prueba tu implantación cargando imágenes de objetos e imágenes para el fondo y verificando la imagen compuesta.

Ejercicio 2: Crear imagen compuesta usando filtro ghost

En este ejercicio modificarás el Ejercicio 1 para aplicar el filtro fantasma a cada uno de los píxeles que se compondrán sobre la imagen de fondo en el caso de que la variable ghost sea cierta. El filtro fantasma creará el efecto de que el objeto en la imagen compuesta se verá como un “fantasma” sobre la imagen de fondo, como en la Figura 6.


figure7.png

Figura 6. Imagen con filtro fantasma. En este ejemplo, el perro en la imagen con el fondo sólido se compone sobre la imagen de fondo utilizando el filtro fantasma.


El efecto fantasma se consigue promediando el valor del color del píxel del fondo con el valor del color del píxel correspondiente del objeto, en lugar de solo reemplazar el valor del color del píxel del fondo por el del objeto. Calculamos el promedio de cada uno de los componentes (rojo, verde y azul)

$$N_R=\frac{S_R+B_R}{2}$$ $$N_G=\frac{S_G+B_G}{2}$$ $$N_B=\frac{S_B+B_B}{2},$$

en donde $$N_R, N_G, N_B$$ son los componentes rojo, verde y azul del nuevo píxel fantasma, $$S_R, S_G, S_B$$ son los componentes de la imagen del objeto, y $$B_R, B_G, B_B$$ son los componentes de la imagen de fondo.

Ejercicio 3: Crear imagen compuesta colocando el objeto en una posición específica

El “widget” que despliega el fondo fue programado para que detecte la posición marcada por el usuario. En este ejercicio programarás la función MergeImages para que el objeto sea desplegado en la posición marcada por el usuario en la imagen de fondo, en lugar de ser desplegado en la esquina superior izquierda. Las Figuras 7 y 8 muestran el efecto. Nota los valores de Selected Coord bajo la imagen del medio.


figure8.png

Figura 7. En este ejemplo, la imagen del fondo no ha sido marcada y Selected Coord tiene (0,0) que es su valor por defecto. El perro se inserta en la imagen compuesta con su esquina superior izquierda en el lugar (0,0).


figure9.png

Figura 8. En este ejemplo, la imagen del fondo fue marcada en las coordenadas (827,593). La imagen del perro se inserta en la imagen compuesta con su esquina superior izquierda en la posición (827,593).


Tu tarea en este ejercicio es la misma que en el Ejercicio 1, pero esta vez debes ajustar la imagen del objeto dentro de la composición con las cantidades especificadas en los parámetros x_offset y y_offset. Recuerda tomar en consideración los límites de la imagen compuesta cuando insertes el objeto; el usuario pudiera especificar unos parámetros que se salgan de los límites y el objeto se cortará, como sucede en la Figura 9.


figure10.png

Figura 9. En este ejemplo, el usuario seleccionó una posición que asignó valores muy grandes para x_offset y y_offset; la implementación hizo el ajuste para que parte de la imagen del perro saliera en la imagen compuesta.


El ejemplo de la Figura 10 muestra cómo se comportará la imagen del objeto al sobreponerla en la imagen que queremos de fondo. Las variables offset_x, offset_y representan el punto en la imagen de fondo en el que se colocará la esquina superior izquierda de la imagen del objeto. Nota que si se escoge un punto muy cerca del borde para la composición, parte de la imagen del objeto se sale de los límites de la imagen de fondo. Como hemos visto en la manipulación de arreglos, si se intenta acceder o alterar elementos que estan fuera del rango de tamaño del arreglo, al compilar occurre un error fatal. Lo mismo sucede con las imágenes.

Debes asegurarte de que tu implementación toma en cuenta los valores de offset x y offset y para que la composición no intente acceder o alterar píxeles fuera del límite de la imagen de fondo. Si intentas acceder o alterar píxeles fuera de esos límites, resulta en un error fatal.


figure11.png

Figura 10. Ilustración de la imagen del objeto de interés con píxeles que se salen de los límites de la imagen de fondo. Si no se toma en consideración esta posibilidad en la implementación, ocurrirá un error fatal.


Valida tu implantación seleccionando varios valores para el ajuste de “offset” y observando el efecto que tienen en la imagen compuesta. Asegúrate de tratar casos en los que tus valores para x_offset y y_offset ocasionarían que la imagen fuera cortada como ocurrió en la imagen compuesta de la Figura 9.



Entrega

Utiliza “Entrega” en Moodle para entregar el archivo filter.cpp que contiene la función MergeImages. Recuerda utilizar buenas prácticas de programación, incluir el nombre de los programadores y documentar tu programa.



Referencias

[1] http://en.wikipedia.org/wiki/Greenscreen(disambiguation)

[2] http://en.wikipedia.org/wiki/Chroma_key

[3] http://doc.qt.io/qt-4.8/qimage.html.




English | Español

Arrays - Green Screen

main1.png main2.png main3.png

Arrays help us to store and work with groups of data of the same type. The data is stored in consecutive memory spaces which can be accessed by using the name of the array and indexes or subscripts that indicate the position where the data is stored. Repetition structures provide us a simple way of accessing the data within an array. In this laboratory experience, you will be using nested loops to process bi-dimensional arrays and implement the functionality of a green-screen.

Objectives:

  1. Practice accessing and modifying elements in an array.

  2. Use nested loops to implement greens-screen techniques.

  3. Use arithmetic expressions and selection structures to transform pixel colors.

  4. Read pixels from an image and decompose them in their red, green and blue components.

Pre-Lab:

Before coming to the laboratory you should have:

  1. Reviewed the basic concepts about repetition structures, nested loops, and bi-dimensional arrays.

  2. Understood the methods of the QImage class for pixel manipulation.

  3. Studied the concepts and instructions for the laboratory session.

  4. Taken the Pre-Lab quiz that is found in Moodle.



Green-screen technology

In this laboratory experience the student will be exposed to the basics of the green screen technology used in newscasting, motion pictures, video games, and others. Green screen compositing, or more generally chroma key compositing, is a technique for combining two still images or video frames[1]. Chroma key compositing, or chroma keying, is a special effects / post-production technique for compositing (layering) two images or video streams together based on color hues (range)[2]. Chroma keying can be done with backgrounds of any color that are uniform and distinct, but green and blue backgrounds are more commonly used because they differ most distinctly in hue from most human skin colors.

With this laboratory we provide a simple GUI that allows the user to load an image with any solid background (although green or blue are preferred), and a background image. Your task is to implement a function that creates a third, merged image, in which the image with the solid background appears over the background image (with the solid background removed). Figure 1 shows an example of the expected results.


figure1.png

Figure 1: Example of the expected results. The object of interest is the hand carrying the sunglasses.


For illustration purposes, let’s call the image with the solid background image A and let’s say that the solid color in the background has an RGB 0x00ff00 (pure green). We will refer to the image with the interesting background as image B. Let’s also assume that both images are the same size (width and height).

To produce the merged image (image C), we could start by completely copying image B to *image C. Then, to insert only the object of interest into the merged image we could traverse image A pixel by pixel. We would compare the color of each pixel p in image A to the color 0x00FF00, if they are similar we do nothing (because it means that this pixel is part of the solid color background). If the color of p is not similar to 0x00FF00, we modify the corresponding pixel in image C, copying the color of the object’s pixel to the merged image.


figure2.png

Figure 2 - Illustration of how the algorithm decides which pixels to include from image A into image C.



Pixels

The smallest element in an image is called a pixel. This unit consists of a single color. Since each color is a combination of tones for the primary red, green and blue colors, it is coded as an unsigned integer whose bytes represent the tones of red, green and blue of the pixel (Figure 3). This combination is called the color’s RGB which is an acronym for “Red-Green-Blue”. For example, a pure red pixel has an RGB representation of 0x00ff0000, while a white pixel has an RGB representation of 0x00FFFFFF (since the color white is a combination of tones of red, green and blue in all of their intensity).


figure3.png

Figure 3. Bit distribution for the tones of red, green and blue in an RGB representation. Each tone can have values between 0x00 (the eight bits in 0) and (0xFF (the 8 bits in 1).


Qt uses the QRgb type to represent RGB values. Using certain functions that are described below we can obtains the red, green and blue components of the QRgb value of the pixel and manipulate the images.

Library

In today’s laboratory experience you will use the QImage class. This class permits access to the data in the pixels of an image to manipulate it. The documentation for the QImage class can be found in http://doc.qt.io/qt-4.8/qimage.html.

The code provided in this project contains the following objects of the QImage class:

  • originalImage // contains the information of the original image that you will edit
  • editedImage // will contain the edited image

The objects of the QImage class have the following methods that will be useful for today’s laboratory experience:

  • width() // returns the integer value for the image’s width
  • height() // returns the integer value for the image’s height
  • pixel(i, j) // returns the QRgb for the pixel in position (i,j)
  • setPixel(i,j, pixel) // modifies the value for the pixel in position (i,j) to the value of pixel QRgb

The following functions are useful to work with data of type QRgb:

  • qRed(pixel) // returns the tone for the pixel’s red color
  • qGreen(pixel) // returns the tone for the pixel’s green color
  • qBlue(pixel) // returns the tone for the pixel’s blue color
  • qRgb(int red, int green, int blue) // returns the QRgb pixel composed of the red, green and blue values received.

Examples:

  1. QRgb myRgb = qRgb(0xff, 0x00, 0xff);: Assigns the value 0xff00ff to myRgb which represents the color figure2.jpg

    Notice that the value 0xff00ff represents the values 0xff, 0x0, and 0xff, that correspond to the red, green and blue components in myRgb.

  2. If the following 4 x 4 image of pixels represents the object originalImage,

ejemplo.png

then originalImage.pixel(2,1) returns the rgb value that represents the color blue ( 0x0000ff).

  1. The following instruction assigns the color red to the pixel in position (2,3) in the edited image:

editedImage.setPixel(2,3,qRgb(0xff,0x00,0x00));.

  1. The following instruction assigns to greenContent the value of the green tone that is contained in the pixel (1,1) of originalImage:

    int greenContent = qGreen(originalImage.pixel(1,1));.

  2. The following program creates an object of the QImage class and prints the red, green and blue components of the pixel in the center of the image. The image used is the one specified within the parenthesis during the creation of the object, that is, the file chuck.png


#include <QImage>
#include <iostream>

using namespace std;
int main() {
    QImage myImage(“/Users/rarce/Downloads/chuck.png”);
    QRgb    centralPixel;

    centralPixel = myImage.pixel(myImage.width() / 2, myImage.height() / 2);

    cout    << hex;

    cout    << “The red, green and blue components of the middle pixel are: “
        << qRed(centralPixel) << “, “
        << qGreen(centralPixel) << “, “
        << qBlue(centralPixel) << endl;
    return 0;
}

Measuring similarity of pixel colors

Look at Figure 4, although the background in image A looks uniform, it really includes pixels of diverse (although similar) colors.


figure5.png

Figure 4 - What may seem as a solid color, really is not. Thus, we use the color distance.


Instead of only considering as part of the solid background the pixels whose color is exactly 0x00FF00, we measure a color’s distance from the pure color. A small distance means that the color is almost a pure green. A large distance means that the color is very different from green. The equation for distance is:

$$distance = \sqrt{(P_R-S_R)^2+(P_G-S_G)^2+(P_B-S_B)^2},$$

where $$P_R$$, $$P_G$$, and $$P_B$$ are the red, green and blue components of the pixel being considered. $$S_R$$, $$S_G$$, and $$S_B$$ are the components of the solid background, e.g. in our example $$S_R=S_B=0$$ y $$S_G=255$$.



Laboratory Session

In this laboratory experience, starting with an image with an object of interest over a solid color background and an image to use as a background, you will define and implement a function that creates a third merged image where the image with the object of interest will have its background color removed and will appear over the image chosen to be the background.

You will be working with the Filter.cpp file. The following is a review of the variables in this file:

  • objectImage: reference to the object image with the solid background
  • backgroundImage: reference to the background image object
  • mergedImage: reference to the merged image
  • threshold: is a theshold value used to compare the distances between the object pixel and the solid background pixel. In the provided code, the threshold value is read from the slideBar.
  • ghost: is a boolean value used to apply ghost filter to pixels.
  • (x, y): contains the coordinate of the pixel whose color will be used as solid background. The default value is (0,0).
  • (offset_x, offset_y): the coordinate of the merged image where the upper-left corner of the objectImage should be inserted. The default value is (0,0).

Exercise 1: Create a composite image

Instructions

  1. Load the Qt project called GreenScreenLab by double-clicking on the GreenScreenLab.pro file in the Documents/eip/Arrays-GreenScreen folder of your computer. You may also go to http://bitbucket.org/eip-uprrp/arrays-greenscreen to download the Arrays-GreenScreen folder to your computer.

  2. Build and run the program. The provided code creates the interface shown in Figure 5. The buttons Select Image and Select Background Image have already been programmed to perform their actions.


    figure6.png

    Figure 5.Interface for the green screen application.


  3. Click the Select Image button to load the image that contains the solid background, the click Select Background Image to load the image that contains the interesting background. The folders called green_background and landscapes contain some images that are suitable as the first and second images.

  4. Your first task is to complete the function MergeImages in file Filter.cpp.MergeImages is the function that is called when the user presses the button captioned Merge Images or when he slides the slide bar. The function MergeImages receives the image with the solid background, the background image, a reference to the merged image, a threshold value, and the coordinates (x,y) of the pixel from which we will extract the sample green background color, and the coordinates (offset_x, offset_y) from the merged image.

For this first exercise you can ignore the following parameters: ghost, x_offset, y_offset. Your implementation should place the objectImage into the mergedImage starting at position (0,0).

The algorithm

  1. Acquire the value of the solid color. The solid color will be the color of the pixel in the coordinate (x,y) of the object image with the solid background. The default value for (x,y) is (0,0).

  2. For every position (i,j), read the color of the corresponding pixel in the objectImage. Compute the distance of the pixel colors to the solid color. If the distance between the solid color and the color of the pixel of the image is greater than the threshold, set the corresponding (i,j) pixel in the merged image to the objectImage pixel color.

Test your implementation by loading object and background images and verifying the merged image.

Exercise 2: Creating a composite image using a ghost filter

In this exercise you will modify Exercise 1 to apply a ghost filter to each of the pixels that will be composed over the background image (if the ghost variable is true). The filter creates a ghost like effect on the objects composed over the background image, as in Figure 6.


figure7.png

Figure 6 - In this example, the dog in the image with the solid background is composed in the background image with the ghost filter.


The ghost effect is achieved by averaging the background color with the object’s color (instead of simply replacing the background with the object’s color). The average is performed for each of the components (red, green and blue).

$$N_R=\frac{S_R+B_R}{2}$$ $$N_G=\frac{S_G+B_G}{2}$$ $$N_B=\frac{S_B+B_B}{2},$$

where $$N_R$$, $$N_G$$, and $$N_B$$ are the red, green and blue components of the new ghost pixel. $$S_R$$, $$S_G$$, and $$S_B$$ are the components of the object image. $$B_R$$, $$B_G$$, $$B_B$$ are the components of the background image.

Exercise 3: Create a composite image placing the object in a specified position

The widget that displays the background has been programmed to register the position where the user clicks. In this exercise you will program the MergeImages function so that the position that user clicks in the background image is used as the top left corner where the object image will be displayed in the merged image. The following figures illustrates the effect. Note the Selected Coord values under the images.


figure8.png

Figure 7. In this example, the background image has not been clicked. Thus the “Selected Coord” is at its default value of (0,0). The dog image is inserted with its top-left corner at (0,0) in the merged image.


figure9.png

Figure 8. In this example, the background image has been clicked at coordinate (827,593). The dog image is inserted with its top-left corner at (827,593) in the merged image.


In this exercise your task will be the same as in Exercise 1, but this time you will need to offset the object image inside the merged image by the amount specified in the x_offset and y_offset parameters. Please take into consideration the merged image boundaries when you are inserting the object image. The user may specify an offset where the boundaries are exceeded and the object will be cut, as in Figure 9.


figure10.png

Figure 9. In this example, the user selected a position that assigned values that are too large for x_offset and y_offset; the implementation made the adjustment so part of the dog appeared in the merged image.


The example in Figure 10 shows how the object image will behave when merging it with the background image. The x_offset and y_offset variables represent the point in the background image where the upper left corner of the object image will be placed. Notice that if a point too close to the image border is chosen, part of the object image will be outside of the limits of the background image. As we have seen when manipulating arrays, if one tries to access or alter elements that are outside of the size range of the array, we get a fatal compilation error. The same thing happens with the images.

You should make sure that your implementation takes into account the x_offset and y_offset values so the composition does not try to access or alter pixels outside of the limits of the background image. If you try to access or alter pixels outside of these limits, it will result in a fatal error.


figure11.png

Figure 10. Illustration of the object image with pixels that are outside of the background image limits. If the possibility of this happening is not taken into account in the implementation, there will be a fatal error.


Validate your implementation by choosing several offsets and observing the merged image. Be sure to try cases in which you choose x and y offsets that result in the object being cropped in the merged image (as in Figure 9).



Deliverables

Use “Deliverables” in Moodle to upload the filter.cpp file that contains the MergeImages function. Remember to use good programming techniques, include the names of the programmers involved, and to document your program.



References

[1] http://en.wikipedia.org/wiki/Greenscreen(disambiguation)

[2] http://en.wikipedia.org/wiki/Chroma_key

[3] http://doc.qt.io/qt-4.8/qimage.html.