Howto Read in an Image From a P2 Ppm File in C

Due Engagement: May 31 @ 06:00 p.m.

Introduction

In this assignment you will practice your newly acquired C skills by implementing some functions for manipulating images. We will use the PPM (portable pix map) format, equally information technology is one of the easiest to sympathize and process. PPM is frequently used equally an intermediary format, i.e. the lowest common denominator colour image format, that nearly all other formats (e.thou. jpg, gif, png) can be translated to and from. We're explaining how this format works in more detail below.

The PPM Epitome Format

The PPM (or Portable Pix Map) image format allows for images that are encoded in homo-readable ASCII text (as opposed to a binary format), so the contents can be viewed in a text editor. You can remember of an paradigm as a matrix of pixels. Each pixel for a colour epitome is encoded by iii numbers representing the colour of the pixel, i.e. the respective carmine, greenish and bluish (RGB) values of that pixel. A PPM epitome file contains information on all the pixels in the image (in the body of the image file), preceded past a header. The eight lines below are a sample ppm file. You can download information technology here, if y'all desire to view it in a text editor. The first 3 lines comprise the header and the remaining lines the body.

          P3 	4 four 	255 	0  0  0   100 0  0       0  0  0    255   0 255 	0  0  0    0 255 175     0  0  0     0    0  0 	0  0  0    0  0  0       0 15 175    0    0  0 	255 0 255  0  0  0       0  0  0    255  255 255        

Image Header

You lot can think of the epitome as having 2 parts, a header and a body. The header consists of 4 enteries:

          P3 	iv 4 	255        

P3 is a "magic number". It indicates what type of PPM image this is. For this assignment it volition always be P3. P3 stands for color and ASCII encoded images.
Next comes the number of columns and the number of rows in the paradigm (four x 4). (The commencement number refers to the number of columns and the 2nd number to the number of rows).
Finally, we have the maximum colour value 255. This can exist any value between zero and 65536, but a common value is 255.
Note that in the sample file the four components (the magic number, # columns, # rows, maximum color) of the header are on three different lines. This formatting is to improve homo readability. The ppm standard only requires that the four components are all separated by at least i whitespace (e.g. a blank, a TAB, a newline).

Image Body

The image body contains the actual picture information. Each pixel of the image is a tiny, colored square. The colour is determined past how much red, green, and blueish are present. So, 0 0 0 is the starting time colour of the image, which is black, and the last pixel in the paradigm is 255 255 255, which is white. Past varying the levels of the RGB values you lot can come up with any colour in between.
You tin see that the body of the sample paradigm to a higher place has four rows, and each row has 12 numbers, corresponding to the 4 pixels in each row (since the file has four columns and each pixel requires iii numbers).
Note that color values must exist separated by at least one space, just at that place could be additional whitespace, which would be ignored past an prototype viewer. In the sample ppm above we used additional whitespace to format the image and then that it is easy for a human to understand, but the reckoner doesn't care how much whitespace there is between pixels or the colors within a pixel. Also, in the sample ppm file higher up there is 1 line for each row of the matrix, i.e. we have all the pixels of 1 row of the matrix in one line. We accept done that for meliorate readability, but the format does not crave this. E.g. a valid ppm image could besides have all the pixels of the prototype (of all the rows in the matris) in one line, or on the other extreme each pixel in the file could be on a separate line. The but constraint is that no line can be longer than 70 characters. The of import thing is that the pixels are listed in the right guild, starting with the elements of the kickoff row of the matrix, then the 2d row, and and then on.

Putting it all together

The example image higher up would wait something similar this:

Go on in mind, each square is 1 pixel, and so the real thing is much smaller (the rendered paradigm was diddled up by 5000%).

For those of you who wish to accept the experience of reading real documentation, the formal image specification tin be found here.

A elementary paradigm editor

Your job is to write a program called

image_editor

that serves as a simple image editor that supports three different functions.

  1. Ruby-red-removal: Takes an input image and removes the red from it.
  2. Black-white: Converting an input image to black and white.
  3. Instagram: The instagram office, which converts an image to a square image.

Since we accept not notwithstanding seen how to read and write to/from files, your program volition await to read the input paradigm from STDIN, i.e. the keyboard. It volition also expect exactly i command line argument, which specifies which of the three functions higher up information technology is supposed to execute on the input image. And then the usage of your program will be as follows:

          Usage: image_editor Selection        

where

OPTION

has to be ane graphic symbol, which is either

one

for crimson-removal,

2

for black and white conversion or

3

for the instagram office.

We are providing ii files every bit starter code, which you are expected to modify:
image_editor.c contains the primary function of the program. At the moment this function does nothing, but this is where y'all will add code to procedure the commandline argument and so telephone call the corresponding image processing function.

image_processing.c contains the skeletons of the three functions, which you will complete, such that they read the input image from the keyboard, perform the corresponding conversion and then use printf to write the output image to STDOUT (i.due east. the screen).

Chore 1: Command-line arguments

The offset task is to complete the main office in image_editor.c. Add together code to check the number of command-line arguments and the value provided equally the commencement argument. An error message should be printed, if the user provides the wrong number of arguments or if the argument is invalid (i.eastward. it is non ane of either 1, 2, or 3), every bit follows:

          Error: Expecting i command-line statement, which needs to be either 1, 2, or 3.

If an error bulletin is printed, the plan should terminate without trying to read and procedure an paradigm. Otherwise, if the control-line argument is ok, the principal function should telephone call the corresponding function to read the epitome and do the advisable conversion.

Processing of command line arguments volition be covered in calendar week 3 PCRS cloth, and so yous might want to look with implementing this function until we go there.

Task 2: The red remover

Your next task is to write a function

remove_red()

which will remove all the red from an image. The role reads an input image from the keyboard, sets the red value of each pixel in the input value to nothing, and prints the resulting image.

Chore three: The black and white converter

The second job is to write a function

convert_to_black_and_white()

, which will convert an image from color to blackness and white. Converting a pixel to black and white is washed past averaging the values of all 3 color numbers for a pixel, the red, light-green and blue, and so replacing them all by that average. So if the three colors were 25, 75 and 250, the average would be 116, and all iii numbers would become 116. So the

black_white()

function reads an input image from the keyboard, converts it to blackness and white (by converting each pixel as described in a higher place) and so printing the new output image to STDOUT (i.eastward. the screen).
Yous might wonder at this point what happens if the result of the partitioning in computing the average is not an integer. You volition come across once you take completed the calendar week 3 PCRS prep, that when you lot split an integer by another integer in C the result will be an integer (if the result has a partial part it will exist truncated). We enquire you to utilize this course of truncation when doing the partition.

Task 4: The Instagram function

For those of y'all who remember, the signature feature of the original Instagram app was that it converted any image to a square image. Y'all would upload a rectangular image of capricious dimensions and information technology would chop it to a square image. That is the functionality that you are implementing in the third task of the assignment in a function called

instagram_square()

.
The

instagram_square()

part reads an input epitome from the keyboard, and if necessary removes parts of it to brand it square, and prints the new image.
When a file needs to be chopped to become square, your role volition remove the right-most columns or bottom rows, depending on which one is the larger dimension. For case, an input image with four columns and 6 rows will be converted to a (4 x 4) image by removing the last two rows of pixels. Similarly, an image with 6 columns and 4 rows will be converted to a (4 x four) prototype past removing the terminal two columns (the pixels on the right side of the epitome)>.
Remember that you lot volition also have to modify the header to reflect the new dimensions of the image.

Some important hints

Here are a few things to remember every bit you implement and test the three functions:

  1. The input image is provided on STDIN, so y'all should utilize scanf to read input.
  2. The converted output image should exist printed to STDOUT, so you should use printf. Your program should not produce any other output, besides the output prototype. The merely exception is an fault message, in example there is a problem with the command line arguments.
  3. Equally information technology might be cumbersome to enter an input file at the keyboard, y'all can use a unix feature called input/output redirection to make life easier. By default, standard input (STDIN) is connected to the terminal keyboard. But you can use the input redirection operator (<) to connect the STDIN for a program to a file instead. For example, by running your programme image_editor as follows:
                  ./image_editor i  < sample_file.ppm            
    your program, when executing scanf, will be reading from the file named sample_file.ppm instead of the keyboard. All the contents of the file will announced to your program as if they were entered from the keyboard.
  4. If y'all provide input by typing at the keyboard, you lot terminate the input (provide EOF) by typing ctrl-D in a new (empty) line.
  5. Start by testing with small files, such as the sample ppm we take used above and make sure things piece of work as expected.
  6. Once things seem to be working for small files, you can try larger ones. We volition provide a number of sample ppm files for you to play with.
  7. You might be tempted to use an array to first read the entire input image and store the pixels of the input epitome in the array, and then practise another pass over the array to produce the output file. This has some problems. 1 is that you lot will be using upward more than memory than necessary, as yous can implement all the functionality without creating an array that contains the image pixels. The other 1 is that nosotros have non all the same seen how to dynamically classify arrays with a size that is non known before the program is run: Since you don't know before hand how big an image will be, y'all don't know how to declare an assortment of the proper size in your code.
  8. Except for Job one, which explicitly asks you to bank check for specific types of invalid input, you exercise non demand to perform mistake checking. In particular, you may assume that the input file provided to your program is a valid ppm file.
  9. You can create your ain ppm input files by converting your own images (due east.g. in jpg format) to ppm images using the mogrify command. Information technology tin be used to catechumen most common image formats to ppm, and vice versa.

    If you're working on the lab machines, the following command will convert a jpg prototype file named input.jpg to a ppm file named input.ppm.

                  mogrify -format ppm -compress none input.jpg            
    And the following command will convert a ppm prototype named input.ppm to a jpg image named input.jpg.
                  mogrify -format jpg -compress none input.ppm            
    mogrify is function of a software suite called imagemagick. If yous desire to run this on your own computer, you will have to download imagemagick here and install it.
  10. If you want to view ppm files, you lot can either employ mogrify to convert them to a more mutual format, like jpg, that whatsoever image viewer supports. Or you tin can use an prototype viewer that supports ppm. Information technology seems that on Macs new versions of Preview back up ppm, on linux machines gimp can open ppm.
  11. Your program should support any type of valid ppm P3 image as an input. In particular, there might be an arbitrary number of whitespaces separating the unlike fields, and the row, column and max color fields could be any positive integer value.
    If you read the formal specifications y'all will see that ppm supports a few things we take not talked virtually, including for example comments (lines that starting time with a #). Your programme is not required to support any ppm features that are non discussed in this consignment handout.
  12. Your program must output images that are valid in the P3 format, eastward.grand. that ways you lot must also output the appropriate P3 header and not just the pixel data.
  13. Test thoroughly before submitting a final version. We are using automated grading tools, so your program must compile and run according to the specifications. In detail, your program must be able to run on whatsoever valid ppm input file and produce merely valid ppm output files.

Submission and Marking

We are using automated grading tools to provide functional feedback, and so it'due south important that your submission be fully submitted and compile cleanly.

Your program must compile on the lab machines or mathlab, so please examination it there before submission. Nosotros will be using

gcc

to compile programme with the flags

-Wall

and

-std=c99

:

gcc -Wall -std=c99 -o image_editor image_editor.c image_processing.c

Your program should not produce any fault or alarm letters when compiled. Programs that do not compile will receive a 0. Programs that produce alert letters will exist penalized.

For this assignment you will exist working individually (rather than in teams). You will be submitting via svn to Markus. The instructions below will setup your svn piece of work environment. If yous are not already familiar with version control, make certain to review the lecture textile from Week two.

Your first step should be to log into mathlab or any of the lab machines in BV 473 using your UtorID and password. Create a directory in your home directory chosen cscb09 (directories are created using mkdir). Change into that directory (using cd). Verify that you are actually in the right directory (running pwd should return /cmshome/your_utor_id/cscb09). The following commands should achieve the in a higher place:

mkdir ~/cscb09
cd ~/cscb09
pwd

Next you need to check out your SVN repo. To check out your SVN repo you need to log in to Markus and click on A1. You volition see on the correct side a field saying "URL to your group'due south repository". The URL will probably have the class

http://markus.utsc.utoronto.ca/svn/cscb09s17/your_utor_id

. Your repository will only be generated by the Markus server once you log in and click on A1 and information technology might have a little while. And then wait a fleck before you try to check out your repo into the cscb09 directory you created earlier. You check out your repo from the shell command-line using

svn checkout

with your repo's URL equally the argument, and then this should look something like :

svn co http://markus.utsc.utoronto.ca/svn/cscb09s17/your_utor_id        

You lot will be asked for a countersign which is your usual utorid password. You volition find the repository in your electric current working directory (the place from where you were running the

svn checkout

command). It will exist a directory named after your utorid and yous will see that it contains a sub-directory called

A1

. (Use

ls

to bank check that the directory is in that location). This directory is a working re-create of your svn repository.

For this assignment yous will need to submit ii files: image_editor.c and image_processing.c. You will demand to create these two files inside the A1 directory in your repository. Later on you kickoff create these files in your A1 directory y'all demand to add them to your repository by running svn add inside your A1 directory.

          svn add image_editor.c image_processing.c        

As you work on these 2 files while implementing this assignment, y'all want to periodically upload your modifications to the svn server by running

svn commit

. You lot commit by running the following in your A1 directory (with a message of your choice):

          svn ci -1000 "Committing a new version of A1"

You tin can log into Markus to view the files it has received.

When doing the mark, nosotros will apply the latest version of your A1 that was committed before the deadline.

ivesholleatunce.blogspot.com

Source: http://www.cs.toronto.edu/~bianca/cscb09s17/posted_assignments/A1/a1.shtml

0 Response to "Howto Read in an Image From a P2 Ppm File in C"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel