[English](#markdown-header-arrays-simple-image-editor) | [Español](#markdown-header-arreglos-editor-de-imagenes-simple) # Arreglos - Editor de Imagenes Simple ![main1.png](images/main1.png) ![main2.png](images/main2.png) ![main3.png](images/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 diseñarás e implementarás algoritmos simples de procesamiento de imágenes para practicar el uso de ciclos anidados en la manipulación de arreglos bi-dimensionales. ##Objetivos: 1. Practicar el acceder y manipular datos en un arreglo. 2. Aplicar ciclos anidados para implementar algoritmos simples de procesamiento de imágenes. 3. Utilizar expresiones aritméticas para transformar colores de pixeles. 4. Acceder pixeles en una imagen y descomponerlos en sus componentes rojo, azul y verde. ##Pre-Lab: Antes de llegar al laboratorio debes: 1. Conseguir y tener disponible uno o más archivos con una imagen a color en alguno de los siguientes formatos: `tiff, jpg, png`. 2. Haber repasado los conceptos básicos relacionados a estructuras de repetición y ciclos anidados. 3. Conocer las funciones básicas de `QImage` para manipular los pixeles de las imágenes. 4. Haber estudiado los conceptos e instrucciones para la sesión de laboratorio. 5. Haber tomado el quiz Pre-Lab que se encuentra en Moodle. --- --- ##Edición de imágenes En esta experiencia de laboratorio, trabajarás con varios conceptos y destrezas básicas de edición de imágenes. Te proveemos un interface gráfico (GUI) simple que le permite al usuario cargar una imagen e invertirla vertical y horizontalmente. Tu tarea es crear e implementar una función para convertir una imagen a color a una imagen con tonos de gris, y otra función que convierta una imagen a color a una imagen en blanco y negro. ###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 1). 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). --- ![figure1.png](images/figure1.png) **Figura 1.** 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 ![figure2.png](images/figure2.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](images/ejemplo.png) entonces `originalImage.pixel(2,1)` devuelve un valor `rgb` que representa el color azul (`0x0000ff`). 3. 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));`. 4. 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));`. 5. 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`. --- ```cpp #include #include 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; } ``` --- --- ##Sesión de laboratorio: En la experiencia de laboratorio de hoy diseñarás e implementarás algoritmos simples de procesamiento de imágenes para practicar el uso de ciclos anidados en la manipulación de arreglos bi-dimensionales. ###Ejercicio 1: Entender el código provisto ####Instrucciones 1. Carga a Qt el proyecto `SimpleImageEditor` haciendo doble "click" en el archivo `SimpleImageEditor.pro` en el directorio `Documents/eip/Arrays-SimpleImageEditor` de tu computadora. También puedes ir a `http://bitbucket.org/eip-uprrp/arrays-simpleimageeditor` para descargar la carpeta `Arrays-SimpleImageEditor` a tu computadora. 2. El código que te proveemos crea la interface de la Figura 2. --- ![figure3.png](images/figure3.png) **Figura 2.** Interface del editor de imágenes. --- 3. Estarás trabajando con el archivo `filter.cpp`. Estudia la función `HorizontalFlip` del archivo `filter.cpp` para que entiendas su operación. En los ejercicios siguientes estarás usando mayormente los objetos `originalImage` y `editedImage` de clase `QImage`. ¿Cuál crees que es el propósito la variable `pixel`? 4. El código que te proveemos ya tiene programado el funcionamiento de los botones de la interface gráfica. NO tienes que cambiar nada en este código pero te incluimos las siguientes explicaciones para que conozcas un poco del funcionamiento de los botones. En el archivo `mainwindow.cpp`, las etiquetas `lblOriginalImage` y `lblEditedImage` corresponden a las partes de la interface que identifican la imagen original y la imagen procesada. Los botones * `btnLoadImage` * `btnSaveImage` * `btnInvertThreshold` * `btnFlipImageHorizontally` * `btnFlipImageVertically` * `btnGreyScaleFilter` * `btnRevertImage` están conectados a funciones de modo que cuando se presione el botón de la interface se haga alguna tarea. Por ejemplo, cuando se presiona `LoadImage`, saldrá una ventana para seleccionar el archivo con la imagen para editar, al seleccionar el archivo, se lee y se asigna la imagen al objeto `originalImage`. El deslizador `thresholdSlider` puede asumir valores entre 0 y 255. 5. Compila y corre el programa. Prueba los botones `Load New Image` y `Flip Image Horizontally` con las imágenes que trajiste para que valides las operaciones de los botones. ###Ejercicio 2: Convertir una imagen a colores a una imagen en tonos de gris El "image grayscale" es una operación que se usa para convertir una imagen a color a una imagen que solo tenga tonalidades de gris. Para hacer esta conversión se usa la siguiente fórmula en cada uno de los píxeles: `gray = (red * 11 + green * 16 + blue * 5)/32 ;` donde `red`, `green` y `blue` son los valores para los tonos de los colores rojo, verde y azul en el píxel de la imagen original a color, y `gray` será el color asignado a los colores rojo, verde y azul en el píxel de la imagen editada. Esto es, `editedImage.setPixel( i, j, qRgb(gray, gray, gray) )`. ####Instrucciones 1. Utilizando pseudocódigo, expresa el algoritmo para convertir una imagen a color a una imagen solo con tonalidades de gris. El apéndice de este documento contiene algunos consejos sobre buenas prácticas al hacer pseudocódigos. 2. Completa la función `GreyScale` en el archivo `filter.cpp` para implementar el algoritmo de tonalidades de gris. La función debe producir un resultado similar al de la Figura 3, en donde la imagen de la izquierda es la imagen original y la de la derecha es la imagen editada. --- ![chuck-color.png](images/chuck-color.png) ![chuck-gris.png](images/chuck-gris.png) **Figura 3.** Imagen original e imagen luego de aplicar la función `GreyScale`. --- ###Ejercicio 3: Convertir una imagen a colores a una imagen en blanco y negro ("Thresholding") "Thresholding" es una operación que se puede utilizar para convertir una imagen a color a una imagen en blanco y negro. Para hacer esta conversión debemos decidir cuáles colores de la imagen original van a convertirse en píxeles blancos y cuáles serán negros. Una manera sencilla de decidir esto es computando el promedio de los componentes rojo, verde y azul de cada píxel. Si el promedio es menor que el valor umbral ("threshold"), entonces cambiamos el píxel a negro; de lo contrario se cambia a blanco. ####Instrucciones 1. Utilizando pseudocódigo, expresa el algoritmo para "thresholding". Presume que utilizarás el valor del deslizador como umbral. 2. En el programa, si la caja `chkboxThreshold` está marcada, se hace una invocación a la función `applyThresholdFilter`. La función `applyThresholdFilter` también es invocada cada vez que se cambia el valor del deslizador. 3. Completa la función `ThresholdFilter` de modo que implemente el algoritmo de "threshold" en la imagen a color utilizando el valor del deslizador como umbral. Si se implementa correctamente, la imagen de la derecha debe ser la imagen original pero en blanco y negro. El valor umbral es un parámetro de la función `ThresholdFilter`. El código provisto en `mainwindow.h` tiene definidas las constantes `BLACK` y `WHITE` con el valor hexadecimal de los colores negro y blanco respectivamente; puedes aprovechar esto y utilizarlas en tu código. 4. El parámetro booleano `invertColor` tendrá el valor `true` si la opción de invertir los colores fue seleccionada. Escribe código de modo que los colores blanco y negro se inviertan en la imagen si `invertColor` asume el valor `true`. 5. Prueba tu programa con distintas imágenes y distintos valores de umbral. --- ![chuck-color.png](images/chuck-color.png) ![chuck-threshold.png](images/chuck-threshold.png) **Figura 4.** Imagen original e imagen luego de aplicar la función `ThresholdFilter`. --- --- ##Entrega Utiliza "Entrega" en Moodle para entregar el archivo `filter.cpp` que contiene las funciones `GreyScale` y `Threshold`. Recuerda utilizar buenas prácticas de programación, incluir el nombre de los programadores y documentar tu programa. --- --- ##Apéndice: Buenas prácticas al escribir pseudocódigos 1. Provee una descripción de los datos de entrada y salida 2. Enumera los pasos 3. Usa estructuras de repetición y decisión comunes: `if, else, for, while` 4. Indenta los bloques de pasos que están dentro de una estructura de repetición o decisión, "Python-style" 5. No necesitas declarar los tipos de las variables pero si debes inicializarlas. Esto es especialmente importante para contadores y acumuladores 6. Recuerda que el propósito de un pseudocódigo es que un humano lo pueda entender. **Ejemplo:** ``` Input: n, a positive integer Output: true if n is prime, false otherwise --------------------------------------------------------- 1. for i = 3 to n / 2 2. if n % i == 0: 3. return false 4. return true ``` --- --- ##Referencias [1] http://www.willamette.edu/~gorr/classes/GeneralGraphics/imageFormats/24bits.gif [2] http://doc.qt.io/qt-4.8/qimage.html. --- --- --- [English](#markdown-header-arrays-simple-image-editor) | [Español](#markdown-header-arreglos-editor-de-imagenes-simple) # Arrays - Simple Image Editor ![main1.png](images/main1.png) ![main2.png](images/main2.png) ![main3.png](images/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 today's laboratory experience you will design and implement simple algorithms for image processing to practice the use of nested loops to manipulate bi-dimensional arrays. ##Objectives 1. Practice the access and manipulation of data in an array. 2. Apply nested loops to implement simple image processing algorithms. 3. Use arithmetic expressions to transform colors in pixels. 4. Access pixels in an image and break them down into their red, blue, and green components. ##Pre-Lab: Before coming to the laboratory session you should have: 1. Acquired one or more files with a colored image in one of the following formats: `tiff, jpg, png`. 2. Reviewed the basic concepts related to repetition structures and nested loops. 3. Become familiar with the basic functions in `QImage` to manipulate the pixels in the images. 4. Studied the concepts and instructions for the laboratory session. 5. Taken the Pre-Lab quiz available through the course’s Moodle portal. --- --- ##Image editing In this laboratory experience, you will work with various concepts and basic skills of image editing. We have provided a simple graphical user interface that allows the user to load an image and invert it vertically and horizontally. Your task is to create and implement a function to convert the colored image into an image with gray tones, and another function that converts the colored image into a black and white image. ###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 1). 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). --- ![figure1.png](images/figure1.png) **Figure 1.** 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.png](images/figure2.png) 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](images/ejemplo.png) then `originalImage.pixel(2,1)` returns the `rgb` value that represents the color blue ( `0x0000ff`). 3. 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));`. 4. 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));`. 5. 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` --- ```cpp #include #include 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; } ``` --- --- ##Laboratory Session: In today's laboratory experience you will design and implement simple image processing algorithms to practice the use of nested loops and the manipulation of bi-dimensional arrays. ###Exercise 1: Understand the provided code ####Instructions 1. Load the Qt project called `SimpleImageEditor` by double-clicking on the `SimpleImageEditor.pro` file in the `Documents/eip/Arrays-SimpleImageEditor` folder of your computer. You may also go to `http://bitbucket.org/eip-uprrp/arrays-simpleimageeditor` to download the `Arrays-SimpleImageEditor` folder to your computer. 2. The code that we provide creates the interface in Figure 2. --- ![figure3.png](images/figure3.png) **Figura 2.** Interface del editor de imágenes. --- 3. You will be working with the `filter.cpp` file. Study the `HorizontalFlip` function in the `filter.cpp` file so you understand how it operates. In the following exercises you will be mainly using the objects `originalImage` and `editedImage` of the `QImage` class. What do you think is the purpose for the `pixel` variable? 4. The provided code already has the the functionality of the buttons in the graphical user interface programmed. You do NOT have to change anything in this code but we provide the following explanations so you can know a little about how the buttons work. In the `mainwindow.cpp` file, the `lblOriginalImage` and `lblEditedImage` objects correspond to the parts of the interface that identify the original image and the processed image. The buttons * `btnLoadImage` * `btnSaveImage` * `btnInvertThreshold` * `btnFlipImageHorizontally` * `btnFlipImageVertically` * `btnGreyScaleFilter` * `btnRevertImage` are connected to functions so when a button in the interface is pressed, a certain task is carried out. For example, when you press the `LoadImage` button, a window will appear for you to select the file with the image you want to edit, which when read, the image is assigned to `originalImage`. The slider `thresholdSlider` can assume values between 0 and 255. 5. Compile and run the program. Test the buttons for `Load New Image` and `Flip Image Horizontally` with the images that you brought so you can validate if the buttons are working. ###Exercise 2: Convert a colored image to an image with gray tones Image grayscale is an operation that is used to convert a colored image to an image with only tones of gray. To make this conversion the following formula is used in each pixel: `gray = (red * 11 + green * 16 + blue * 5)/32 ;` where `red`, `green` and `blue` are the values for the tones of the red, green and blue colors in the pixel of the original colored image, and `gray` will be the assigned color to the red, green, and blue colors in the pixel of the edited image. That is, `editedImage.setPixel( i, j, qRgb(gray, gray, gray) )`. ####Instructions 1. Using pseudocode, express the algorithm to convert a colored image to an image with only gray tones. The appendix in this document contains some advice about good techniques for writing pseudocode. 2. Complete the `GreyScale` function in the `filter.cpp` file to implement the grayscale algorithm. The function should produce a result similar to that in Figure 3, where the image on the left is the original image and the one on the right is the edited image. --- ![chuck-color.png](images/chuck-color.png) ![chuck-gris.png](images/chuck-gris.png) **Figure 3.** Original image and image after applying the `GreyScale` function. --- ###Exercise 3: Convert a colored image to a black and white image ("Thresholding") Thresholding es an operation that can be used to convert a colored image to an image in black and white. To make this conversion we must decide which colors of the original image will be converted to white pixels and which to black. One simple way of deciding this is to compute the average of the red, green and blue components of each pixel. If the average is smaller than the threshold value, then we change the pixel to black; if not, it's changed to white. ####Instructions 1. Using pseudocode, express the thresholding algorithm. Assume that you will use the slider's value as the threshold. 2. In the program, if the `chkboxThreshold` box is marked, the `applyThresholdFilter` function is invoked. The `applyThresholdFilter` function is also invoked each time that the value of the slider is changed. 3. Complete the `ThresholdFilter` function so it implements the threshold algorithm in the colored image using the slider's value as the threshold. If the implementation is correct, the image on the right should be the original image but in black and white. The threshold value is a parameter of the `ThresholdFilter` function. The code provided in `mainwindow.h` has the constants `BLACK` and `WHITE` defined with their hexadecimal values; you can take advantage of this and use them in your code. 4. The boolean parameter `invertColor` will be `true` if the option to invert the colors has been selected. Write the code so that the white and black colors are inverted if `invertColor` is `true`. 5. Test the program with different images and different threshold values. --- ![chuck-color.png](images/chuck-color.png) ![chuck-threshold.png](images/chuck-threshold.png) **Figure 4.** Original image and image after applying the `ThresholdFilter` function. --- --- ##Deliverables Use "Deliverables" in Moodle to upload the `filter.cpp` file that contains the `GreyScale` and `Threshold` functions. Remember to use good programming techniques, include the names of the programmers involved, and to document your program. --- --- ##Appendix: Good techniques for writing pseudocode 1. Provide a description of the input and output data 2. Enumerate the steps 3. Use common repetition and decision structures: `if, else, for, while` 4. Indent the blocks of steps that are inside of a decision or repetition structure, "Python-style" 5. You do not need to declare the types of variables but you should initialize them. This is especially important for counters and accumulators 6. Remember that the purpose of pseudocode is so a human can understand it. **Example:** ``` Input: n, a positive integer Output: true if n is prime, false otherwise --------------------------------------------------------- 1. for i = 3 to n / 2 2. if n % i == 0: 3. return false 4. return true ``` --- --- ##References [1] http://www.willamette.edu/~gorr/classes/GeneralGraphics/imageFormats/24bits.gif [2] http://doc.qt.io/qt-4.8/qimage.html.