project report on jpeg implementation using...

143
PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLAB Submitted in partial fulfillment of the requirement for the Award of the Degree of BACHELORS OF TECHNOLOGY IN ELECTRONICS AND COMMUINICATION ENGINEERING BY B.DHEERAJ REDDY (HALLTICKET NUMBER: 02E0A0408) Under the guidance of D. Nageshwer Rao NIZAM INSTITUTE OF ENGINEERING & TECHNOLOGY (AFFLIATED TO J.N.T.U., HYDERABAD) 2006

Upload: others

Post on 24-Mar-2020

0 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

PROJECT REPORTON

JPEG IMPLEMENTATION USING MATLAB

Submitted in partial fulfillment of the requirementfor the Award of the Degree of

BACHELORS OF TECHNOLOGYIN

ELECTRONICS AND COMMUINICATION ENGINEERING

BYB.DHEERAJ REDDY

(HALLTICKET NUMBER: 02E0A0408)

Under the guidance of

D. Nageshwer Rao

NIZAM INSTITUTE OF

ENGINEERING & TECHNOLOGY(AFFLIATED TO J.N.T.U., HYDERABAD)

2006

Page 2: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

DEPARTMENT OF ELECTRONICS & COMMUNICATION ENGINEERING

CERTIFICATE

This is to certify that the project work entitled “JPEG Implementation Using MATLAB” has been carried out by B.DHEERAJ REDDY bearing a Hall Ticket Number 02E01A0408, It is sufficiently warrant for the submission in the partial fulfillment of the requirements for the award of degree of Bachelor of Technology in Electronics and Communication Engineering during the academic year 2002-2006. The results embodied in this dissertation have not been submitted to any other University or Institution for the award any degree.

Col.(Retd.) Dr. Sadasivan .T.Veetil ,FIE Ph.D.,(Engg) MBA

Principal

D. Nageshwer Rao B.E(Electronics), M.Tech(DSCE), MISTEHead of the Department & Internal Guide

External Examiner

Page 3: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

CERTIFICATE

This is to certify that B.DHEERAJ REDDY, student of Bachelor of Technology from Nizam Institute of Engineering and Technology ( Affiliated to JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY) of Electronics and Communication Engineering has completed the project titled “JPEG Implementation using MATLAB” under the guidance of the undersigned, during the period December-2005 to March -2006 at Research Center Imarat (RCI), Hyderabad. He has displayed good analytical capability, have innovative approach tosolve problems and have produced excellent results.

It is also certified that this report carriers a bonafide account of a project work carried out under my guidance.

The results embodied in the dissertation have not been submitted to any another university or institution for the award of any degree.

Page 4: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T)

Contents

1. Introduction 1

1.1 Introduction to the project 1

1.2 Requirement Specification 1

2. Image 3

2.1 Image 3

2.2 Digital Image 3

2.3 Pixel 3

2.4 Image Types 7

2.5 Image Viewing 11

2.6 Image Calibration 13

3. Image processing 14

3.1 Image processing 14

3.2 Digital image processing 14

3.3 Steps in Digital Image Processing 15

3.4 Components of an Image Processing System 17

3.5 Uses 19

3.6 Applications 19

4. Image compressing 21

4.1 Introduction 21

4.2 Information Theory 21

4.3 Redundancy 22

4.4 Image Compression 24

4.5 Lossless Image Compression 24

4.6 Lossy Image Compression 27

4.7 Lossy vs. Lossless Compression 32

4.8 Scalability 32

Page 5: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T)

4.9 Applications 33

5. MATLAB 35

5.1 Introduction 35

5.2 The MATLAB Working Environment 35

5.3 Using the MATLAB Editor to Create M-files 37

5.4 Getting Help 37

5.5 Saving and Retrieving a Work Session 38

5.6 Reading images 38

5.7 Displaying Images 42

5.8 Writing Images 44

5.9 Data Classes 46

5.10 Arithmetic Operators 47

5.11 Relational Operators 47

5.12 Logical Operators 47

5.13 Special Characters 48

5.14 Bitwise Operators 48

5.15 Set Operators 49

5.16 Flow control 49

5.17 Some Special key Words 51

6. JPEG 56

6.1 Introduction 56

6.2 JPEG 56

6.3 Lossless process 57

6.4 Lossy process 57

6.5 Discrete cosine transform 60

6.6 Transform coding 61

6.7 JPEG Fundamentals 66

6.8 Decompression 75

Page 6: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T)

6.9 Compression ratio 76

7. Implementation & Results 77

7.1 Algorithms 77

7.2 Implementation 83

8. Conclusion 90

9. Future Enhancement of the Project 91

10. Appendix-A --COMPRESSION CODE 92

11. Appendix-B --DECOMPRESSION CODE 107

12. Bibliography 125

Page 7: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T)

ABSTRACT

PROJECT TITLE:JPEG Implementation Using MATLAB

“But life is short and information endless… Abbreviation is a necessary evil and the abbreviator’s business is to make the best of a job which although intrinsically bad, is still better than nothing.” --Aldous Huxley

Image compression is the application of data compression on digital images. In effect, the objective is to reduce redundancy of the image data in order to be able to store or transmit data in an efficient form.

Image compression can be lossy or lossless. Lossless compression is sometimes preferred for artificial images such as technical drawings, icons or comics.. Lossless compression methods may also be preferred for high value content, such as medical imagery or image scans made for archival purposes. Lossy methods are especially suitable for natural images such as photos in applications where minor (sometimes imperceptible) loss of fidelity is acceptable to achieve a substantial reduction in bit rate. Transform coding is the most commonly used method of the lossy compression methods A Fourier-related transform such as DCT or the wavelet transform are applied, followed by quantization and entropy coding. The best image quality at a given bit-rate (or compression rate) is the main goal of image compression.

Image processing more frequently uses the transforms like Discrete Cosine Transform (DCT) or Fourier transform (FT) for image compression. This involves the conversion of the source signal to frequency component.

The important application of wavelets is separating the smooth variations and details of the image, which is done by wavelet decomposition of the image using a Discrete Wavelet Transform (DWT). The overall compression is achieved through source encoder, Quantizer and entropy encoder.

The JPEG process is a widely used form of lossy image compression that centers around the discrete cosine transform.The DCT works by separating images in to parts of different frequencies.During a step called quantization where part of compression actually occurs,the less important frequencies are discarded the only important frequencies that remain are used to retreive the image in decompression process.As a result, reconstructed images contain some distortion .The JPEG method is used for both color and black and white images, but the focus of this project will be on the compression of the latter.

Page 8: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

INTRODUCTION

Page 9: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 1

1.1 INTRODUCTION TO THE PROJECT

Every day, an enormous amount of information is stored, processed and transmitted daily digitally. Companies provide businesses, associates, investors, and potential costumers with financial data, annual reports, inventory, and product information over the Internet. Method of compressing the data prior to storage and /or transmission is of significant practical and commercial interest.

Image compression addresses the problem of reducing the amount of data required to represent a digital image. The underlying basis of the reduction process is the removal of redundant data. From a mathematical viewpoint, this amounts to transformation a 2-D pixel array into a statistically uncorrelated data set. The transformation is applied prior to storage or transmission of the image. At the receiving end, the compressed image is decompressed to reconstruct the original image or an approximation of it.

The initial focus of research efforts in this field was on the development of analog methods of reducing video transmission bandwidth, a process called bandwidth compression. The advent of the digital computers and subsequent development of advanced integrated circuits, however, caused interest to shift from analog to digital compression approaches.

Image compression is recognized as an “Enabling technology.” In addition to the areas just mentioned, image compression is the natural technology for handling the increased spatial resolutions of today’s imaging sensors and evolving broadcast television standards. Furthermore, image compression plays a major role in many important and diverse applications, including televideo-conferencing, remote sensing, document and medical imaging, facsimile transmission, and the control of remotely pilot vehicles in military, space, and hazardous waste management application.

1.2 REQUIREMENT SPECIFICATION

PURPOSE: The main purpose of preparing this document is to give a general in sight into the analysis and requirements of a typical image compression system and its implementation.

SCOPE: It describes the complete requirement of the system. It is meant for use by the developers and can be used as a base line document for future development.

Page 10: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 2

MAJOR HARDWARE SPECIFICATIONS:

PROCESSOR : Intel Pentium-III or more

RAM : 128 MB or more

CACHE : 256 KB

HARD DISK : 10 GB hard disk recommendation for primary partition

SOFTWARE SPECIFICATIONS:

OPEARTING SYSTEM: MS-WINDOWS 98 or Later editions

CODING TOOLS USED: MATLAB 7.0

Page 11: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

IMAGE

Page 12: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 3

2.1 Image

In common usage, an image (from Latin imago) or picture is an artifact that reproduces the likeness of some subject—usually a physical object or a person. Images may be two dimensional (e.g. a photograph) or three dimensional (e.g. a statue). They are typically produced by optical devices—such as a cameras, mirrors, lenses, telescopes, microscopes, etc. and natural objects and phenomena, such as the human eye or water surfaces. The word image is also used in the broader sense of any two-dimensional figure or illustration, e.g. a map, a graph, a pie chart, an abstract painting, etc. In this wider sense, images can also be produced manually (by drawing, painting, carving, etc.), by computer graphics technology, or a combination of the two. A volatile image is one that exists only for a short period of time, e.g. the reflection of an object by a mirror, a projection of the sun on a wall by a pinhole camera, or a scene displayed on a cathode ray tube. A fixed image, also called hardcopy, is one that has been recorded on a material object, such as paper or textile. A mental image exists in someone's mind: something one remembers or imagines. The subject of an image need not be real; it may be an abstract concept, such as a graph or function—or an imaginary entity or being.

2.2 Digital Image

A digital image is a representation of a two-dimensional image as a finite set of digital values, called picture elements or pixels. Typically, the pixels are stored in computer memory as a raster image or raster map, a two-dimensional array of small integers. These values are often transmitted or stored in a compressed form. Digital images can be created by a variety of input devices and techniques, such as digital cameras, scanners, coordinate-measuring machines, seismographic profiling, airborne radar, and more. They can also be synthesized from arbitrary non-image data, such as mathematical functions or three-dimensional geometric models; the latter being a major sub-area of computer graphics. The field of digital image processing is the study of algorithms for their transformation.

2.3 Pixel

A pixel is one of the many tiny dots that make up the representation of a picture in a computer's memory. Each such information element is not really a dot, nor a square, but an abstract sample. With care, pixels in an image can be reproduced at any size without the appearance of visible dots or squares; but in many contexts, they are reproduced as dots or squares and can be visibly distinct when not fine enough. The intensity of each pixel is variable; in color systems, each pixel has typically three or four dimensions of variability such and Red, Green and Blue, or Cyan, Magenta, Yellow and Black.

Pixels are generally thought of as the smallest complete sample of an image. The definition is highly context sensitive. Pixel in a visible image (e.g. a printed page) or pixels carried by one or more electronic signal(s), or represented by one or more digital value(s), or pixels on a display device, or pixels in a digital camera ( photo-sensor elements). This list is not exhaustive and depending on context

Page 13: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 4

there are several synonyms which are accurate in particular contexts, e.g. pel, sample, bytes, bits, dots, spots, superset, triad, stripe set, window, etc. Pixels in the abstract, in particular when using pixels as a measure of resolution, e.g. 2400 pixels per inch or 640 pixels per line. Dots are often used to mean pixels, and gives rise to the abbreviation DPI or dots per inch.

FIGURE: 2-1 The logo of Wikipedia has been divided into pixel and a particular pixel has been enlarged

This example shows a former Wikipedia logo with a portion greatly enlarged. The different shades of grey blend together to create the illusion of a smooth image. Note that sometimes the edge pixels of text are reduced in shade to produce a less stepped look when viewed at normal size. This is called anti-aliasing.

The more pixels used to represent an image, the closer the result can resemble the original. The number of pixels in an image is sometimes called the resolution, though resolution has a more specific definition. Pixels can be expressed as a single number, as in a "three-megapixel" digital camera, which has a nominal three million pixels, or as a pair of numbers, as in a "640 by 480 display", which has 640 pixels from side to side and 480 from top to bottom, and therefore has a total number of 640 × 480 = 307,200 pixels. The color samples that form a digitized image are also called pixels. Depending on how a computer displays an image, these may not be in one-to-one correspondence with screen pixels. In areas where the distinction is important, the dots in the image file may be called texels. In computer programming, an image composed of pixels is known as a bitmapped image or a raster image. The word raster originates from analogue television technology. Bitmapped images are used to encode digital video and to produce some types of computer-generated art.

2.3.1 Native Vs Logical pixels

Since the resolution of most computer displays can be adjusted from the computer's operating system, a display's pixel resolution may not be an absolute measurement. Modern LCD computer displays are designed with a native resolution which refers to the perfect match between pixels and triads. (CRT displays also use red-green-blue phosphor triads, but these are not coincident with image pixels, and cannot therefore be said to be equivalent to pixels.).The native resolution will produce the sharpest picture capable from the display. However since the user can adjust the resolution, the monitor must be capable of displaying other resolutions. Non-native resolutions have to be supported by approximate resampling in the LCD screen, using

Page 14: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 5

interpolation algorithms. This often causes the screen to look jagged or blurry. For example, a display with a native resolution of 1280×1024 will look best set at 1280×1024 resolution, will display 800×600 adequately by drawing each pixel with more physical triads, and may be unable to display in 1600×1200 at all due to the lack of physical triads.

Pixels can be either rectangular or square. A number called the aspect ratio describes the squareness of a pixel. For example, a 1.25:1 aspect ratio means that each pixel is 1.25 times wider than it is high. Pixels on computer monitors are usually square, but pixels used in digital video have non-square aspect ratios, such as those used in the PAL and NTSC variants of the CCIR 601 digital video standard, and the corresponding anamorphic widescreen formats. Each pixel in a monochrome image has its own brightness. Zero usually represents black, and the maximum value possible represents white. For example, in an eight-bit image, the maximum unsigned value that can be stored by eight bits is 255, so this is the value used for white. In a colour image, each pixel can be described using its hue, saturation, and value, but is usually represented instead as red, green and blue intensities.

2.3.2 Bits Per Pixel

The number of distinct colours that can be represented by a pixel depends on the number of bits per pixel (BPP). The maximum number of colors a pixel can take can be found by taking two to the power of the color depth. For example, common values are

• 8 bpp [28=256; (256 colours)],

• 16 bpp [216=65536; (65,536 colours, known as Highcolour)],

• 24 bpp [224=16777216; (16,777,216 colours, known as Truecolour)].

• 48 bpp [248=281474976710656; (281,474,976,710,656 colors, used in many

flatbed scanners and for professional work)

Images composed of 256 colours or fewer are usually stored in the computer's video memory in chunky or planar format, where a pixel in memory is an index into a list of colours called a palette. These modes are therefore sometimes called indexed modes. While only 256 colours are displayed at once, those 256 colours are picked from a much larger palette, typically of 16 million colours. Changing the values in the palette permits a kind of animation effect. The animated startup logo of Windows 95 and Windows 98 is probably the best-known example of this kind of animation. For depths larger than 8 bits, the number is the total of the three RGB (red, green and blue) components. A 16-bit depth is usually divided into five bits for each of red and blue, and six bits for green (the eye being more sensitive to green). A 24-bit depth allows 8 bits per component. On some systems, 32-bit depth is available: this means that each 24-bit pixel has an extra 8 bits to describe its opacity. On older systems, 4 bpp (16 colours) is also common.

When an image file is displayed on a screen, the number of bits per pixel is expressed separately for the raster file and for the display. Some raster file

Page 15: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 6

formats have a greater bit-depth capability than others. The GIF format, for example, has a maximum depth of 8 bits, while TIFF files can handle 48-bit pixels. There are no displays that can display 48 bits of colour, so this depth is typically used for specialized professional applications with film scanners and printers. Such files are rendered on a screen with 24-bit depth.

2.3.3 Subpixels

Many display and image-acquisition systems are, for various reasons, not capable of displaying the different colour channels at the same site. This approach is generally resolved by using multiple subpixels, each of which handles a single colour channel. For example, LCD displays typically divide each pixel horizontally into three subpixels. Most LED displays divide each pixel into four subpixels; one red, one green, and two blue. Most digital camera sensors also use subpixels, by using coloured filters. (CRT displays also use red-green-blue phosphor dots, but these are not aligned with image pixels, and cannot therefore be said to be subpixels.). For systems with subpixels, two different approaches can be taken: The subpixels can be ignored, with pixels being treated as the smallest addressable imaging element, or the subpixels can be included in rendering calculations, which requires more analysis and processing time, but can produce apparently superior images in some cases.

The latter approach has been used to increase the apparent resolution of colour displays. The technique, referred to as subpixel rendering, uses knowledge of pixel geometry to manipulate the three coloured sub-pixels separately, and is most effective with flat-panel displays set to their native resolutions (because the pixel geometry of such displays is usually fixed and predictable). This is a form of anti-aliasing, and is mostly used to improve the appearance of text. Microsoft's Clear Type, which is available in Windows XP, is an example of this.

2.3.4 Megapixel

A megapixel is 1 million pixels, and is usually used to express the resolution capabilities of digital cameras. For example, a camera that can take pictures with a resolution of 2048×1536 pixels is commonly said to have "3.1 megapixels" (2048 × 1536 = 3,145,728). Digital cameras use photosensitive electronics, either Charge-coupled devices (CCDs) or CMOS sensors, which record brightness levels on a per-pixel basis. In most digital cameras, the CCD is covered with a patterned color filter having red, green, and blue regions in the Bayer filter mosaic arrangement, so that each sensor pixel can record the brightness of a single primary color. The camera interpolates the color information of neighboring pixels, through a process called de-mosaicing, to create the final image. Thus, an x-megapixel image from a digital camera can have as little as one quarter the color resolution of the same image as taken by a scanner. Thus, a picture of a blue or red object will tend to look fuzzy compared to the same object displayed in shades of grey. Green objects appear less fuzzy, since green is allocated more pixels (due to the eye's increased sensitivity for green). In a new development, the Foveon X3 CCD uses a tri-layer image sensor that detects red, green and blue intensity at each pixel location. This structure

Page 16: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 7

eliminates the need for de-mosaicing and eliminates the associated image artifacts, like color blurring around sharp edges.

2.4 Image Types

Each pixel of an image is typically associated to a specific 'position' in some 2D region, and has a value consisting of one or more quantities (samples) related to that position. Digital images can be classified according to the number and nature of those samples:

Binary (bi-level) Grayscale Color False-color Multi-spectral Thematic

The term digital image is also applied to data associated to points scattered over a three-dimensional region, such as produced by tomo-graphicequipment. In that case, each datum is called a voxel.

2.4.1 Binary Image

A binary image is a digital image that has only two possible values for each pixel. Binary images are also called bi-level or two-level. (The names black-and-white, B&W, monochrome or monochromatic are often used for this concept, but may also designate any images that have only one sample per pixel, such as grayscale images.). Binary images often arise in digital image processing as masks or as the result of certain operations such as segmentation, thresholding, and dithering. Some input/output devices, such as laser printers, fax machines, and bi-level computer displays, can only handle bi-level images. A binary image is usually stored in memory as a bitmap, a packed array of bits. Binary images can be interpreted as subsets of the two-dimensional integer lattice Z2; the field of morphological image processing was largely inspired by this view.

2.4.2 Grayscale Image

In computing, a grayscale or greyscale digital image is an image in which the value of each pixel is a single sample. Displayed images of this sort are typically composed of shades of gray, varying from black at the weakest intensity to white at the strongest, though in principle the samples could be displayed as shades of any color, or even coded with various colors for different intensities. Grayscale images are distinct from black-and-white images, which in the context of computer imaging are images with only two colors, black and white; grayscale images have many shades of gray in between. In most contexts other than digital imaging, however, the term "black and white" is used in place of "grayscale"; for example, photography in shades of gray is typically called "black-and-white photography". The

Page 17: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 8

term monochromatic in some digital imaging contexts is synonymous with grayscale, and in some contexts synonymous with black-and-white.

Grayscale images are often the result of measuring the intensity of light at each pixel in a single band of the electromagnetic spectrum (e.g. visible light). Grayscale images intended for visual display are typically stored with 8 bits per sampled pixel, which allows 256 intensities (i.e., shades of gray) to be recorded, typically on a non-linear scale. The accuracy provided by this format is barely sufficient to avoid visible banding artifacts, but very convenient for programming. Technical uses (e.g. in medical imaging or remote sensing applications) often require more levels, to make full use of the sensor accuracy (typically 10 or 12 bits per sample) and to guard against roundoff errors in computations. Sixteen bits per sample (65536 levels) appears to be a popular choice for such uses.

FIGURE: 2-2 The same picture in three different color modes. The picture on the top left is the original photograph, in full color. The picture in the top right is in grayscale; all the colors

contained in it are black, white, or any shade of gray. The picture on the bottom is in black and white, or monochrome; the only colors used in the picture are black and white, with no intermediary

grays.

2.4.3 Color Image

A (digital) color image is a digital image that includes colorinformation for each pixel. For visually acceptable results, it is necessary (and almost sufficient) to provide three samples (color channels) for each pixel, which are interpreted as coordinates in some color space. The RGB color space is commonly used in computer displays, but other spaces such as YUV, HSV, and are often used in other contexts.

2.4.3.1 Color Image Representation

A color image is usually stored in memory as a raster map, a two-dimensional array of small integer triplets; or (rarely) as three separate raster maps,

Page 18: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 9

one for each channel. Eight bits per sample (24 bits per pixel) seem to be adequate for most uses, but faint banding artifacts may still be visible in some smoothly varying images -- especially those which have been subject to processing. Particularly demanding applications may use 10 bits per sample or more. On the other hand, some widely used image file formats and graphics cards may use only 8 bits per pixel -- i.e. only 256 different colors, or 2--3 bits per channel. Converting continuous-tone images like photographs to such formats requires dithering and yields rather grainy and fuzzy results. Graphics cards that support 16 bits per pixel provide 65536 distinct colors, or 5--6 bits per channel. This resolution seems to be satisfactory for non-professional uses, even without dithering.

2.4.4 False-color Image

A false-color image is an image that depicts a subject in colors that differ from human perception of the same subject. Also known as a pseudo-color image, it is derived from a greyscale image by mapping each pixel value to a color according to a table or function. A familiar example is the encoding of altitude in physical relief maps, where negative values (below sea level) are usually represented by shades of blue and positive values by greens and browns. Although false-coloring does not increase the information contents of the original image, it can make some details more visible, by increasing the distance in color space between successive gray levels. A true-color image of a subject is an image that appears to the human eye just like the original subject would: a green tree appears green in the image, a red apple red, a blue sky blue, etc. When applied to black-and-white images, true-color means that the perceived lightness of a subject is preserved in its depiction.

FIGURE: 2-3 This "true color" image shows the same region as the "false color" image on left, but uses true colors, e.g., the plants are shown in green.

In a false-color image this close correspondence between subject color and image color is violated. That can happen in many ways. For example, a photographic negative could be called a false-color image, since it shows the complementary colors of its subject. However, the term "false-color" is typically used to describe images whose colors represent measured intensities outside the visible portion of the electromagnetic spectrum (or outside the electromagnetic spectrum altogether).

Page 19: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 10

For example infrared film captures a small region of the near infraredspectrum (wavelengths from about 700 nm to 900 nm). Black-and-white infrared film maps the average intensity in this portion of the spectrum to a "false" gray value. Typical color infrared film is sensitive in the visible and near infrared range; it is usually used, in conjunction with a blue-cut filter, for shifting the near infrared spectrum into the visible spectrum (ca. 400 nm to 700 nm). Loosely speaking, this process effectively subtracts ca. 150 nm from the subject wavelength: a green subject is depicted as blue; a red subject is depicted as green; and an infrared subject is depicted as red (blue subjects cannot be depicted; they appear black).

More generally, false-color images can be generated by digital image processing techniques to represent up to three independent measurements over a two-dimensional map or image. For example, a satellite might capture average intensities in short ranges of the ultraviolet spectrum and the near infrared spectrum. These measurements can be combined with altitude information in such a way that blue represents ultraviolet, green represents altitude, and red represents infrared. Then a bright yellow pixel indicates a high-altitude object that emits or reflects infrared light but not ultraviolet light; a magenta pixel indicates a low-altitude object that emits or reflects both infrared and ultraviolet light; etc. Because human visual perception is limited to three independent coordinates, at most three measurements can be depicted in such a way. False-color images are frequently used for viewing satellite images, such as from weather satellites, the Hubble Space Telescope, and the Cassini-Huygens space probe's images of the rings of Saturn. Infrared cameras used for thermal imaging often show their image in false colors.

2.4.5 Multi-spectral Image

Multi-spectral images are images of the same object (Earth or planetary surface), taken in different bands of visible or infrared region of electromagnetic continuum. This is the main type of images acquired by Remote sensing (RS) radiometers. Multi-spectral is the opposite of panchromatic. Usually satellites have 3 to 7 or more radiometers (France's SPOT has 3, Landsat has 7). Each one acquires one digital image (in remote sensing, called a scene) in a small band of visible spectra, ranging 0.7 μm to 0.4 μm, called red-green-blue (RGB) region, and going to infra-red wavelengths of 0.7 μm to 10 or more μm, classified as NIR-Near Infrared, MIR-Midle Infrared and FIR-Far Infrared or Thermal. In the Landsat case there are 7 scenes comprising a 7 band multi spectral image

2.4.6 Thematic Image

Thematic Images are usually image products of classificationprocessing of multi-spectral images. The classification process differentiate types of earth surface such as land, water, forest, lake, structure etc. In more details we might have classes such as type of crop, or pollution structure, burn forest, volcano eruption with lava, clear or turbid water, sea water, phytoplankton, or, in smaller scales, roads, crops, artificial structures etc.

Page 20: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 11

2.5 Image Viewing

The user can utilize different programs to see the image. The GIF, JPEG and PNG images can be seen simply using a web browser because they are the standard internet image formats. The SVG format is more and more used in the web and is a standard W3C format. The more advanced programs offer a slideshow utility, to see the images in a certain folder one after the other automatically.

2.5.1 GIF

GIF (Graphics Interchange Format) is a bitmap image format forpictures with up to 256 distinct colours. The format was introduced by CompuServein 1987 and has since come into widespread usage on the World Wide Web. GIFs are compressed files, and were adopted to reduce the amount of time it takes to transfer images over a network connection.

A GIF file employs lossless data compression so that the file size of an image may be reduced without degrading the visual quality, provided the image fits into 256 colours. (However, there is a hack that can overcome this limitation under certain circumstances.) The GIF format's 256-colour limitation makes it unsuitable for photographs, though losslessly compressed photographs tend to be unacceptably large for the web anyway. On the other hand the lossy JPEG format does badly on sharp transitions like those in diagrams, producing highly visible artifacts and little file-size reduction. Therefore GIF is normally used for diagrams, buttons, etc., that have a small number of colours, while the JPEG format is used for photographs.

FIGURE: 2-4 The image of the planet EARTH which is in GIF format

Many software developers were caught by surprise when it was revealed that the GIF format had been patented by Unisys, and that they would have to pay royalties for writing programs that generated (or displayed) GIF files. The desire for a comparable format with fewer legal restrictions (as well as fewer technical restrictions such as the number of colours) led to the development of the PNG (Portable Network Graphics) standard. Although the GIF patents will expire in near future, PNG is still touted as a technically superior alternative, and has become the third most common image format on the web. The latest expiration date of the GIF-related patents will most probably be Friday, 11 August 2006.

Page 21: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 12

2.5.2 PNG

Figure: 2-5 A PNG image with an 8-bit transparency layer (Left), overlayed onto a chequered background (Right).

PNG (Portable Network Graphics) is a lossless bitmap image format. PNG was created to both improve upon and replace the GIF format with an image file format that does not require a patent license to use. PNG is officially pronounced as

"ping" (/pɪŋ/ in IPA), but it is often just spelled out — possibly to avoid confusion with the internet tool ping. PNG is supported by the libpng reference library, a platform-independent library that contains C functions for handling PNG images. PNG files nearly always use the file extension PNG or png and are assigned the MIMEmedia type image/png.

2.5.3 BMP

.BMP or .DIB (device-independent bitmap) is a bitmapped graphics format used internally by the Microsoft Windows graphics subsystem (GDI), and used commonly as a simple graphics file format on that platform. Images are generally stored with a color depth of 2 (1-bit), 16 (4-bit), 256 (8-bit), 65,536 (16-bit), or 16.7 million (24-bit). 8-bit images can also be greyscale instead of indexed color. An alpha channel (for transparency) may be stored in a separate file, where it is similar to a greyscale image. A 32-bit version with integrated alpha channel has been introduced with Windows XP and is used within its logon and theme system; it has yet to gain wide support in image editing software.

BMP files are usually not compressed, so they are typically much larger than compressed image file formats for the same image. The typical true-color bitmap size in bytes can be calculated as: (width in pixels)×(height in pixels)×3+54, though it will be slightly more if the width is not a multiple of 4. So an 800×600 image will occupy almost 1.4 megabytes. As such they are generally unsuitable for transferring images on the Internet or other slow or capacity-limited media. Compressed images employ a RLE algorithm. Nevertheless, the simplicity of BMP and its widespread familiarity in MS Windows and elsewhere, as well as the fact that this format is well-documented and free of patents, makes it a very common format that image processing programs from many operating systems can read and write.

The X Window System uses a similar .XBM format for true single-bit black and white images, and .XPM (pixelmap) for color images. There is also a .RAW

Page 22: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 13

format, which saves raw data with no other information. The Portable Pixmap file format (.PPM) and Truevision TGA (.TGA) formats also exist, but are rarely used. Yet other formats store as "bitmaps" (as opposed to vector graphics), but use compression or color indexes, and thus are not strictly considered true bitmaps. Most BMP files compress very well with lossless data compression algorithms such as ZIP because they contain redundant data.

2.6 Image Calibration

Proper use of a digital image usually requires knowledge of the relationship between it and the underlying phenomenon, which implies geometric and photometric (or sensor) calibration. One must also keep in mind the unavoidable errors that arise from the finite spatial resolution of the pixel array and the need to quantize each sample to a finite set of possible values.

Page 23: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

IMAGEPROCESSING

Page 24: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 14

3.1 Image processing

In the broadest sense, Image processing is any form of information processing for which both the input and output are images, such as photographs or frames of video. Most image processing techniques involve treating the image as a two-dimensional signal and applying standard signal processing techniques to it.

A few decades ago, image processing was done largely in the analogdomain, chiefly by optical devices. These optical methods are still essential to applications such as holography because they are inherently parallel; however, due to the significant increase in computer speed, these techniques are increasingly being replaced by digital image processing methods.

Digital image processing techniques are generally more versatile, reliable, and accurate; they have the additional benefit of being easier to implement than their analog counterparts. Specialized hardware is still used for digital image processing: computer architectures based on pipelining have been the most commercially successful. There are also many massive parallel architectures that have been developed for the purpose. Today, hardware solutions are commonly used in video processing systems. However, commercial image processing tasks are more commonly done by software running on conventional personal computers.

3.2 Digital image processing Digital image processing is the use of computer algorithms to perform image processing on digital images. Digital image processing has the same advantages (over analog image processing) as digital signal processing has (over analog signal processing) -- it allows a much wider range of algorithms to be applied to the input data, and can avoid problems such as the build-up of noise and signal distortion during processing.

Because of the computational load of dealing with images containing millions of pixels, digital image processing was largely of academic interest until the 1970s, when dedicated hardware became available that could process images in real time, for some dedicated problems such as television standards conversion. As general-purpose computers became faster, they started to take over the role of dedicated hardware for all but the most specialized and compute-intensive operations. With the fast computers and signal processors available in the 2000s, digital image processing has become the most common form of image processing, and is generally used because it is not only the most versatile method, but also the cheapest.

3.2.1 Digital processing of camera images

Images taken by popular digital cameras often need processing to improve their quality, a distinct advantage digital cameras have over film cameras. The digital image processing is done by special software programs that manipulate theimages is many ways. This process is performed in a "digital darkroom", which is not really a darkroom as it is accomplished via a computer and keyboard.

Page 25: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 15

3.3 Steps in Digital Image Processing Image acquisition is the first process. Note that acquisition could be as simple as being given an image that is already in digital form. Generally, the image acquisition stage involves preprocessing, such as scaling.

Image enhancement is among the simplest and most appealing areas of digital image processing. Basically, the idea behind enhancement techniques is to bring out detail that is obscured, or simply to highlight certain features of interest in an image. A familiar example of enhancement is when we increase the contrast of an image because “it looks better.” It is important to keep in mind that enhancement is a very subjective area of image processing.

Image restoration is an area that also deals with improving the appearance of an image. However, unlike enhancement, which is subjective, image restoration is objective, in the sense that restoration techniques tend to be based on mathematical or probabilistic models of image degradation. Enhancement, on the other hand, is based on human subjective preferences regarding what constitutes a “good” enhancement result.

Color image processing is an area that has been gaining in importance because of the significant increase in the use of digital images over the Internet.

Wavelets are the foundation for representing images in various degrees of resolution.

Compression, as the name implies, deals with techniques for reducing the storage required for saving an image, or the bandwidth required in transmitting it. Although storage technology has improved significantly over the past decade, the same cannot be said for transmission capacity. This is true particularly in uses of the Internet, which are characterized by significant pictorial content. Image compression is familiar (perhaps inadvertently) to most users of computers in the form of image file extensions, such as the jpg file extension used in the JPEG (Joint Photographic Experts Group) image compression standard.

Morphological processing deals with tools for extracting image components that are useful in the representation and description of shape. Segmentation procedures partition an image into its constituent parts or objects. In general, autonomous segmentation is one of the most difficult tasks in digital image processing. A rugged segmentation procedure brings the process a long way toward successful solution of imaging problems that require objects to be identified individually. On the other hand, weak or erratic segmentation algorithms almost always guarantee eventual failure. In general, the more accurate the segmentation, the more likely recognition is to succeed.

Representation and description almost always follow the output of a segmentation stage, which usually is a raw pixel data, constituting either the boundary of a region (i.e., the set of pixels separating one image region from another) or all the points in the region itself. In either case, converting the data to a form suitable for

Page 26: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 16

computer processing is necessary. The first decision that must be made is whether the data should be represented as a boundary or as a complete region. Boundary representation is appropriate when the focus is on external shape characteristics, such as corners and inflections. Regional representation is appropriate when the focus is on internal properties, such as texture or skeletal shape. In some applications, these representations complement each other. Choosing a representation is only part of the solution for transforming raw data into a form suitable for subsequent computer processing. A method must also be specified for describing the data so that features of interest are highlighted. Description, also called feature selection, deals with extracting attributes that result in some quantitative information of interest or are basics for differentiating one class of objects from another.

FIGURE: 3-1 Fundamental Steps in Digital Image Processing

Recognition is the process that assigns a label to an object based on its descriptors.

Knowledge about a problem domain is coded into an image processing system in the form of a knowledge database. This knowledge may be as simple as detailing regions of an image where the information of interest is known to be located, thus limiting the search that has to be conducted in seeking that information. The knowledge base also can be quite complex, such as an interrelated list of all major possible defects in a materials inspection problem or an image database containing high-resolution satellite images of a region in connection with change-detection applications. In addition to guiding the operation of each processing module, the knowledge base also controls the interaction between modules.

Page 27: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 17

3.4 Components of an Image Processing System As recently as the mid-1980s, numerous models of image processing systems being sold throughout the world were rather substantial peripheral devices that are attached to equally substantial host computers. Late in the 1980s and early in the 1990s, the market shifted to image processing hardware in the form of single boards designed to be compatible with industry standard buses and to fit into the engineering workstation cabinets and personal computers. In addition to lowering costs, this market shift also served as a catalyst for a significant number of new companies whose specialty is the development of software written specifically for image processing.

Although large-scale image processing systems still are being sold for massive imaging applications, such as processing of satellite images, the trend continues toward miniaturizing and blending of general-purpose small computers with specialized image processing hardware.

With reference to sensing, two elements are required to acquire digital images. The first is a physical device that is sensitive to the energy radiated by the object we wish to image. The second, called a digitizer, is a device for converting the output of the physical sensing device into digital form. For instance, in a digital video camera, the sensors produce an electrical output proportional to light intensity. The digitizer converts these outputs to digital data.

Specialized image processing hardware usually consists of the digitizer just mentioned, plus hardware that performs other primitive operations, such as an arithmetic logic unit (ALU), which performs arithmetic and logical operations in parallel on entire images. One example of how an ALU is used is in averaging images as quickly as they are digitized, for the purpose of noise reduction. This type of hardware sometimes is called a front-end subsystem, and its most distinguishing characteristic is speed. In other words, this unit performs functions that require fast data throughputs (e.g., digitizing and averaging video images at 30 frames) that the typical main computer cannot handle.

The computer in an image processing system is a general-purpose computer and can range from a PC to a supercomputer. In dedicated applications, sometimes specially designed computers are used to achieve a required level of performance, but our interest here is on general-purpose image processing systems. In these systems, almost any well-equipped PC-type machine is suitable for offline image processing tasks.

Software for image processing consists of specialized modules that perform specific tasks. A well-designed package also includes the capability for the user to write code that, as a minimum, utilizes the specialized modules. More sophisticated software packages allow the integration of those modules and general-purpose software commands from at least one computer language.

Mass storage capability is a must in image processing applications. An image of size 1024*1024 pixels, in which the intensity of each pixel is an 8-bit quantity, requires one megabyte of storage space if the image is not compressed.

Page 28: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 18

When dealing with thousands, or even millions, of images, providing adequate storage in an image processing system can be a challenge. Digital storage for image processing applications falls into three principal categories: (1) short term storage for use during processing, (2) on-line storage for relatively fast recall, and (3) archival storage, characterized by infrequent access. Storage is measured in bytes (eight bits), Kbytes (one thousand bytes), Mbytes (one million bytes), Gbytes (meaning giga, or one billion, bytes), and Tbytes (meaning tera, or one trillion, bytes).

FIGURE: 3-2 Components of a general purpose image processing system

One method of providing short-term storage is computer memory. Another is by specialized boards, called frame buffers, that store one or more images and can be accessed rapidly, usually at video rates (e.g., at 30 complete images per second).The latter method allows virtually instantaneous image zoom, as well as scroll (vertical shifts) and pan (horizontal shifts). Frame buffers usually are housed in the specialized image processing hardware unit. Online storage generally takes the form of magnetic disks or optical-media storage. The key factor characterizing on-line storage is frequent access to the stored data. Finally, archival storage is characterized by massive storage requirements but infrequent need for access. Magnetic tapes and optical disks housed in “jukeboxes” are the usual media for archival applications.

Page 29: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 19

Image displays in use today are mainly color (preferably flat screen) TV monitors. Monitors are driven by the outputs of image and graphics display cards that are an integral part of the computer system. Seldom are there requirements for image display applications that cannot be met by display cards available commercially as part of the computer system. In some cases, it is necessary to have stereo displays, and these are implemented in the form of headgear containing two small displays embedded in goggles worn by the user.

Hardcopy devices for recording images include laser printers, film cameras, heat-sensitive devices, inkjet units, and digital units, such as optical and CD-ROM disks. Film provides the highest possible resolution, but paper is the obvious medium of choice for written material. For presentations, images are displayed on film transparencies or in a digital medium if image projection equipment is used. The latter approach is gaining acceptance as the standard for image presentations.

Networking is almost a default function in any computer system in use today. Because of the large amount of data inherent in image processing applications, the key consideration in image transmission is bandwidth. In dedicated networks, this typically is not a problem, but communications with remote sites via the Internet are not always as efficient. Fortunately, this situation is improving quickly as a result of optical fiber and other broadband technologies.

3.5 Uses

Digital image processing allows the use of much more complex algorithms for image processing, and hence can offer both more sophisticated performance at simple tasks, and the implementation of methods which would be impossible by analog means.

In particular, digital image processing is the only practical technology for:

Classification Feature extraction Pattern recognition Projection Multi-scale signal analysis

3.6 Applications

Photography and printing Satellite image processing Medical image processing Face detection, feature detection, face identification Microscope image processing

Page 30: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

IMAGECOMPRESSION

Page 31: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 20

4.1 Introduction

In computer science and information theory, data compression or source coding is the process of encoding information using fewer bits (or other information-bearing units) than an un-encoded representation would use through use of specific encoding schemes. The article could be encoded with fewer bits if we accept the convention that the word "compression" be encoded as "comp". One popular instance of compression that many computer users are familiar with is the ZIP file format, which, as well as providing compression, acts as an archiver, storing many files in a single output file.

As is the case with any form of communication, compressed data communication only works when both the sender and receiver of the information understands the encoding scheme. The text makes sense only if the receiver understands that it is intended to be interpreted as characters representing the English language. Similarly, compressed data can only be understood if the decoding method is known by the receiver.

Further compression is possible if some loss of fidelity is allowable. A person viewing a picture or television video scene might not notice if some of its finest details are removed or not represented perfectly. Similarly, two strings of samples representing an audio recording may sound the same but actually not be exactly the same.

Compression is important because it helps reduce the consumption of expensive resources, such as disk space or connection bandwidth. However, compression requires information processing power, which can also be expensive. The design of data compression schemes therefore involves trade-offs between various factors including compression capability, any amount of introduced distortion, computational resource requirements, and often other considerations as well.

4.2 Information Theory Information theory is the mathematical theory of data communication and storage, generally considered to have been founded in 1948 by Claude E. Shannon. The central paradigm of classic information theory is the engineering problem of the transmission of information over a noisy channel. The most fundamental results of this theory are Shannon's source coding theorem, which establishes that on average the number of bits needed to represent the result of an uncertain event is given by the entropy; and Shannon's noisy-channel coding theorem, which states that reliable communication is possible over noisy channels provided that the rate of communication is below a certain threshold called the channel capacity. The channel capacity is achieved with appropriate encoding and decoding systems.

Information theory is closely associated with a collection of pure and applied disciplines that have been carried out under a variety of banners in different parts of the world over the past half century or more: adaptive systems, anticipatory systems, artificial intelligence, complex systems, complexity science, cybernetics,

Page 32: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 21

informatics, machine learning, along with systems sciences of many descriptions. Information theory is a broad and deep mathematical theory, with equally broad and deep applications, chief among them coding theory.

Coding theory is concerned with finding explicit methods, called codes, of increasing the efficiency and fidelity of data communication over a noisy channel up near the limit that Shannon proved is all but possible. These codes can be roughly subdivided into data compression and error-correction codes. It took many years to find the good codes whose existence Shannon proved. A third class of codes are cryptographic ciphers; concepts from coding theory and information theory are much used in cryptography and cryptanalysis; see the article on deciban for an interesting historical application.

Information theory is also used in information retrieval, intelligence gathering, gambling, statistics, and even musical composition.Coding theory is the most important and direct application of information theory. It can be subdivided into data compression theory and error correction theory. Using a statistical description for data, information theory quantifies the number of bits needed to describe the data. There are two formulations for the compression problem — in lossless data compression the data must be reconstructed exactly, whereas lossy data compression examines how many bits are needed to reconstruct the data to within a specified fidelity level. This fidelity level is measured by a function called a distortion function. In information theory this is called rate distortion theory. Both lossless and lossy source codes produce bits at the output which can be used as the inputs to the channel codes mentioned above.

The idea is to first compress the data, i.e. remove as much of its redundancy as possible, and then add just the right kind of redundancy (i.e. error correction) needed to transmit the data efficiently and faithfully across a noisy channel. This division of coding theory into compression and transmission is justified by the information transmission theorems, or source-channel separation theorems that justify the use of bits as the universal currency for information in many contexts. However, these theorems only hold in the situation where one transmitting user wishes to communicate to one receiving user. In scenarios with more than one transmitter (the multiple-access channel), more than one receiver (the broadcast channel) or intermediary "helpers" (the relay channel), or more general networks, compression followed by transmission may no longer be optimal. Network information theory refers to these multi-agent communication models.

4.3 Redundancy

The term data compression refers to the process of reducing the amount of data required to represent a given quantity of information. Data redundancy is a central issue in digital image compression. If n1 and n2 denote the number of information, the relative data redundancy RD of first data set can be defined as

RD = 1-1/CR

Where CR, commonly called the compression ratio, is

Page 33: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 22

CR = n1/ n2

For the case n1= n2, CR= 1 and RD = 0, indicating that the first representation of the information contains no redundant data. When n2 <<n1, CR and RD 1, implying significant compression and highly redundant data. Finally, when n2 >>n1, CR 0and RD -, indicating that the second data set contains much more data then the original representation.

In digital image compression, three basic data redundancies can be identified and exploited: coding redundancy, interpixel redundancy, and psychovisual redundancy. Data Compression is achieved when one or more of these redundancies are reduced or eliminated.

4.3.1 Coding Redundancy

Assigning fewer bits to the more probable gray levels than to less probable ones achieves data compression. This process commonly referred to as variable-length coding. If the gray levels of an image are coded in a way that uses more code symbols than absolutely necessary to represent each gray level, the resulting image is said to contain coding redundancy. In general, coding redundancy is present when the codes assigned to a set of events have not been selected to take full advantage of the probabilities of the events. It is almost always present when an image’s gray levels are represented with a straight or natural binary code. In this case, the underlying basis for the coding redundancy is that images are typically composed of objects that have a regular and somewhat predictable morphology and reflectance, and are generally sampled so that the objects being depicted are much larger than the picture elements. The natural consequence is that, in most images, certain gray levels are more probable than other. A natural binary coding of their gray levels assigns the same number of bits to both the most and least probable values, thus failing to minimize and resulting in coding redundancy.

4.3.2 Interpixel Redundancy

The value of any given pixel can be reasonably predicted from the value of its neighbors, the information carried by individual pixels is relatively small. Much of the visual contribution of a single pixel to an image is redundant; it could have been guessed on the basis of the values of its neighbors. A variety of names, including spatial redundancy, geometric redundancy, and inter frame redundancy, have been coined to refer to these interpixel dependencies. We use the term interpixel redundancy to encompass them all.

In order to reduce the interpixel redundancies in an image, the 2-D pixel array normally used for human viewing and interpretation must be transformed into a more efficient format. Transformations of this type are referred to as mappings. They are called reversible mappings if the original image elements can be reconstructed from the transformed data set.

Page 34: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 23

4.3.3 Psychovisual Redundancy

The brightness of a region, as perceived by the eye, depends on factors other than simply the light reflected by the region. For example, Intensity variations can be perceived in an area of constant intensity. Such phenomena results from the fact that the eye does not respond with equal sensitivity to all visual information. Certain information simply has less relative importance than other information in normal visual processing. This information is said to be psychovisually redundant. It can be eliminated without significantly impairing the quality of image perception.

The Psychovisual Redundancies exists should not come as a surprise, because human perception of the information in an image normally does not involve quantitative analysis of every pixel value in the image. In general, an observer searches for distinguishing features such as edges or textural regions and mentally combines them into recognizable groupings. The brain then correlates these groupings with prior knowledge in order to complete the image interpretation process.

Psychovisual Redundancy is fundamentally different from other the redundancies. Unlike coding and interpixel redundancy, Psychovisual Redundancy is associated with real or quantifiable visual information. Its elimination is possible only because the information itself is not essential for normal visual processing. Since the elimination of Psychovisual Redundant data results in a loss of quantitative information, it is commonly referred to as quantization. This terminology is consistent with normal usage of the word, which generally means the mapping of a broad range of input values to a limited number of output values. As it is an irreversible operation, quantization results in lossy data compression.

4.4 Image Compression

Image compression is the application of data compression on digital images. In effect, the objective is to reduce redundancy of the image data in order to be able to store or transmit data in an efficient form.

Image compression can be lossy or lossless. Lossless compression is sometimes preferred for artificial images such as technical drawings, icons or comics. This is because lossy compression methods, especially when used at low bit rates, introduce compression artifacts. Lossless compression methods may also be preferred for high value content, such as medical imagery or image scans made for archival purposes. Lossy methods are especially suitable for natural images such as photos in applications where minor loss of fidelity is acceptable to achieve a substantial reduction in bit rate.

4.5 Lossless Image Compression

Lossless Image Compression is a class of image compression algorithms that allows the exact original image to be reconstructed from the compressed image.Contrast with lossy data compression.

Page 35: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 24

Lossless compression is used when it is important that the original and the decompressed data be identical, or when no assumption can be made on whether certain deviation is uncritical. Typical examples are executable programs and source code. Some image file formats, notably PNG, use only lossless compression, while others like TIFF and MNG may use either lossless or lossy methods. GIF uses a lossless compression method, but most GIF implementations are incapable of representing full color, so they quantize the image to 256 or fewer colors before encoding as GIF. Color quantization is a lossy process, but reconstructing the color image and then re-quantizing it produces no additional loss. (Some rare GIF implementations make multiple passes over an image, adding 255 new colors on each pass.)

Lossless compression methods may be categorized according to the type of data they are designed to compress. The three main types of targets for compression algorithms are text, images, and sound. Whilst, in principle, any general-purpose lossless compression algorithm can be used on any type of data, many are unable to achieve significant compression on data that is not of the form that they are designed to deal with. Sound data, for instance, cannot be compressed well with conventional text compression algorithms.

Most lossless compression programs use two different kinds of algorithms: one which generates a statistical model for the input data, and another which maps the input data to bit strings using this model in such a way that "probable" (e.g. frequently encountered) data will produce shorter output than "improbable" data. Often, only the former algorithm is named, while the second is implied or unspecified. Methods for lossless image compression are:

Run-length encodingEntropy codingAdaptive dictionary algorithms such as LZW

4.5.1 Run-Length Encoding

Run-length encoding (RLE) is a very simple form of image compression in which runs of data (that is, sequences in which the same data value occurs in many consecutive data elements) are stored as a single data value and count, rather than as the original run. This is most useful on data that contains many such runs.

Consider a screen containing plain black text on a solid whitebackground. There will be many long runs of white pixels in the blank space, and many short runs of black pixels within the text. Let us take a hypothetical single scan line, with B representing a black pixel and W representing white:

WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW

If we apply a simple run-length code to the above hypothetical scan line, we get the following:

Page 36: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 25

12WB12W3B24WB14W

Interpret this as twelve W's, one B, twelve W's, three B's, etc. The run-length code represents the original 67 characters in only 16. Of course, the actual format used for the storage of images is generally binary rather than ASCII characters like this, but the principle remains the same. Even binary data files can be compressed with this method; file format specifications often dictate repeated bytes in files as padding space. However, newer compression systems often use deflation or other LZ77-based algorithms, which can take advantage of runs of strings of characters (such as BWWBWWBWWBWW).

Common formats for run-length encoded data include PackBits, PCXand ILBM. Run-length encoding performs lossless data compression and is well suited to palette-based iconic images. It does not work well at all on continuous-tone images such as photographs, although JPEG uses it quite effectively on the coefficients that remain after transforming and quantizing image blocks. Data that has long sequential runs of bytes can be RLE compressed after Delta encoding is applied to it.

4.5.2 Entropy Coding

An entropy encoding is a coding scheme that assigns codes to symbols so as to match code lengths with the probabilities of the symbols. Typically, entropy encoders are used to compress data by replacing symbols represented by equal-length codes with symbols represented by codes proportional to the negative logarithm of the probability. Therefore, the most common symbols use the shortest codes.

According to Shannon's theorem, the optimal code length for a symbol is −logbP, where b is the number of symbols used to make output codes and P is the probability of the input symbol. Three of the most common entropy encoding techniques are Huffman coding, range encoding, and arithmetic encoding. If the approximate entropy characteristics of a data stream are known in advance, a simpler static code such as unary coding, Elias gamma coding, Fibonacci coding, Golomb coding, or Rice coding may be useful.

4.5.3 Lempel-Ziv-Welch (LZW)

LZW (Lempel-Ziv-Welch) is an implementation of a lossless data compression algorithm created by Lempel and Ziv. It was published by Terry Welchin 1984 as an improved version of the LZ78 dictionary coding algorithm developedby Abraham Lempel and Jacob Ziv.

The key insight of the method is that it is possible to automatically build a dictionary of previously seen strings in the text being compressed. The dictionary does not have to be transmitted with the compressed text, since the decompressor can build it the same way the compressor does, and if coded correctly, will have exactly the same strings that the compressor dictionary had at the same

Page 37: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 26

point in the text. The dictionary starts off with 256 entries, one for each possible character (single byte string). Every time a string not already in the dictionary is seen, a longer string consisting of that string appended with the single character following it in the text is stored in the dictionary.

The output consists of integer indices into the dictionary. These initially are 9 bits each, and as the dictionary grows, can increase to up to 16 bits. A special symbol is reserved for "flush the dictionary" which takes the dictionary back to the original 256 entries, and 9 bit indices. This is useful if compressing a text which has variable characteristics, since a dictionary of early material is not of much use later in the text. This use of variably increasing index sizes is one of Welch's contributions. Another was to specify an efficient data structure to store the dictionary. In general, dictionary-based compression replaces phrases with tokens. If the number of bits in the token is less than the number of bits in the phrase, compression will occur.

Uncompressed text:

"I am dumb and because I am dumb, I can't even tell you that I am dumb."Compressed text:

"$1 and because $1, I can't even tell you that $1. $1= [I am dumb]"

This is very far from efficient, but it illustrates the compression through phrase replacement. The method became moderately widely used in the program "compress" which became a more or less standard utility in UNIX systems circa 1986. Several other popular compression utilities also used the method, or closely related ones. It became very widely used after it became part of the GIF image format in 1987. It may also be used in TIFF files. LZW compression provided a better compression ratio, in most applications, than any well-known method available up to that time. It became the first widely used general purpose data compression method on computers. On large English texts, it would typically compresses to about half the original size. Other kinds of data were also quite usefully compressed in many cases. Various patents have been issued in the USA and other countries for LZW and similar algorithms. LZ78 was covered by U.S. Patent 4,464,650 by Lempel, Ziv, Cohn, and Eastman, assigned to Sperry Corporation, later Unisys Corporation, filed on August 10, 1981, and presumably now expired.

US Patent 4,558,302 is the one that has caused the most controversy. Unisys at one time granted royalty-free patent licenses to developers of free softwareand freely available proprietary software; the company terminated those licenses in August 1999. Many legal experts have concluded that the patent does not cover devices that can only uncompress LZW data and cannot compress it; for this reason, the popular Gzip program can read ‘.Z’ files but cannot write them.

4.6 Lossy Image Compression

Unlike the error-free process discussed above, lossy encoding is based on the concept of compromising the accuracy of the reconstructed image in exchange for

Page 38: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 27

increased compression. If the resulting distortion can be tolerated, the increase in compression can be significant. In fact, many lossy encoding techniques are capable of reproducing recognizable monochrome images from data that have been compressed by more than 100:1 and images that are virtually indistinguishable from the originals at 10:1 to 50:1. Error-free encoding of monochrome images, however, seldom results in more than a 3:1 reduction in data. The principal difference between these two approaches is the presence or absence of the quantizer block. There are two basic lossy compression schemes:

In lossy transform codec’s, samples of picture or sound are taken, chopped into small segments, transformed into a new basis space, and quantized. The resulting quantized values are then entropy coded.

In lossy predictive codec’s, previous and/or subsequent decoded data is used to predict the current sound sample or image frame. The error between the predicted data and the real data, together with any extra information needed to reproduce the prediction, is then quantized and coded.

In some systems the two techniques are combined, with transform codec’s being used to compress the error signals generated by the predictive stage. Lossy Image Compression method is one where compressing image and then decompressing it retrieves image that may well be different from the original, but is "close enough" to be useful in some way. Methods for lossy compression:

Color spaceChroma Sub-Sampling. Transform Coding. Fractal Compression.

4.6.1 Color Space

A color model is an abstract mathematical model describing the way colors can be represented as tuples of numbers, typically as three or four values or color components (e.g. RGB and CMYK are color models). However, a color model with no associated mapping function to an absolute color space is a more or less arbitrary color system with little connection to the requirements of any given application.

Adding a certain mapping function between the color model and a certain reference color space results in a definite "footprint" within the reference color space. This "footprint" is known as a gamut, and, in combination with the color model, defines a new color space. Adobe RGB and sRGB are two different absolute color spaces, both based on the RGB model.

The RGB color model is implemented in different ways, depending on the capabilities of the system used. By far the most common general-use incarnation as of 2005 is the 24-bit implementation, with 8 bits, or 256 discrete levels of color per channel. Any color space based on such a 24-bit RGB model is thus limited to a gamut of 256×256×256 ≈ 16.7 million colors. Some implementations use 16 bits per

Page 39: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 28

component, resulting in the same range with a greater density of distinct colors. This is especially important when working with wide-gamut color spaces, or when a large number of digital filtering algorithms are used consecutively. The same principle applies for any color spaces based on the same color model, but implemented in different bit depths.

RGB uses additive color mixing, because it describes what kind of light needs to be emitted to produce a given color. Light is added together to create form from out of the darkness. RGB stores individual values for red, green and blue. RGBA is RGB with an additional channel, alpha, to indicate transparency. Common color spaces based on the RGB model include sRGB, Adobe RGB and Adobe Wide Gamut RGB.

Additive color mixing Subtractive color mixing

FIGURE: 4-1 Pictures of Additive color Mixing and Subtractive color mixing

CMYK uses subtractive color mixing used in the printing process, because it describes what kinds of inks need to be applied so the light reflected from the substrate and through the inks produces a given color. One starts with a white substrate (canvas, page, etc), and uses ink to subtract color from white to create an image. CMYK stores ink values for cyan, magenta, yellow and black. There are many CMYK color spaces for different sets of inks, substrates, and press characteristics (which change the dot gain or transfer function for each ink and thus change the appearance). YIQ is used in NTSC (North American) television broadcasts for historical reasons. YIQ stores a luminance value with two chrominance values, corresponding approximately to the amounts of blue and red in the color. It corresponds closely to the YUV scheme used in PAL television except that the YIQ color space is rotated 33° with respect to the YUV color space. The YDbDr scheme used by SECAM television is rotated in another way.

YPbPr is a scaled version of YUV. It is most commonly seen in its digital form, YCbCr, used widely in video and image compression schemes such as MPEG and JPEG. HSV (hue, saturation, value), also known as HSB (hue, saturation, brightness) is often used by artists because it is often more natural to think about a color in terms of hue and saturation than in terms of additive or subtractive color components. HSV is a transformation of an RGB colorspace, and its components and colorimetry are relative to the RGB colorspace from which it was derived. HSL (hue,

Page 40: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 29

saturation, lightness/luminance), also known as HLS or HSI (hue, saturation, intensity) is quite similar to HSV, with "lightness" replacing "brightness". The difference is that the brightness of a pure color is equal to the brightness of white, while the lightness of a pure color is equal to the lightness of a medium gray.

4.6.2 Chroma Sub-Sampling

In digital image processing, chroma subsampling is the use of lower resolution for the color (chroma) information in an image than for the brightness (intensity or luma) information. It is used when an analog component video or YUVsignal is digitally sampled.

Because the human eye is less sensitive to color than intensity, the chroma components of an image need not be as well defined as the luma component; so many video systems sample the color difference channels at a lower definition (i.e., sample frequency) than the brightness. This reduces the overall bandwidth of the video signal without much apparent loss of picture quality. The missing values will be interpolated or repeated from the preceding sample for that channel.

The subsampling in a video system is usually expressed as a three part ratio. The three terms of the ratio are: the number of brightness ("luminance" "luma" or Y) samples, followed by the number of samples of the two color ("chroma") components: U/Cb then V/Cr, for each complete sample area. For quality comparison, only the ratio between those values is important, so 4:4:4 could easily be called 1:1:1; however, traditionally the value for brightness is always 4, with the rest of the values scaled accordingly.

FIGURE: 4-2 Picture shows the three terms of the ratio are the number of brightness, the number of samples of the two color components U/Cb then V/Cr for each complete sample area

Sometimes, four part relations are written, like 4:2:2:4. In these cases, the fourth number means the sampling frequency ratio of a key channel. In virtually all cases, that number will be 4, since high quality is very desirable in keying applications.

4.6.3 Transform Coding

Transform coding is a type of data compression for "natural" data like audio signals or photographic images. The transformation is typically "lossy",

Page 41: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 30

resulting in a lower quality copy of the original input. In transform coding, knowledge of the application is used to choose information to discard, thereby lowering its bandwidth. The remaining information can then be compressed via a variety of methods. When the output is decoded, the result may not be identical to the original input, but is expected to be close enough for the purpose of the application.

One of the most successful transform encoding systems is typically not referred to as such -- the example being color television. After an extensive series of studies in the 1950s, Alda Bedford showed that the human eye has high resolution only for black and white, somewhat less for "mid-range" colors like yellows and greens, and much less for colors on the end of the spectrum, reds and blues. Using this knowledge allowed RCA to develop a system in which they discarded most of the blue signal after it comes from the camera, keeping most of the green and only some of the red. The result is a signal with considerably less content, one that would fit within existing 6MHz black-and-white signals. The average TV displays the equivalent of 350 pixels on a line, but the TV signal contains enough information for only about 50 pixels of blue and perhaps 150 of red. This is not apparent to the viewer in most cases, as the eye has sophisticated systems for "re-building" a sharp image based on clues from contrast and edges.

The term is much more commonly used in digital media. The common JPEG image format is an example of a transform coding, one that examines small blocks of the image and "averages out" the color using a discrete cosine transform to form an image with far fewer colors in total. MPEG modifies this across frames in a motion image, further reducing the size compared to a series of JPEGs. MPEG audio compression analyzes the transformed data according to a psychoacoustic model that describes the human ear's sensitivity to parts of the signal, similar to the TV model. The basic process of digitizing an analog signal is a kind of transform coding that uses sampling in one or more domains as its transform.

4.6.4 Fractal Compression

Fractal compression is a lossy compression method used to compress images using fractals. The method is best suited for photographs of natural scenes. The fractal compression technique relies on the fact that in certain images, parts of the image resemble other parts of the same image. Michael Barnsley is the principal researcher who has worked on fractal compression, and he holds several patents on the technology. The most widely known practical fractal compression algorithm was invented by Arnaud Jacquin in 1988, although Barnsley and Alan Sloan took out the patent (US. 5,065,447) on this method also.

Fractal compression appeared to be a promising technology in the late 1980s, when in some circumstances it appeared to compress much better than JPEG, its main competitor at that time. However, fractal compression never achieved widespread use. The patent issue may have been a problem (JPEG can be used without any patent royalties), and fractal compression is much slower to compress than JPEG. (JPEG decompression seems to take about the same time as fractal decompression). Also, the improved compression ratio may have been an illusion. Fractal compression only has a large advantage over JPEG at low image quality levels, which is usually undesirable. The claim that fractal compressed images, when

Page 42: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 31

enlarged beyond their original size, looked better than similarly enlarged JPEG images seems also to have been an irrelevant distinction.

4.7 Lossy vs. Lossless Compression

The advantage of lossy methods over lossless methods is that in some cases a lossy method can produce a much smaller compressed file than any known lossless method, while still meeting the requirements of the application. Lossy methods are most often used for compressing sound, images or videos. The compression ratio (that is, the size of the compressed file compared to that of the uncompressed file) of lossy video codec’s are nearly always far superior to those of the audio and still-image equivalents. Audio can be compressed at 1:10 with no noticeable loss of quality; video can be compressed immense amounts with little visible quality loss, eg: 300:1. Lossily compressed still images are often compressed to 1/10th their original size, as with audio, but the quality loss is more noticeable, especially on closer inspection. When a user acquires a lossily-compressed file, (for example, to reduce download-time) the retrieved file can be quite different to the original at the bit level while being indistinguishable to the human ear or eye for most practical purposes. Many methods focus on the idiosyncrasies of the human anatomy, taking into account, for example, that the human eye can see only certain frequencies of light. The psychoacoustic model describes how sound can be highly compressed without degrading the perceived quality of the sound. Flaws caused by lossy compression that are noticeable to the human eye or ear are known as compression artifacts.

(a) (b) (c)

FIGURE: 4-3 (a) Original Lena Image (12KB size), (b) Lena Image, Compressed (85% less information, 1.8KB), (c) Lena Image, Highly Compressed (96% less information, 0.56KB)

The above images show the use of lossy compression to reduce the file size of the image. The image is an excerpt of the image of Lena, a de facto industry-standard test image. The first picture is 12,249 bytes. The second picture has been compressed (JPEG quality 30) and is 85% smaller, at 1,869 bytes. Notice the loss of detail in the brim of the hat. The third picture has been highly compressed (JPEG quality 5) and is 96% smaller, at 559 bytes. The compression artifacts are much more noticeable. Even though the third image has high distortion, the face is still recognizable. Good lossy compression algorithms are able to throw away "less important" information and still retain the "essential" information.

Page 43: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 32

4.8 Scalability

Scalability generally refers to a quality reduction achieved by manipulation of the bit stream or file (without decompression and re-compression). Other names for scalability are progressive coding or embedded bit streams. Despite its contrary nature, scalability can also be found in lossless codes, usually in the form of coarse-to-fine pixel scans. Scalability is especially useful for previewing images while downloading them (e.g. in a web browser) or for providing variable quality access to databases. There are several types of scalability:

Quality progressive or layer progressive: The bit stream successively refines the reconstructed image.

Resolution progressive: First encode a lower image resolution; then encode the difference to higher resolutions.

Component progressive: First encode grey; then color.

Region of interest coding Certain parts of the image are encoded with higher quality than others. This can be combined with scalability (encode these parts first, others later).

Meta information Compressed data can contain information about the image which can be used to categorize, search or browse images. Such information can include color and texture statistics, small preview images and author/copyright information.

The quality of a compression method is often measured by the Peak signal-to-noise ratio. It measures the amount of noise introduced through a lossy compression of the image. However, the subjective judgement of the viewer is also regarded as an important, perhaps the most important measure.

4.9 Applications

One very simple means of compression is run-length encoding, wherein large runs of consecutive identical data values are replaced by a simple code with the data value and length of the run is an example of lossless data compression. It is often used to better use disk space on office computers, or better use the connection bandwidth in a computer network. For symbolic data such as spreadsheets, text, executable programs, etc., losslessness is essential because changing even a single bit cannot be tolerated (except in some limited cases).

For visual and audio data, some loss of quality can be tolerated without losing the essential nature of the data. By taking advantage of limitations of the human sensory system, a great deal of space can be saved while producing output which is nearly indistinguishable from the original. These lossy data compression methods typically offer a three-way tradeoff between compression speed, compressed data size and quality loss.

Page 44: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 33

Lossy image compression is used in digital cameras, greatly increasing their storage capacities while hardly degrading picture quality at all. Similarly, DVDs use the lossy MPEG-2 codec for video compression.

In lossy audio compression, methods of psychoacoustics are used to remove non-audible (or less audible) components of the signal. Compression of human speech is often performed with even more specialized techniques, so that "speech compression" or "voice coding" is sometimes distinguished as a separate discipline than "audio compression". Different audio and speech compression standards are listed under audio codec’s. Voice compression is used in Internet telephony for example, while audio compression is used for CD ripping and is decoded by MP3 players.

Page 45: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

MATLAB

Page 46: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 34

5.1 Introduction

MATLAB is a high-performance language for technical computing. It integrates computation, visualization, and programming in an easy-to-use environment where problems and solutions are expressed in familiar mathematical notation. Typical uses include the following:

• Math and computation

• Algorithm development

• Data acquisition

• Modeling, simulation, and prototyping

• Data analysis, exploration, and visualization

• Scientific and engineering graphics

• Application development, including graphical user interface building

MATLAB is an interactive system whose basic data element is an array that does not require dimensioning. This allows formulating solutions to many technical computing problems, especially those involving matrix representations, in a fraction of the time it would take to write a program in a scalar non-interactive language such as C or FORTRAN. The name MATLAB stands for MATRIX LABORATORY. MATLAB was written originally to provide easy access to matrix software developed by the LINPACK (Linear System Package) and EISPACK (Eigen System Package) projects. Today, MATLAB engines incorporate the LAPACK (Linear Algebra Package) and BLAS (Basic Linear Algebra Subprograms) libraries, constituting the state of the art in software for matrix computation. In university environments, MATLAB is the standard computational tool for introductory and advanced courses in mathematics, engineering, and science. In industry, MATLAB is the computational tool of choice for research, development, and analysis. MATLAB is complemented by a family of applicationspecific solutions called toolboxes. The Image Processing Toolbox is a collection of MATLAB functions (called M-functions or M-files) that extend the capability of the MATLAB environment for the solution of digital image processing problems. Other toolboxes that sometimes are used to complement IPT are the signal Processing, Neural Network, Fuzzy Logic, and Wavelet Toolboxes.1.3

5.2 The MATLAB Working Environment

MATLAB desktop is the main MATLAB application window. As shown below, the desktop contains five sub-windows: the Command Window, the Workspace Browser, the Current Directory Windows, the Command History Windows, and one or more Figure Windows, which are shown only when the user displays graphic.

The Command Window is where the user types MATLAB commands and expressions at the prompt (>>) and where the outputs of those commands are displayed. MATLAB defines the work space as the set of variables that the user creates in a work session. The Workspace Browser shows these variables and some information about

Page 47: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 35

them. Double clicking on a variable in the Work- space Browser launches the Array Editor, which can be used to obtain information and is some instances edit certain properties of the variable.

FIGURE: 5-1 The MATLAB desktop and its principal components.

The Current Directory tab above the workspace tab shows the contents of the current directory whose path is shown in the Current Directory Window. For example, in the Windows operating system the path might be as follows: D:\MATLAB\Work, indicating that directory “Work” is a subdirectory of the main directory “MATLAB”, which is installed in drive D. clicking on the arrow in the Current Directory Windows, shows a list of recently used paths. Clicking on the button to the right of the window allows the user to change the current directory. MATLAB uses a search path to find M-files and other MATLAB-related

files, which are organized in directories in the computer file system. Any file run in MATLAB must reside in the current directory or in a directory that is on the search path. By default, the files supplied with MATLAB and Math Works toolboxes are included in the search path. The easiest way to see which directories are on the search path, or to add or modify a search path, is to select Set Path from the File menu on the desktop, and then use the Set Path dialog box. It is good practice to add any commonly used directories to the search path to avoid repeatedly having the change the current directory.

The Command History Window contains a record of the commands a user has entered in the Command Window, including both current and previous MATLAB sessions. Previously entered MATLAB commands can be selected and re-executed from the Command History Window by right-clicking on a command or sequence of

Page 48: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 36

commands. This action launches a menu from which to select various options in addition to executing the commands. This is a useful feature when experimenting with various commands in a work session.

5.3 Using the MATLAB Editor to Create M-files

The MATLAB editor is both a text editor specialized for creating M-files and a graphical MATLAB debugger. The editor can appear in a window by itself, or it can be a sub-window in the desktop. M-files are denoted by the extension .m, as in pixeldup.m. The MATLAB editor window has numerous pull-down menus for tasks such as saving, viewing, and debugging files. Because it performs some simple checks and also uses color to differentiate between various elements of code, this text editor is recommended as the tool of choice for Writing and editing M-functions. To open the editor, type edit at the prompt in the Command Window. Similarly, typing edit filename at the prompt opens the M-file filename.m in an editor window, ready for editing. As noted earlier, the file must be in the current directory, or in a directory in the search path.

5.4 Getting Help

The principal way to get help online is to use the MATLAB Help Browser,opened as a separate window either by clicking on the question mark symbol (?) on the desktop toolbar, or by typing help browser at the prompt in the Command Window. The Help Browser is a Web browser integrated into the MATLAB desktop that displays Hypertext Markup Language (HTML) documents. The Help Browser consists of two panes, the help navigator pane, used to find information, and the display pane, used to view the information. Self-explanatory tabs on the navigator pane are used to perform a search. For example, help on a specific function is obtained by selecting the Search tab, selecting Function Name as the Search Type, and then typing in the function name in the Search for field. It is good practice to open the Help Browser at the beginning of a MATLAB session to have help readily available during code development or other MATLAB task. Another way to obtain help for a specific function is by typing doc followed by the function name at the command prompt. For example, typing doc formatdisplays documentation for the function called format in the display pane of the Help Browser. This command opens the browser if it is not already open.

M-functions have two types of information that can be displayed by theuser. The first is called the H1 line, which contains the function name and a one-line description. The second is a block of explanation called the Help text block . Typing help at the prompt followed by a function name displays both the H1 line and the Help text for that function in the Command Window. Occasionally, this information can be more up to date than the information in the Help browser because it is extracted directly from the documentation of the M-function in question. Typing lookfor followed by a keyword displays all the H1 lines that contain that keyword. This function is useful when looking for a particular topic without knowing the names of applicable functions. For example, typing lookfor edge at the prompt displays all the H1 lines containing that keyword. Because the H1 line contains the function name, it then becomes possible to look at specific functions using the other help methods. Typing lookfor edge –all at the prompt

Page 49: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 37

displays the H1 line of all functions that contain the word edge in either the H1 line or the Help text block. Words that contain the characters edge also are detected. For example, the H1 line of a function containing the word polyedge in the H1 line or Help text would also be displayed. It is common MATLAB terminology to use the term help page when referring to the information about an M-function displayed by any of the precedingapproaches, excluding lookfor. This is necessary either because of space limitations or to avoid deviating from a particular discussion more than is absolutely necessary. In these cases we simply introduce the syntax required to execute the function in the form required at that point.

5.5 Saving and Retrieving a Work Session There are several ways to save and load an entire work session (the contents of the Workspace Browser) or selected workspace variables in MATLAB. Thesimplest is as follows. To save the entire workspace, simply right-click on any blank space in theWorkspace Browser window and select Save Workspace As from the menu that appears.This opens a directory window that allows naming the file and selecting any folder in the system in which to save it. Then simply click Save. To save a selected variable from the Workspace, select the variable with a left click and then right-click on the highlighted area. Then select Save Selection As from the menu that appears. This again opens a window from which a folder can be selected to save the variable. To select multiple variables, use shiftclickor control-click in the familiar manner, and then use the procedure just described for a single variable. All files are saved in double-precision, binary format with the extension .mat. These saved files commonly are referred to as MAT-files. For example, a session named, say, mywork_2003_02_10, would appear as the MAT-file mywork_2003_02_10.mat when saved. Similarly, a saved image called final_image (which is a single variable in the workspace) willappear when saved as final_image.mat.

To load saved workspaces and/or variables, left-click on the folder icon onthe toolbar of the Workspace Browser window. This causes a window to open from which a folder containing the MAT-files of interest can be selected. Double-clicking on a selected MAT-file or selecting Open causes the contents of the file to be restored in the Workspace Browser window.

It is possible to achieve the same results described in the preceding paragraphs by typing save and load at the prompt, with the appropriate file names and path information. This approach is not as convenient, but it is used when formats other than those available in the menu method are required.

5.6 Reading images

5.6.1 IMREAD

A = IMREAD (FILENAME, FMT) reads a grayscale or color image from the file specified by the string FILENAME, where the string FMT specifies the

Page 50: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 38

format of the file. If the file is not in the current directory or in a directory in the MATLAB path, specify the full pathname of the location on your system. If IMREADcannot find a file named FILENAME, it looks for a file named FILENAME.FMT.

IMREAD returns the image data in the array A. If the file contains agrayscale image, A is a two-dimensional (M-by-N) array. If the file contains a color image, A is a three-dimensional (M-by-N-by-3) array. The class of the returned array depends on the data type used by the file format.

For most file formats, the color image data returned uses the RGB color space. For TIFF files, however, IMREAD can return color data that uses the RGB, CIELAB, ICCLAB, or CMYK color spaces. If the color image uses the CMYK color space, A is an M-by-N-by-4 array.

[X, MAP] = IMREAD (FILENAME, FMT) reads the indexed image in FILENAME into X and its associated colormap into MAP. Colormap values in the image file are automatically rescaled into the range [0, 1].

[...] = IMREAD (FILENAME) attempts to infer the format of the filefrom its content.

[...] = IMREAD (URL,) reads the image from an Internet URL. The URL must include the protocol type (e.g., "http://").

5.6.1.1 Data Types

In most of the image file formats supported by IMREAD, pixels are stored using 8 or fewer bits per color plane. If the file contains only 1 bit per pixel, the class of the output (A or X) is logical. When reading other files with 8 or fewer bits per color plane, the class of the output is uint8. IMREAD also supports reading 16-bit-per-pixeldata from BMP, PNG, JPEG, and TIFF files, as well as 12-bit JPEG files. For 12-bit JPEG and 16-bit JPEG, PNG, and TIFF image files, the class of the output (A or X) is uint16 and for 16-bit BMP image files, the class of the output is uint8.

5.6.1.1.1 TIFF-specific syntaxes

[...] = IMREAD (..., IDX) reads in one image from a multi-image TIFF file. IDX is an integer value that specifies the order that the image appears in the file. For example, if IDX is 3, IMREAD reads the third image in the file

[...] = IMREAD (...,'PixelRegion',{ROWS, COLS}) returns the sub-image specified by the boundaries in ROWS and COLS. In the case of tiled TIFF images, IMREAD will read only the appropriate tiles, improving memory efficiency and performance. ROWS and COLS must be either two or three element vectors. If two elements are provided, they denote the 1-based indices [START STOP]. If three elements are provided, the indices [START INCREMENT STOP] allow image downsampling.

Page 51: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 39

5.6.1.1.2 PNG-specific syntaxes

[...] = IMREAD (...,'BackgroundColor', BG) composites any transparent pixels in the input image against the color specified in BG. If BG is 'none', then no compositing is performed. Otherwise, if the input image is indexed, BG should be an integer in the range [1, P] where P is the colormap length. If the input image is grayscale, BG should be an integer in the range [0, 1]. If the input image is RGB, BG should be a three-element vector whose values are in the range [0, 1].

If the ALPHA output argument is used, then BG defaults to 'none' if not specified by the user. Otherwise, if the PNG file contains a background color chunk, that color is used as the default value for BG. If ALPHA is not used and the file does not contain a background color chunk, then the default value for BG is 1 for indexed images; 0 for grayscale images; and [0 0 0] for RGB images.

[A, MAP, ALPHA] = IMREAD (...) returns the alpha channel if one is present; otherwise ALPHA is []. Note that MAP may be empty if the file contains a grayscale or truecolor image.

5.6.1.1.3 HDF-specific syntaxes

[...] = IMREAD (..., REF) reads in one image from a multi-image HDF file. REF is an integer value that specifies the reference number used to identify the image. For example, if REF is 12, IMREAD reads the image whose reference number is 12. (Note that in an HDF file the reference numbers do not necessarily correspond with the order of the images in the file). If you omit this argument, IMREAD reads the first image in the file.

5.6.1.1.4 ICO- and CUR-specific syntaxes

[...] = IMREAD (..., IDX) reads in one image from a multi-image icon or cursor file. IDX is an integer value that specifies the order that the image appears in the file. For example, if IDX is 3, IMREAD reads the third image in the file. If you omit this argument, IMREAD reads the first image in the file.

[A, MAP ALPHA] = IMREAD (...) returns the AND mask for theresource, which can be used to determine the transparency information. For cursor files, this mask may contain the only useful data.

5.6.1.1.5 GIF-specific syntaxes

[...] = IMREAD (..., IDX) reads in one or more frames from a multiframe (i.e., animated) GIF file. IDX must be an integer scalar or vector of integer values. For example, if IDX is 3, IMREAD reads the third image in the file. If IDX is 1:5, only the first five frames will be returned.

[...] = IMREAD (...,'Frames' IDX) is the same as the syntax above except that IDX can be 'all'. In this case, all of the frames are read and returned in the order that they appear in the file.

Page 52: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 40

Note: Because of the way that GIF files are structured, all of the frames must be read when a particular frame is requested. Consequently, it is much faster to specify a vector of frames or 'all' for IDX than to call IMREAD in a loop when reading multiple frames from the same GIF file.

5.6.1.2 Supported file types

JPEG -- Any baseline JPEG image; JPEG images with some commonly used extensions; 8-bit and 12-bit lossy compressed RGB and grayscale images; 8-bit and 12-bitlossless compressed RGB images; 8-bit, 12-bit, and 16-bit lossless compressed grayscale images.

TIFF -- Any baseline TIFF image, including 1-bit, 8-bit, and 24-bit uncompressed images; 1-bit, 8-bit, and 24-bit images with packbits compression; 1-bit images withCCITT compression; 16-bit grayscale, 16-bit indexed, and 48-bit RGB images; 24-bit and 48-bit ICCLAB and CIELAB images; 32-bit and 64-bit CMYK images; and 8-bit tiled TIFF images with any compression and colorspace combination listed above.

GIF -- Any 1-bit to 8-bit GIF image.

BMP -- 1-bit, 4-bit, 8-bit, 16-bit, 24-bit, and 32-bit uncompressed images; 4-bit and 8-bit run-length encoded (RLE) images

PNG -- Any PNG image, including 1-bit, 2-bit, 4-bit, 8-bit, and 16-bit grayscale images; 8-bit and 16-bit indexed images; 24-bit and 48-bit RGB images

HDF -- 8-bit raster image datasets, with or without an associated colormap; 24-bit raster image datasets

PCX -- 1-bit, 8-bit, and 24-bit images

XWD -- 1-bit and 8-bit ZPixmaps; XYBitmaps; 1-bit XYPixmaps

ICO -- 1-bit, 4-bit, and 8-bit uncompressed images

CUR -- 1-bit, 4-bit, and 8-bit uncompressed images

RAS -- Any RAS image, including 1-bit bitmap, 8-bit indexed, 24-bit truecolor and 32-bit truecolor with alpha.

PBM -- Any 1-bit PBM image. Raw (binary) or ASCII (plain) encoded.

PGM -- Any standard PGM image. ASCII (plain) encoded with arbitrary color depth. Raw (binary) encoded with up to 16 bits per gray value.

PPM -- Any standard PPM image. ASCII (plain) encoded with arbitrary color depth. Raw (binary) encoded with up to 16 bits per color component.

Page 53: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 41

5.7 Displaying Images

5.7.1 IMSHOW

IMSHOW (I,N) displays the intensity image I with N discrete levels of gray. If you omit N, IMSHOW uses 256 gray levels on 24-bit displays, or 64 gray levels on other systems.

IMSHOW (I,[LOW HIGH]) displays I as a grayscale intensity image, specifying the data range for I. The value LOW (and any value less than LOW) displays as black, the value HIGH (and any value greater than HIGH) displays as white, andvalues in between display as intermediate shades of gray. IMSHOW uses the default number of gray levels. If you use an empty matrix ([]) for [LOW HIGH], IMSHOW uses[min(I(:)) max(I(:))]; the minimum value in I displays as black, and the maximum value displays as white.

IMSHOW (BW) displays the binary image BW. Values of 0 display as black, and values of 1 display as white.

IMSHOW(X, MAP) displays the indexed image X with the colormapMAP.

IMSHOW (RGB) displays the truecolor image RGB.

IMSHOW (..., DISPLAY_OPTION) displays the image, callingTRUESIZE if DISPLAY_OPTION is 'truesize', or suppressing the call to TRUESIZE if DISPLAY_OPTION is 'notruesize'. Either option string can be abbreviated. If you do not supply this argument, IMSHOW determines whether to call TRUESIZE based on the setting of the 'ImshowTruesize' preference.

IMSHOW(x, y,...) uses the 2-element vectors x and y to establish a nondefault spatial coordinate system, by specifying the image XData and YData. Note that x and y can have more than 2 elements, but only the first and last elements are actually used.

IMSHOW (FILENAME) displays the image stored in the graphics file FILENAME. IMSHOW calls IMREAD to read the image from the file, but the image data is not stored in the MATLAB workspace. The file must be in the current directory or on the MATLAB path.

H = IMSHOW (...) returns the handle to the image object created by IMSHOW. The input image can be of class logical, uint8, uint16, or double, and it must be nonsparse.

You can use the IPTSETPREF function to set several toolbox preferences that modify the behavior of IMSHOW:

'ImshowBorder' controls whether IMSHOW displays the image with a border around it.

Page 54: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 42

‘ImshowAxesVisible' controls whether IMSHOW displays the image with the axes box and tick labels.

'ImshowTruesize' controls whether IMSHOW calls the TRUESIZE function.

5.7.2 IMVIEW

IMVIEW Display image in the image viewer.

IMVIEW (I) displays the intensity image I.

IMVIEW (RGB) displays the truecolor image RGB.

IMVIEW(X, MAP) displays the indexed image X with colormap MAP.

IMVIEW (I, RANGE), where RANGE is a two-element vector [LOW HIGH], controls the black-to-white range in the displayed image. The value LOW (and any value less than LOW) displays as black, the value HIGH (and any value greater than HIGH) displays as white, and values in between display as intermediate shades of gray. RANGE can also be empty ([]), in which case IMVIEW displays the minimum value of I as black and the maximum value of I as white. In other words, IMVIEW(I,[]) isequivalent to IMVIEW(I,[min(I(:)) max(I(:))]).

IMVIEW (FILENAME) displays the image contained in the file specified by FILENAME. The file must contain an image that can be read by IMREAD. If the file contains multiple images, the first one will be displayed.

With no input arguments, IMVIEW displays a file chooser dialog so youcan select an image file interactively.

H = IMVIEW (...) returns a handle H to the tool. CLOSE (H) closes theimage viewer. IMVIEW CLOSE ALL closes all image viewers.

IMVIEW (...,'InitialMagnification', INITIAL_MAG), where INITIAL_MAG can be either 100 or 'fit', controls the initial magnification used to display the image. When INITIAL_MAG is set to 100, the image is displayed at 100% magnification. When it is set to 'fit', the entire image is scaled to fit in the viewer window. By default, the initial magnification is set to the value returned by IPTGETPREF('ImviewInitialMagnification').The input image can be of class logical, uint8, uint16, int16, or double.

Examples:

Imview ('board.tif')[X, map] = imread ('trees.tif');Imview (X, map)I = imread ('cameraman.tif');Imview (I)h = imview (I, [0 80]);

Page 55: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 43

close(h)

If you have multiple Image Viewer windows open and you want to close all of them, there are two ways to do it:

1. Use the command: IMVIEW CLOSE ALL

2. Go to the Window menu on the MATLAB Desktop and choose "Close All." Note, this will close all windows listed in the Window menu, not just Image Viewer windows.

You can also use the Window menu to navigate to a particular ImageViewer that you have open.

5.7.3 FIGURE

FIGURE Create figure window. FIGURE, by itself, creates a new figure window, and returns its handle. FIGURE (H) makes H the current figure, forces it to become visible, and raises it above all other figures on the screen. If Figure H does not exist, and H is an integer, a new figure is created with handle H. GCF returns the handle to the current figure.

5.8 Writing Images

5.8.1 IMWRITE

IMWRITE Write image to graphics file. IMWRITE (A, FILENAME, FMT) writes the image A to the file specified by FILENAME in the format specified by FMT.

A can be an M-by-N (grayscale image) or M-by-N-by-3 (color image)array. A cannot be an empty array. If the format specified is TIFF, IMWRITE can also accept an M-by-N-by-4 array containing color data that uses the CMYK color space.FILENAME is a string that specifies the name of the file. FMT is a string specifying the format of the file.

IMWRITE(X, MAP, FILENAME, FMT) writes the indexed image in X and its associated colormap MAP to FILENAME in the format specified by FMT. If X is of class uint8 or uint16, IMWRITE writes the actual values in the array to the file. If X is of class double, IMWRITE offsets the values in the array before writing, using uint8(X-1). MAP must be a valid MATLAB colormap. Note that most image file formats do notsupport colormaps with more than 256 entries.

IMWRITE (..., FILENAME) writes the image to FILENAME, inferring the format to use from the filename's extension. The extension must be one of the legal values for FMT.

IMWRITE (..., PARAM1, VAL1, PARAM2, VAL2,...) specifies parameters that control various characteristics of the output file. Parameters are currently supported for HDF, JPEG, TIFF, PNG, PBM, PGM, and PPM files.

Page 56: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 44

5.8.2 IMFINFO

IMFINFO Information about graphics file. INFO = IMFINFO(FILENAME,FMT) returns a structure whose fields contain information about an image in a graphics file. FILENAME is a string that specifies the name of thegraphics file, and FMT is a string that specifies the format of the file. The file must be in the current directory or in a directory on the MATLAB path. If IMFINFO cannot find afile named FILENAME, it looks for a file named FILENAME.FMT. The possible values for FMT are contained in the file format registry, which is accessed via the IMFORMATS command.

If FILENAME is a TIFF, HDF, ICO, GIF, or CUR file containing morethan one image, INFO is a structure array with one element for each image in the file. For example, INFO(3) would contain information about the third image in the file.

INFO = IMFINFO (FILENAME) attempts to infer the format of the file from its content. INFO = IMFINFO (URL,...) reads the image from an Internet URL. The URL must include the protocol type (e.g., "http://"). The set of fields in INFO depends on the individual file and its format. However, the first nine fields are always the same. These common fields are:

Filename A string containing the name of the file

FileModDate A string containing the modification date of the file

FileSize An integer indicating the size of the file in bytes

Format A string containing the file format, as specified by FMT; for formats with more than one possible extension (e.g., JPEG and TIFF files), the first variant in the registry is returned

FormatVersion A string or number specifying the file format version

Width An integer indicating the width of the image in pixels

Height An integer indicating the height of the image in pixels

BitDepth An integer indicating the number of bits per pixel

ColorType A string indicating the type of image; either 'truecolor' for a truecolor (RGB) image, 'grayscale' for grayscale intensity image, or 'indexed', for an indexed image

5.8.3 SIZE

SIZE Size of array. D = SIZE(X), for M-by-N matrix X, returns the two-element row vector D = [M, N] containing the number of rows and columns in the matrix. For N-D arrays, SIZE(X) returns a 1-by-N vector of dimension lengths. Trailing singleton dimensions are ignored. [M, N] = SIZE(X) for matrix X, returns the number of rows and columns in X as separate output variables. [M1, M2, M3,..., MN] = SIZE(X)

Page 57: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 45

returns the sizes of the first N dimensions of array X. If the number of output arguments N does not equal NDIMS(X), then for:

N > NDIMS(X), size returns ones in the "extra" variables, i.e., outputs NDIMS(X)+1 through N. N < NDIMS(X), MN contains the product of the sizes of the remaining dimensions, i.e., dimensions N+1 through NDIMS(X).

M = SIZE(X, DIM) returns the length of the dimension specified by the scalar DIM. For example, SIZE(X, 1) returns the number of rows.

5.9 Data Classes

CLASS Create object or return object class. C = CLASS (OBJ) returns the class of the object OBJ. Possibilities are:

Double -- Double precision floating point number array (this is the traditional

MATLAB matrix or array)

Single -- Single precision floating point number array

Logical -- Logical array

Char -- Character array

Cell -- Cell array

Struct -- Structure array

function_handle -- Function Handle

int8 -- 8-bit signed integer array

uint8 -- 8-bit unsigned integer array

int16 -- 16-bit signed integer array

uint16 -- 16-bit unsigned integer array

int32 -- 32-bit signed integer array

uint32 -- 32-bit unsigned integer array

int64 -- 64-bit signed integer array

uint64 -- 64-bit unsigned integer array

<class_name> -- Custom object class

<java_class> -- Java class name for java objects

All other uses of CLASS must be invoked within a constructor method, in a file named <class_name>.m in a directory named @<class_name>. Further, 'class_name' must be the second argument to CLASS.

Page 58: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 46

5.10 Arithmetic Operators

Plus - Plus +Uplus - Unary plus +Minus - Minus -Uminus - Unary minus -Mtimes - Matrix multiply *Times - Array multiply .*Mpower - Matrix power ^Power - Array power .^Mldivide - Backslash or left matrix divide \Mrdivide - Slash or right matrix divide /Ldivide - Left array divide .\Rdivide - Right array divide ./Kron - Kronecker tensor product kron

5.11 Relational OperatorsEq - Equal ==Ne - Not equal ~=Lt - Less than <Gt - Greater than >Le - Less than or equal <=Ge - Greater than or equal >=

5.12 Logical OperatorsShort-circuit logical AND &&Short-circuit logical OR ||And - Element-wise logical AND &Or - Element-wise logical OR |Not - Logical NOT ~

Xor - Logical EXCLUSIVE OR

Any - True if any element of vector is nonzero

All - True if all elements of vector are nonzero

Page 59: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 47

5.13 Special CharactersColon - Colon :Paren - Parentheses and subscripting ( )Paren - Brackets [ ]Paren - Braces and subscripting { }Punct - Function handle creation @Punct - Decimal point .Punct - Structure field access .Punct - Parent directory ..Punct - Continuation ...Punct - Separator ,Punct - Semicolon ;Punct - Comment %Punct - Invoke operating system command!Punct - Assignment =Punct - Quote 'Transpose - Transpose .'Ctranspose - Complex conjugate transpose 'Horzcat - Horizontal concatenation [,]Vertcat - Vertical concatenation [;]Subsasgn - Subscripted assignment ( ),{ },.Subsref - Subscripted reference ( ),{ },.

Subsindex - Subscript index

5.14 Bitwise Operators

Bitand - Bit-wise AND.

Bitcmp - Complement bits.

Bitor - Bit-wise OR.

Bitmax - Maximum floating point integer.

Bitxor - Bit-wise XOR.

Bitset - Set bit.

Bitget - Get bit.

Page 60: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 48

Bitshift - Bit-wise shift.

5.15 Set Operators

Union - Set union.

Unique - Set unique.

Intersect - Set intersection.

Setdiff - Set difference.

Setxor - Set exclusive-or.

Ismember - True for set member

5.16 Flow control

5.16.1 IF

IF Conditionally execute statements. The general form of the IF statement is

IF expressionstatementsELSEIF expressionstatementsELSEstatementsEND

The statements are executed if the real part of the expression has all non-zero elements. The ELSE and ELSEIF parts are optional. Zero or more ELSEIF parts can be used as well as nested IF's. The expression is usually of the form expr rop expr where rop is ==, <, >, <=, >=, or ~=.

Exampleif I == JA(I,J) = 2;elseif abs(I-J) == 1A(I,J) = -1;elseA(I,J) = 0;End

5.16.2 FOR

FOR Repeat statements a specific number of times. The general form of a FOR statement is:

FOR variable = expr, statement, ..., statement END

Page 61: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 49

The columns of the expression are stored one at a time in the variable and then the following statements, up to the END, are executed. The expression is often of the form X:Y, in which case its columns are simply scalars. Some examples (assume N has already been assigned a value).

FOR I = 1:N,FOR J = 1:N,A(I,J) = 1/(I+J-1);ENDEND

FOR S = 1.0: -0.1: 0.0, END steps S with increments of -0.1FOR E = EYE(N), ... END sets E to the unit N-vectors.

Long loops are more memory efficient when the colon expression appearsin the FOR statement since the index vector is never created. The BREAK statement can be used to terminate the loop prematurely.

5.16.3 While

WHILE Repeat statements an indefinite number of times. The general form of a WHILE statement is:

WHILE expressionstatementsEND

The statements are executed while the real part of the expression has all non-zero elements. The expression is usually the result of expr rop expr where rop is ==, <, >, <=, >=, or ~=. The BREAK statement can be used to terminate the loop prematurely.

Example:

E = 0*A; F = E + eye(size(E)); N = 1;while norm(E+F-E,1) > 0,E = E + F;F = A*F/N;N = N + 1;end

5.16.4 Break

BREAK Terminate execution of WHILE or FOR loop. BREAKterminates the execution of FOR and WHILE loops. In nested loops, BREAK exits from the innermost loop only. BREAK is not defined outside of a FOR or WHILE loop. Use RETURN in this context instead.

Page 62: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 50

5.16.5 Continue

CONTINUE Pass control to the next iteration of FOR or WHILE loop. CONTINUE passes control to the next iteration of FOR or WHILE loop in which it appears, skipping any remaining statements in the body of the FOR or WHILE loop. In nested loops, CONTINUE passes control to the next iteration of FOR or WHILE loop enclosing it.

5.16.6 Return

RETURN Return to invoking function. RETURN causes a return to the invoking function or to the keyboard. It also terminates the KEYBOARD mode. Normally functions return when the end of the function is reached. A RETURNstatement can be used to force an early return.

Examplefunction d = det(A)if isempty(A)d = 1;returnelse...End

5.17 Some Special key Words

5.17.1 Function

FUNCTION Add new function. New functions may be added to MATLAB's vocabulary if they are expressed in terms of other existing functions. Thecommands and functions that comprise the new function must be put in a file whose name defines the name of the new function, with a filename extension of '.m'. At the top of the file must be a line that contains the syntax definition for the new function. For example, the existence of a file on disk called STAT.M with:

function [mean, stdev] = stat(x)%STAT Interesting statistics.n = length(x);mean = sum(x) / n;stdev = sqrt (sum((x - mean).^2)/n);

defines a new function called STAT that calculates the mean and standard deviation of a vector. The variables within the body of the function are all local variables. A sub-function that is visible to the other functions in the same file is created by defining a new function with the FUNCTION keyword after the body of the

Page 63: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 51

preceding function or sub-function. For example, avg is a sub-function within the file STAT.M:

function [mean, stdev] = stat(x)%STAT Interesting statistics.n = length(x);mean = avg(x,n);stdev = sqrt(sum((x-avg(x,n)).^2)/n);

%-------------------------function mean = avg(x,n)%AVG subfunctionmean = sum(x)/n;

Sub-functions are not visible outside the file where they are defined.Normally functions return when the end of the function is reached. A RETURN statement can be used to force an early return.

5.17.2 Rem

REM Remainder after division. REM(x,y) is x - n.*y where n = fix(x./y)if y ~= 0. If y is not an integer and the quotient x./y is within roundoff error of an integer,then n is that integer. By convention, REM(x,0) is NaN. The input x and y must be real arrays of the same size, or real scalars. REM(x,y) has the same sign as x while MOD(x,y)has the same sign as y. REM(x,y) and MOD(x,y) are equal if x and y have the same sign, but differ by y if x and y have different signs.

5.17.3 Fix

FIX Round towards zero. FIX(X) rounds the elements of X to the nearest integers towards zero

5.17.4 Round

ROUND Round towards nearest integer. ROUND(X) rounds the elements of X to the nearest integers.

5.17.5 COSINE Function

COS Cosine. COS(X) is the cosine of the elements of X.

5.17.6 Quantizer

QUANTIZER Constructor for QUANTIZER object. Q = QUANTIZER creates a Quantizer with all default values. Q = QUANTIZER (Value1, Value2, ... ) creates a QUANTIZER object with values Value1, Value2, .... If two values conflict, then the last value in the list is the one that is set. Q = QUANTIZER(a) where a is a structure whose field names are object property names, sets the properties named in

Page 64: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 52

each field name with the values contained in the structure. Q = QUANTIZER (pn ,pv)sets the named properties specified in the cell array of strings pn to the corresponding values in the cell array pv. Q = QUANTIZER ('Property1',Value1, 'Property2',Value2,...) assigns values associated with named properties. It is permissible to use property/value string pairs, structures, and property/value cell array pairs in the same call to SET.

Values sorted by property name:

'Mode'

'Double' - Double-precision mode. Override all other parameters.

'Float' - Custom-precision floating-point mode.

'Single' - Single-precision mode. Override all other parameters.

'Fixed' - Signed fixed-point mode.

'Ufixed' - Unsigned fixed-point mode.

'Roundmode'

‘Ceil’ - Round towards positive infinity.

'Convergent' - Convergent rounding.

'Fix' - Round towards zero.

'Floor' - Round towards negative infinity.

'Round' - Round towards nearest.

'Overflowmode' (fixed-point only)

'Saturate' - Saturate at max value on overflow.

'Wrap' - Wrap on overflow.

'Format'

[Wordlength fractionlength] - The format for fixed and ufixed mode.

[Wordlength exponentlength] - The format for float mode.

Besides properties, a QUANTIZER object also has states 'max', 'min', 'noverflows', 'nunderflows', 'noperations'. They can be accessed through QUANTIZER/GET or Q.max, Q.min, Q.noverflows, Q.nunderflows, but they cannot be set. They are updated during the QUANTIZER/QUANTIZE method, and are reset by the QUANTIZER/RESET method.

States

'Max' - Maximum value before quantizing.

'Min' - Minimum value before quantizing.

'Noverflows' - Number of overflows.

'Nunderflows' - Number of underflows.

Page 65: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 53

'Noperations' - Number of elements quantized.

Example:

q = Quantizer ('fixed', 'ceil', 'saturate', [5 4])

5.17.7 Num2bin

NUM2BIN Number to binary string. B = NUM2BIN (Q,X) converts numeric matrix X to binary string B. The attributes of the number are specified by Quantizer object Q. If X is a cell array containing numeric matrices, then B will be a cell array of the same dimension containing binary strings. The fixed-point binary representation is two's complement. The floating-point binary representation is IEEE style.

[B1,B2,...] = NUM2BIN(Q,X1,X2,...) converts numeric matrices X1, X2,... to binary strings B1, B2, .... NUM2BIN and BIN2NUM are inverses of each other, except that NUM2BIN always returns a column. For example, all of the 3-bit fixed-point two's complement numbers in fractional form are given by:

q = Quantizer([3 2]);x = [0.75 -0.250.50 -0.500.25 -0.750 -1 ];b = num2bin (q, x)

x = bin2num(q,b)

5.17.8 Clear

CLEAR Clear variables and functions from memory.

CLEAR removes all variables from the workspace.

CLEAR VARIABLES does the same thing.

CLEAR GLOBAL removes all global variables.

CLEAR FUNCTIONS removes all compiled M- and MEX-functions.

CLEAR ALL removes all variables, globals, functions and MEX links.

CLEAR ALL at the command prompt also removes the Java packages import list.

CLEAR IMPORT removes the Java packages import list at the command prompt. It cannot be used in a function.

CLEAR CLASSES is the same as CLEAR ALL except that class definitions are also cleared. If any objects exist outside the workspace (say in userdata or persistent in a

Page 66: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 54

locked m-file) a warning will be issued and the class definition will not be cleared. CLEAR CLASSES must be used if the number or names of fields in a class are changed.

CLEAR JAVA is the same as CLEAR ALL except that java classes on the dynamic java path (defined using JAVACLASSPATH) are also cleared.

CLEAR VAR1 VAR2 ... clears the variables specified. The wildcard character '*' can be used to clear variables that match a pattern. For instance, CLEAR X* clears all the variables in the current workspace that start with X.

CLEAR -REGEXP PAT1 PAT2 can be used to match all patterns using regularexpressions. This option only clears variables.

If X is global, CLEAR X removes X from the current workspace, but leaves it accessible to any functions declaring it global. CLEAR GLOBAL X completely removes the global variable X. CLEAR GLOBAL -REGEXP PAT removes global variables that match regularexpression patterns. Note that to clear specific global variables, the GLOBAL option must come first. Otherwise, all global variables will be cleared.

CLEAR FUN clears the function specified. If FUN has been locked by MLOCK it will remain in memory. Use a partial path to distinguish between different overloaded versions of FUN. For instance, 'clear inline/display' clears only the INLINE method forDISPLAY, leaving any other implementations in memory.

CLEAR ALL, CLEAR FUN, or CLEAR FUNCTIONS also have the side effect ofremoving debugging breakpoints and reinitializing persistent variables since the breakpoints for a function and persistent variables are cleared whenever the m-file changes or is cleared.

Use the functional form of CLEAR, such as CLEAR('name'), when the variable name or function name is stored in a string.

Examples for pattern matching

clear a* % Clear variables starting with "a"clear -regexp ^b\d{3}$ % Clear variables starting with "b" and% followed by 3 digitsclear -regexp \d % Clear variables containing any digits

Page 67: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG

Page 68: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 55

6.1 Introduction

The CCITT and ISO have defined several continuous tone (as opposed to binary) image compression standards. These standards, which are in various phases of the adoption process, address both monochrome and color image compression. In contrast to the binary compression standards, continuous tone standards are based principally on the lossy transform coding techniques. To develop the standards, CCITT and ISO committees solicited algorithm recommendations from a large number of companies, universities, and research laboratories. The best of those submitted were selected on the basis of image quality and compression performance. The resulting standards, which include the original DCT-based JPEG standard, the recently proposed wavelet-based JPEG 2000 standard, and the JPEG-LS standard, a lossless to near lossless adaptive prediction scheme that includes a mechanism for flat region detection and run-length coding(ISO/IEC[1999]), represent the state of the art in continuous tone image compression.

6.2 JPEG

In computing, JPEG (pronounced jay-peg) is a most commonly used standard method of lossy compression for photographic images. The file format which employs this compression is commonly also called JPEG; the most common file extensions for this format are .jpeg, .jfif, .jpg, .JPG, or .JPE although .jpg is the most common on all platforms.

The name stands for Joint Photographic Experts Group. JPEG itself specifies only how an image is transformed into a stream of bytes, but not how those bytes are encapsulated in any particular storage medium. A further standard, created by the Independent JPEG Group, called JFIF (JPEG File Interchange Format) specifies how to produce a file suitable for computer storage and transmission (such as over the Internet) from a JPEG stream. In common usage, when one speaks of a "JPEG file" one generally means a JFIF file, or sometimes an Exif JPEG file. There are, however, other JPEG-based file formats, such as JNG, and the TIFF format can carry JPEG data as well.JPEG/JFIF is the format most used for storing and transmitting photographs on the World Wide Web. It is not as well suited for line drawings and other textual or iconic graphics because its compression method performs badly on these types of images (the PNG and GIF formats are in common use for that purpose; GIF, having only 8 bits per pixel is not well suited for color photographs, PNG can be used to losslessly store photographs but the file size makes it largely unsuitable for putting photographs on the web).

6.2.1 Overview JPEG includes two classes of encoding and decoding processes:Lossless process -- Prediction-basedLossy process -- DCT-based, is sufficient for many applications

Page 69: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 56

6.3 Lossless process

In numerous applications error-free or lossless compression is the only acceptable means of data reduction. One such application is the archival of medical or business documents, where lossy compression usually is prohibited for legal reasons. Another is the processing of satellite imagery, where both the use and cost of collecting the data makes any loss undesirable. Yet another is digital radiography, where the loss of information can compromise diagnostic accuracy. In these and other cases, the need for error-free compression is motivated by the intended use or nature of the images under consideration. Error free compressions generally provide compression ratios of 2 to 10. Moreover, they are equally applicable to both binary and gray-scale images. The following are some of the error-free or lossless compression coding techniques:

1. Variable-length Coding

Huffman coding

Arithmetic coding

2. LZW Coding

3. Bit-Plane Coding

Constant area coding

One-dimensional coding

Two- dimensional run-length coding

Contour tracing and coding

4. Lossless Predictive Coding

6.4 Lossy process

Unlike the error-free process, lossy encoding is based on the concept of compromising the accuracy of the reconstructed image in exchange for increased compression. If the resulting distortion can be tolerated, the increase in compression can be significant. In fact, many lossy encoding techniques are capable of reproducing recognizable monochrome images from data that have been compressed by more than 100:1 and images that are virtually indistinguishable from the originals at 10:1 to 50:1. Error-free encoding of monochrome images, however, seldom results in more than a 3:1 reduction in data. The principal difference between these two approaches is the presence or absence of the quantizer block.

6.4.1 Lossy Predictive Coding

In this we add a quantizer and examine the trade-off between reconstruction accuracy and compression performance. The quantizer, which absorbs the nearest integer function of the error-free encoder, is inserted between the symbol

Page 70: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 57

encoder and the point at which the prediction error is formed. It maps the prediction error in to a limited range of outputs, which establish the amount of compression and distortion associated with lossy predictive coding. Delta modulation and DPCM are the two simple but well-known form of lossy predictive coding.

6.4.2 Transform Coding

The predictive coding techniques operate directly on the pixels of an image and thus are spatial domain methods. Now we consider a compression technique that is based on modifying the transform of an image. In transform coding, a reversible, linear transform (such as the Fourier transform) is used to map the image in to set of transform coefficients, which are then quantized and coded. For most natural images, a significant number of the coefficients have small magnitudes and can be coarsely quantized with little image distortion. A variety of transformations, including the discrete Fourier transform (DFT) can be used to transform the image data.

FIGURE: 6-1 Shows A transform coding system

Transform T(x) usually invertible

Quantization Q(y) not invertible, introduces distortion

Combination of encoder C(q) and decoder C -1(c) lossless

The decoder implements the inverse sequence of steps of the encoder, which performs four relatively straightforward operations: subimage decomposition, transformation, quantization, and coding. An N X N input image first is subdivided in to images of size n x n, which are then transformed to generate (N/n)2 subimage transform arrays, each of size n X n. The goal of the transformation process is to decorrelate the pixels of each subimage, or to pack as much information as possible in to the smallest number of transform coefficients. The quantization stage then selectively eliminates or more coarsely quantizes the coefficients that carry the least information. These coefficients have the smallest impact on reconstructed subimage quality. The encoding process terminates by coding the quantized coefficients. Any or all of the transform encoding steps can be adapted to local image content, called adaptive transform coding, or fixed for all subimages, called non adaptive transform coding.

Page 71: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 58

6.4.2.1 Transform selection

Transform coding systems based on a variety of discrete 2-D transforms have been constructed and/or studied extensively. The choice of a particular transform in a given application depends on the amount of reconstruction error that can be tolerated and the computational resources available. Compression is achieved during the quantization of the transformed coefficients (not during the transformation step).

6.4.2.2 Karhunen Loève Transform (KLT)

Karhunen Loève Transform (KLT) basis functions are Eigen vectors of the covariance matrix RXX of the input signal. KLT yields de-correlated transform coefficients (covariance matrix RYY is diagonal). KLT achieves optimum energy concentration. KLT maximizes coding gain GT

6.4.2.2.1 Disadvantages of KLT

KLT dependent on signal statistics

KLT not separable for image blocks

Transform matrix cannot be factored into sparse matrices

FIGURE: 6-2 Shows Comparison of various transforms I

6.4.2.3 Discrete Fourier transform

Transform coding of images using the Discrete Fourier Transform (DFT): For stationary image statistics, the energy concentration properties of the DFT converge against those of the KLT for large block sizes.

Page 72: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 59

Problem of block wise DFT coding: blocking effects due to circular topology of the DFT and Gibbs phenomena.

Remedy: reflect image at block boundaries, DFT of larger symmetric block

FIGURE: 6-3 Shows Comparison of various transforms II and Energy concentration measured for typical natural images, block size 1x32 and KLT is optimum and DCT performs only slightly

worse than KLT.

FIGURE: 6-4 Shows Coding gain with 8x8 transforms

FIGURE: 6-5 Shows Edge folded and pixel folded

Page 73: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 60

6.5 Discrete cosine transform

Type II-DCT of block size N x N is defined by transform matrix A containing elements

FIGURE 6-6 The 8 x 8 array of basis images for the two-dimensional discrete cosine transform.

6.5.1 Amplitude distribution of the DCT coefficients:

FIGURE : 6-7 Shows Amplitude distribution of DCT co-efficient

Histograms for 8x8 DCT coefficient amplitudes measured for natural images

DC coefficient is typically uniformly distributed.

Page 74: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 61

For the other coefficients, the distribution resembles a Laplacian PDF.

6.6 Transform coding

Purpose of transform is de-correlation and energy concentration

KLT is optimum, but signal dependent and, hence, without a fast algorithm

DCT shows reduced blocking artifacts compared to DFT

8x8 block size, uniform quantization, zig-zag-scan along with run level coding is

widely used today (e.g. JPEG, MPEG, ITU-T H.261, H.263)

Transformations that redistribute or pack the most information in to the fewest coefficients provide the best subimage approximations and, consequently the smallest reconstruction errors. Therefore Karhunen Loève Transform, not the DCT, is the optimal transform in an information packing sense. That is, the KLT minimizes the mean-square error for any input image and any number of retained coefficients. However, because the KLT is data dependent, obtaining the KLT basis images for each subimage, in general, is a nontrivial computational task. For this reason, the KLT is seldom used in practice for image compression. Instead, a transform, such as the DFT, WHT, or DCT, whose basis images are fixed (input independent), normally is used. Of the possible input independent transforms, the nonsinusoidal transforms (such as the WHT transform) are the simplest to implement. The sinusoidal transforms (such as DFT or DCT) more closely approximate the information packing ability of the optimal KLT.

Hence many transform coding systems are based on the DCT, which provides a good compromise between information packing ability and computational complexity. In fact, the properties of the DCT have proved to be of such practical value that the DCT has become an international standard for transform coding systems. Compared to the other input independent transforms, it has the advantages of having been implemented in a single integrated circuit, packing the most information in to fewest coefficients (for most natural images), and minimizing the block like appearance, called blocking artifact, that results when the boundaries between subimages become visible. This last property is particularly important in comparisons with the other sinusoidal transforms.

6.6.1 Subimage size selection

Another significant factor affecting transform coding error and computational complexity is subimage size. In most applications, images are subdivided so that the correlation (redundancy) between adjacent subimages is reduced to some acceptable level and so that n is an integer power of 2 where, as before, n is the subimage dimension. The latter condition simplifies the computation of the subimage transforms. In general, both the level of compression and computational complexity increase as the subimage size increases. The most popular subimage sizes are 8 x 8 and 16 x 16.

Page 75: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 62

FIGURE:6-8 Shows a 8x8 image and a 16x16 image respectively

6.6.2 Bit allocation

In most transform coding systems, the retained coefficients are selected [that is, the masking function is constructed] on the basis of maximum variance, called zonal coding, or on the basis of maximum magnitude, called threshold coding. The overall process of truncating, quantizing, and coding the coefficients of a transformed subimage is commonly called bit allocation.

γ (u, v) =0 if T (u, v) satisfies a specified truncation function

=1 otherwise ---Eq (6.1)

6.6.3 Zonal coding implementation

Zonal coding is based on the information theory concept of viewing information as uncertainty. Therefore the transform coefficients of maximum variance carry the most image information and should be retained in the coding process. The variances themselves can be calculated directly from the ensemble of (N/n)2 transformed subimage arrays, based on an assumed image model(say a Markov auto correlation function). In this case, the zonal sampling process can be viewed, in accordance with

Ĝ =Σ Σ γ (u, v) T (u, v) Huv ---Eq (6.2)

Where Ĝ is an approximation of G (G is an n x n matrix containing the pixels of f(x, y)) as multiplying each T (u, v) by the corresponding element in a zonal mask, which is constructed by placing a 1 in the locations of maximum variance and a 0 in all other locations. Coefficients of maximum variance usually are located around the origin of an image transform, resulting in the typical zonal mask shown

FIGURE 6-9 Shows the typical zonal mask

1 1 1 1 1 0 0 01 1 1 1 0 0 0 01 1 1 0 0 0 0 01 1 0 0 0 0 0 01 0 0 0 0 0 0 00 0 0 0 0 0 0 00 0 0 0 0 0 0 00 0 0 0 0 0 0 0

Page 76: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 63

The coefficients retained during the zonal sampling process must be quantized and coded, so zonal masks are sometimes depicted showing the number of bits used to code each coefficient

FIGURE 6-10 Shows zonal bit allocation

In most cases, the coefficients are allocated the same number of bits, or some fixed number of bits is distributed among them unequally. In the first case, the coefficients generally are normalized by their standard deviations and uniformly quantized. In the second case, a quantizer, such as an optimal Lloyd-Max quantizer, is designed for each coefficient. To construct the required quantizers, the zeroth or dc coefficient normally is modeled by a Rayleigh density function, whereas the remaining coefficients are modeled by a Laplacian or Gaussian density. The number of quantization levels (and thus the number of bits) allotted to each quantizer is made proportional to log2 σ2

T(u, v). This allocation is consistent with rate distortion theory, which indicates that a Gaussian random variable of variance σ2 cannot be represented by less than ½ log2 (σ

2/D) bits and be reproduced with mean-square error less than D. The intuitive conclusion is that the information content of a Gaussian random variable is proportional to log2 (σ

2/D). Thus the retained coefficients in Eq. (6.2) –which are selected on the basis of maximum variance—should be assigned bits in proportion to the logarithm of the coefficient variances.

6.6.4 Threshold coding implementation

Zonal coding usually is implemented by using a single fixed mask for all subimages. Threshold coding, however, is inherently adaptive in the sense that the location of the transform coefficients retained for each subimage vary from one subimage to another. In fact, threshold coding is adaptive transform coding approach most often used in practice because of its computational simplicity. The underlying concept is that, for any subimage, the transform coefficients of largest magnitude make the most significant contribution to reconstructed subimage quality. Because the locations of the maximum coefficients vary from one subimage to another, the elements of γ (u, v) T (u, v) normally are recorded to form a 1-D, run-length coded sequence. Figure 6.11 shows a typical threshold mask for one sub-image of a hypothetical image. This mask provides a convenient way to visualize the threshold coding process for the corresponding sub-image, as well as to mathematically describe the process using Eq. (6.2).

8 7 6 4 3 2 1 07 6 5 4 3 2 1 06 5 4 3 3 1 1 04 4 3 3 2 1 0 03 3 3 2 1 1 0 02 2 1 1 1 0 0 01 1 1 0 0 0 0 00 0 0 0 0 0 0 0

Page 77: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 64

FIGURE: 6-11 Threshold mask

When the mask is applied via Eq.(6.1) to the subimage for which it was derived, and the resulting n x n array is reordered to form an n2- element coefficient sequence in accordance with the zigzag ordering pattern of fig 6.12, the reordered 1-D sequence contains several long run of 0’s [the zigzag pattern becomes evident by starting at 0 in fig 6.12 and following the numbers in sequence]. These runs normally are run-length coded. The non-zero or retained coefficients, corresponding to the mask locations that contain 1, are represented using one of the variable-length codes of error- free compression.

FIGURE 6-12 Thresholded co-efficient ordering sequence

There are three basic ways to threshold a transformed subimage or, stated differently to create a subimage threshold masking function of the form given in Eq (6.1) (1) A single global threshold can be applied to all sub-images; (2) a different threshold can be used for each sub-image; or (3) the threshold can be varied as a function of the location of each co-efficient within the subimage. In the first approach, the level of compression differs from image to image, depending on the number of coefficients that exceed the global threshold. In the second, called N-largest coding, the same number of coefficients is discarded for each subimage. As a result, the code rate is constant and known in advance. The third technique, like the first, results in a variable code rate, but offers the advantage that thresholding and quantization can be combined by replacing

γ (u, v) T (u, v) in Eq. (6.2) with

Ť (u, v) =round [T (u, v)/Z (u, v)] ---Eq (6.3)

1 1 0 1 1 0 0 01 1 1 1 0 0 0 01 1 0 0 0 0 0 01 0 0 0 0 0 0 00 0 0 0 0 0 0 00 1 0 0 0 0 0 00 0 0 0 0 0 0 00 0 0 0 0 0 0 0

0 1 5 6 14 15 27 282 4 7 13 16 26 29 423 8 12 17 25 30 41 439 11 18 24 31 40 44 5310 19 23 32 39 45 52 5420 22 33 38 46 51 55 6021 34 37 47 50 56 59 6135 36 48 49 57 58 62 63

Page 78: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 65

Where Ť (u, v) is a thresholded and quantized approximation of T (u, v) and Z (u, v) is the element of the transform normalization array

Z= [Z (0, 0) Z (0, 1) ..………… Z (0, n-1); Z (1, 0) …. ……..………………….. ..; …. . . ….. …… ……… ……… ……; Z (n-1, 0) Z (n-1, 1)………...Z (n-1, n-1)]; ---Eq (6.4)

Before a normalized subimage transform, Ť (u, v), can be inverse transformed to obtain an approximation of subimage f(x, y), it must be multiplied by Z (u, v). The resulting denormalized array, denoted T’ is an approximation of Ť (u, v):

T’ (u, v) = Ť (u, v) Z (u, v). --- Eq (6.5)

The inverse transform of T’ (u, v) yields the decompressed subimage approximation.

FIGURE: 6-13 A typical normalization matrix.

6.6.5 Wavelet Coding

Wavelet coding is based on the idea that the coefficients of a transformthat de-correlates the pixels of an image can be coded more efficiently than the original pixels themselves. If the transforms basis functions- in this case wavelets-pack most of the important visual information in to a small number of coefficients, the remaining coefficients can be quantized coarsely or truncated to zero with little image distortion.

6.7 JPEG Fundamentals

A number of concepts need to be developed before JPEG encoding can be discussed in depth. The JPEG standard is applicable to both grey scale and color images. This is done by breaking a picture down in to a number of components. When each component is put together, the end image can be viewed. For example a back and white image would have only one component which would depict the grey scale

Page 79: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 66

of the image, whereas a color image generally has three components (one for each primary color, red green and blue or equivalent).

Each component is made up of x columns and y rows of samples. These samples are simply the actual "pixel" data of the image. In JPEG Baseline the number of samples is the same as the resolution of the image. A single pass through a component and its samples is known as a scan. In JPEG Baseline this does not mean a great deal as only one scan of the image is used.

In JPEG encoding the data is broken into a number of blocks calledMinimum Coded Units (MCU’s). These MCU’s are simply made by taking a number of 8x8 pixel sections of the source image. MCU’s are used to break down the image into workable blocks of data as well as to allow manipulation of local image correlation at a given part of the image by the encoding algorithm. When processing each MCU, the algorithm always moves through the component from the left to right, then top to bottom order.

There are two methods of processing MCU’s and components. The first method is whereby each MCU contains data from a single component only, and hence is comprised of only one unit of data. The second method is where the data from each component is interleaved within a single MCU. This means that each MCU contains all the data for a particular physical section of an image, rather than a number of MCU’s containing each component of that section. This project uses the latter option. Further to this, there are horizontal and vertical sampling factors. These sampling factors dictate how many 8x8 pixel sections are to be placed within an MCU when the component data is interleaved. For this project, the simplest option was taken which is a horizontal and vertical sampling factor of 1. The JPEG standard defines four variations for compression of images. These are known as follows:

Sequential lossless mode

This format is defined for applications in which it would be desirable to have no image detail lost in the compression process. This is not widely used as the compression statistics for this method is modest compared to the other styles.

Sequential DCT-based mode

An image first partitioned into blocks of 8x8 pixels

Then the blocks processed from left to right, top to bottom.

8x8 2-D forward DCT is applied to each block

8x8 DCT coefficients then quantized

Quantized DCT coefficients entropy encoded and output

Progressive DCT-based mode

Similar to sequential DCT-based mode

Quantized DCT coefficients, however, first stored in buffer.

Page 80: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 67

DCT coefficients in buffer then encoded by a multiple scanning process

In each scan, quantized DCT coefficients partially encoded either by

spectral selection or successive approximation.

In spectral selection, quantized DCT coefficients divided into multiplespectral bands according to the zigzag order. In each scan, a specified band is encoded.In successive approximation, a specified number of most significant bits of quantized coefficients first encoded. In subsequent scans, less significant bits are encoded.

FIGURE: 6-14 Sequential coding: part-by-part

FIGURE: 6-15 Progressive coding: quality-by-quality

Hierarchical mode

An image first spatially down-sampled to a multiple layered pyramid

FIGURE: 6-16 Hierarchical multi-resolution encoding

This sequence of frames encoded by predictive coding. Except for the first frame, the encoding process is applied to the differential frames.

Hierarchical coding mode provides a progressive presentation similar to progressive DCT-based mode but is useful in the applications, which have

Page 81: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 68

multi resolution requirements.

Hierarchical mode also provides the capability of progressive coding to a final lossless stage.

6.7.1 Human Visual system

A number of inherent properties of images and the human visual system can be manipulated to allow for greater compression through the JPEG algorithm. One of these is the tendency for the human eye to notice variations of brightness intensity much more than variations of color in an image. The JPEG algorithm can take advantage of this by applying different rules for brightness and color variations. Another property is that real world images generally do not have sharp boundaries for brightness intensity changes and color changes. This means that spatial frequencies detected within an image are generally low order, i.e. gradual change rather than quick changes over a localized area of an image.

6.7.2 JPEG Algorithm Technical Details

The JPEG Baseline algorithm can be broken broadly down into four sections as

follows:

Discrete Cosine Transform (DCT)

Quantization

Zigzag ordering

Huffman coding

6.7.3 DCT

The Discrete Cosine Transform is used in JPEG encoding to produce uncorrelated coefficients, allowing effective compression as each coefficient can be treated independently without risk of affecting compression efficiency. An additional feature of the DCT is that it allows the ability of quantizing the DCT coefficients using visually weighted quantization values to increase compression efficiency. This process is discussed later in the report. A number of ways exist to compute the DCT, each with various speed optimizations. For the purposes of this project, the simplest but slowest method was used to ensure the most reliable results.

6.7.3.1 DCT Details:

The human visual system is very dependent on spatial frequencies within an image. The DCT allows us to approximately break down an image into a set of waveforms, each with a particular spatial frequency. In doing this we can discard information that is not perceptible to the human visual system and keep the information that it is important to it. The DCT uses an 8x8 two-dimensional array of

Page 82: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 69

samples (i.e. an 8x8 pixel section of the original image) as input to the algorithm. Each sample is an 8 bit number representing the specific component currently being processed. Output from the DCT is an 8x8 set of spatial frequencies representing the input section of the image. Each number output from the DCT is a 12 bit number. The DCT itself is a relatively complex mathematical equation as follows:

where

for z = 0 or

for z > 0

- 2-D sample value

- 2-D DCT coefficient

The DCT output matrix represents magnitudes of spatial frequencies of increasing order. The lowest order is the (0,0) position (top left) and increases in each direction. The (0,0)-position value or lowest order is the average value of the input matrix. It is also known as the DC coefficient. All the other values are known as AC coefficients. For example if a 8x8 matrix to be input into the DCT algorithm was filled with the value 5, then the output matrix would have a 5 value in the DC coefficient, and zero in all the other 63 AC coefficients. This is due to the average of the input matrix being 5, as well as there being no spatial frequency change throughout the input. I.e. the input matrix was monotonous.

One of the advantages of using a DCT process as JPEG does is that real world images often have very gradual changes in brightness and color. This leads, generally, to very low (often zero) values in the high frequency coefficients of the DCT output. This is manipulated in the Quantization section of the JPEG Baseline algorithm.

There are algorithms known as "Fast DCT’s" which can speed up the process quite considerably. For example a DCT calculated on a 8x8 array of samples using the equation shown above will use 1024 multiplications and 896 additions to process the DCT. Using one of the fast DCT that has been developed by Feig requires only 54 multiplications, 464 additions and 6 arithmetic shifts to produce a similar result.

6.7.4 Decoding

For decompression, the decoder uses an inverse of this equation as follows

where

Page 83: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 70

for z = 0 or

for z > 0

- 2-D sample value

- 2-D DCT coefficient

6.7.5 Quantization

The second step of the JPEG algorithm is the quantization process. To quantize the output of the DCT we divide this matrix by an integer matrix of the same dimensions. The act of quantizing the output of the DCT is what introduces the "lossy" aspect of the JPEG algorithm. It also enables one of the main compression features that JPEG is able to perform. As mentioned previously, images tend to have low spatial frequency changes in a localized area. Combined with the tendency for humans to not notice high spatial frequency changes, this allows a large amount of the high order spatial frequency coefficients to be discarded. This is implemented by choosing the quantization factors appropriately for the coefficient to be quantized.

For example, the DC coefficient data is important to retain, so a small quantization factor is chosen for it. Typically this is around 10 to 16. Conversely the highest order AC coefficient (7, 7) is not important to retain so a large quantization factor is chosen. Typically this number can range between 80 to 140. The other AC values are generally graded between the two extremes. Obviously the higher the quantization factor, the closer to zero the coefficient is going to become. This property is taken advantage of in the Huffman Entropy encoding. Note that the values are always rounded to integers, so the information that is lost is in the rounding of coefficients after being quantized. This also explains why large quantization factors are more likely to discard information.

The ability to have different quantization factors depending on the component being processed is also specified in the JPEG standard. As was mentioned previously brightness and color separation in the YCbCr color scheme is beneficial for JPEG as the two quantities have different perceptions in the human eye. It follows that it would be beneficial to have different quantization factors for the brightness and the chrominance values as we can discard more chrominance and not readily notice the difference. Hence two different quantization factor tables are generally defined for color images, one for the Y (or brightness) component, and one for the Cb and Cr components (or chrominance). Of course if the image were a grey scale image with only one component, then only one quantization factor table would be required. The JPEG standard allows at most four quantization factor tables to be defined in an image.

It is common to see a normal 8x8 pixel section of an image represented by two or three numbers in the DC and low frequency AC coefficients and the rest of the quantized coefficients being zero. Obviously this is a very compressible format (a large number of repeated predictable constants). Each of 64 DCT coefficients is quantized by a uniform quantizer such as:

Page 84: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 71

Squv : quantized value of the DCT coefficient, Suv,

Quv : quantization step obtained from the quantization table.

6.7.6 Zigzag Ordering

To set up the quantized data for the Entropy encoding procedure, the current matrix format is not particularly useful. Since the quantized coefficients have a greater chance of being zero as the order of the spatial frequency values increases it would be beneficial to arrange the coefficients in this order. i.e., to some how arrange the coefficients so that the data was in a one dimensional array sorted from the DC value to the highest order spatial frequency (7, 7). This is done by zigzag ordering. The following diagram illustrates the sorting algorithm.

FIGURE :6-17 shows a quantization table for the luminance DCT coefficients

FIGURE: 6-18 Zigzag Scan Order for 8 x 8 DCT Coefficients

Page 85: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 72

FIGURE: 6-19 Probability of Quantized data being zero

6.7.7 Huffman Coding

Huffman codes are generally derived use a coding "tree" structure. This tree is built by a sequence of pairing operations in which the two least probable symbols are joined at a node. This continues with each node having their probabilities combined and then paired with the next smallest probable symbol until all the symbols represented in the tree structure. Creating a code from this tree structure is done by assigning a 0 or a 1 bit to each branch of the tree. The code for each symbol is then read by concatenating each bit from the branches, starting at the centre of the structure and extending to the branch for which the relevant symbol is defined.

Following this procedure gives a unique code for each symbol of optimal data size. Note that even though the codes can have different lengths, one code can never be mistaken for another if read from the most significant bit to the least significant bit. This becomes important in JPEG encoding as bit codes are appended to each other without regard for the length of the code.

6.7.7.1 Huffman Coding in JPEG

Fortunately, the JPEG standard provides a number of tables of Huffman codes to describe the different ways that the input quantized data is to be encrypted. The quantized DCT coefficients tend to have two different styles of values within them. The first is the DC coefficient or the first value in the zigzag ordered array. This value is always the average value and as such is likely to be any number within the range permitted.

Page 86: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 73

FIGURE: 6-20 Shows the JPEG co-efficient coding categories and JPEG default DC code respectively.

Figure: 6-21 Shows the JPEG default AC code

The second is all of the AC values (the second through to last coefficient in the zigzag ordered array). The values of the coefficients are likely to be

Page 87: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 74

close to zero, with the likelihood of being zero increasing as the coefficients near the end of the array. These two types of information are different enough to warrant separating them and applying different methods of coding to get the optimal compression efficiency. Additionally, coding in JPEG also distinguishes between whether the data is Luminance or Chrominance information. To do this it allows for different code tables to be specified for each of the components, much the same as how the quantization tables are defined. This means that a total of four Huffman code tables are generally defined in color images, two for DC information and 2 for AC information. Again, if the image was grey scale only two tables would be required (1 DC and 1 AC).

6.8 Decompression

To decompress a JPEG compressed subimage, the decoder must first recreate the normalized coefficients that led to the compressed bit stream. Because a Huffman-coded binary sequence is instantaneous and uniquely decodable, this step is easily accomplished in a simple lookup table manner.

6.8.1 Regenerated array of quantized coefficients

The bits are decoded and are converted in to their corresponding integers. And then these integers are arranged in an 8 x 8 matrix by a process called inverse zigzag process.

6.8.2 De-Normalization

After the completion of inverse zigzag process each 8 x 8 block or subimage(matrix), is now multiplied by a normalization matrix (which was used during the normalization process).

6.8.3 Inverse DCT

The completely reconstructed subimage is obtained by taking the inverse DCT of the denormalized array in accordance with

where

for z = 0 or

for z > 0

- 2-D sample value

- 2-D DCT coefficient.

Page 88: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 75

6.8.4 Level shifting each inverse transformed pixel by 128(27)

After the inverse DCT, level shifting of each pixel of a subimage (matrix) is done by adding 128(27) to each pixel of a subimage. In this manner every subimage of the original image is decompressed and is placed in its own place, as they were, while compressing them.

6.9 Compression ratio

It is the ratio of input image size to the compressed code size. i.e., (no of pixels x 8 bits)/compressed bit size. Compression ratio purely depends upon the input image. Compression ratios can be 5:1 or even 165:1 but it depends upon the input image

Page 89: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

IMPLEMENTATION&

RESULTS

Page 90: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 76

7.1 Algorithms

7.1.1 Algorithm for Image Compression process

Page 91: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 77

Page 92: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 78

Page 93: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 79

Page 94: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 80

7.1.2 Algorithm for Image De-Compression process

Page 95: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 81

Page 96: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 82

7.2 Implementation

7.2.1 Applying JPEG to Image “Number 1”

The input image is a image showing the ”number 1”, original image, image after removing 128 from all the pixel values, image after applying DCT, image after achieving the compression ratio 5.4225, 7.5625, 11.7000, 17.6093 are displayed one after the other respectively

Original imageSize: 1.521KB

Dimensions: 39 x 39

Page 97: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 83

Image after applying the -128Size: 1.6 KB

Dimensions: 40 x 40

Image after applying the DCTSize: 1.6 KB

Dimensions: 40 x 40

De-Compressed imageSize: 0.28KB

Dimensions: 40 x 40Compression ratio: 5.4225

Page 98: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 84

De-Compressed imageSize:0.2011KB

Dimensions: 40 x 40Compression ratio: 7.5625

De-Compressed imageSize: 0.13KB

Dimensions: 40 x 40Compression ratio: 11.7000

Page 99: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 85

De-Compressed imageSize: 0.086KB

Dimensions: 40 x 40Compression ratio: 17.6093

7.2.2 Applying JPEG to Image “Eye”

The input image is a image showing the ”eye”, original image, image after removing 128 from all the pixel values, image after applying DCT, image after achieving the

compression ratio 8.2766, 12.7381, 19.9913, 31.8342are displayed one after the other respectively

Original imageSize: 10KB

Dimensions: 100 x 100

Page 100: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 86

Image after applying the -128Size: 10.8 KB

Dimensions: 104 x 104

Image after applying the DCTSize: 10.8 KB

Dimensions: 104 x 104

Page 101: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 87

De-Compressed imageSize: 1.208KB

Dimensions: 104 x 104Compression ratio: 8.2766

De-Compressed imageSize: 0.785KB

Dimensions: 104 x 104Compression ratio: 12.7381

Page 102: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 88

De-Compressed imageSize:0.5KB

Dimensions: 104 x 104Compression ratio: 19.9913

De-Compressed imageSize: 0.3141KB

Dimensions: 104 x 104Compression ratio: 31.8342

Page 103: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

CONCLUSION

Page 104: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 89

Conclusion

In the project, “JPEG implementation using MATLAB”, for a given input image, dividing into blocks, level shifting by -128, DCT, Normalization, Zizzag, Coding are done one after the other. Compressed code is the output of the above operations and compression ratio is calculated. Effect of increasing the Compression ratio, by multiplying the quantization table with a positive integer is observed.

Decoding, Inverse Zizzag, De-Normalization, IDCT and level shifting by +128, Uniting the blocks to form a complete image are done one after the other in the order and the decompressed image is obtained. The JPEG which was implemented using the coding tool “ MATLAB” has been successfully implemented on the images named ” Number 1” and “EYE”.

All the input and output images of all the operations are displayed. The difference of the original image and the decompressed image can be observed.

Page 105: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

FUTUREENHANCEMENT

OFTHE PROJECT

Page 106: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 90

Future Enhancement of the Project

JPEG, after its standardization in the year 1992 by ISO has been the most dominating one and used world widely. It is being used in the World Wide Web for transferring the data and images which resulted in the amazing transfer of the data from the server to the client. JPEG has been successful, to get an image compression of 1/10th of the original image size, without effecting the quality of the picture and even high compression ratios have been achieved but with picture of slightly less quality.

JPEG using DCT has been outstanding but due to its slightly more time taken to decompress the image, JPEG 2000 has been used as a substitute for JPEG using DCT. JPEG 2000 works on the principle of Wavelet coding, by using this more compression ratio’s can been achieved, even compression ratio’s of 180:1 can also be achieved by using the JPEG 2000.

But the JPEG 2000 has few hurdles to cross, as it has not yet been completely proved satisfactorily for compressing all types of images. But if it is made suitable for compressing all types of images then it will be a great future aspect and can change the world in the medium of data transfer and storage.

Page 107: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

Appendix-A(COMPRESSION CODE)

Page 108: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 91

%*** READING THE IMAGE***clc;result4='0';resultfinal1='0';previous1=0;start1=1; end1=0;quantoutput1=0;%INTIALIZING THE INPUT IMAGE TO '0'inputimage=0; %TAKE THE INPUT IMAGEinputimage=(imread('08.bmp'));colormap(gray)imshow(inputimage)inputimage=double(inputimage);%FINDING THE SIZE OF THE IMAGE[row1,column1]=size(inputimage);

%***DIVIDING INTO BLOCKS***%ROUNDING THE ROWS TO THE MULTIPLE OF 8 if rem(row1,8)==0 row2=fix(row1/8);else row2=fix(row1/8)+1; inputimage(row1+1:8*row2,:)=0;end%ROUNDING THE COLUMNS TO THE MULTIPLE OF 8 if rem(column1,8)==0 column2=fix(column1/8);else column2=fix(column1/8)+1; inputimage(:,column1+1:8*column2)=0; end% STARTING OF THE FOR LOOP FOR ROW2 IN DIVIDING INTO BLOCKS LOGICfor i0=1:row2 i109=8*(i0-1)+1; i209=8*i0;% STARTING OF THE FOR LOOP FOR COLUMN2 IN DIVIDING INTO BLOCKS LOGIC for j0=1:column2 j109=8*(j0-1)+1; j209=8*j0; tempinput1=0; dctoutput2=0; tempinput1=inputimage(i109:i209,j109:j209)-128;

%***APPLYING DCT FOR THE INPUT 8*8 BLOCK***% STARTING OF FOR LOOP FOR THE 'V0' IN THE DCT PROGRAM for v0=0:7 % CONDITION FOR ASSIGNING THE VALUES FOR (V0)

if v0==0 q1=sqrt(1/8); elseif v0>0 q1=sqrt(2/8);

Page 109: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 92

end% STARTING OF FOR LOOP FOR THE 'U0' IN THE DCT PROGRAM for u0=0:7 % INITIALIZING SUM TO ZERO sum0=0; % CONDITION FOR ASSIGNING THE VALUES FOR (U0) if u0==0 q2=sqrt(1/8); elseif u0>0 q2=sqrt(2/8);

end% STARTING OF FOR LOOP FOR THE 'Y0' IN THE DCT PROGRAM for y0=0:7 % STARTING OF FOR LOOP FOR THE 'X0' IN THE DCT PROGRAM for x0=0:7 % SUMATION OF ALL THE PRODUCTS sum0 = sum0 +tempinput1(x0+1,y0+1)*cos(((2*x0)+1)*u0*pi/(2*8))

*cos(((2*y0)+1)*v0*pi/(2*8)); % CLOSING OF FOR LOOP FOR THE 'X0' IN THE DCT PROGRAM end% CLOSING OF FOR LOOP FOR THE 'Y0' IN THE DCT PROGRAM end% MULTIPLYING (V) AND (U) dctoutput2(u0+1,v0+1)=(q2*q1*sum0); sum0=0;% CLOSING OF FOR LOOP FOR THE 'U0' IN THE DCT PROGRAM end % CLOSING OF FOR LOOP FOR THE 'V0' IN THE DCT PROGRAM end

%***NORMALIZATION***%QUANTIZATION TABLE quanttable1=1*[16 11 10 16 24 40 51 61; 12 12 14 19 26 58 60 55; 14 13 16 24 40 57 69 56; 14 17 22 29 51 87 80 62; 18 22 37 56 68 109 103 77; 24 35 55 64 81 104 113 92; 49 64 78 87 103 121 120 101; 72 92 95 98 112 100 103 99]; quantoutput1=round(dctoutput2./quanttable1);

%*** ZIGZAG***%INTIALIZING 'X1' VALUE TO '0' x1=0; %INTIALIZING 'RES' MATRIX VALUE TO '0', WHICH IS THE ZIGZAG MATRIX BUT WITH %ZERO STILL IN IT res0=0; %INTIALIZING 'COUNT0’ TO '0' ,WHICH FINDS THE NUMBER OFZEROS BEFORE AN %INTEGER IN A ZIGZAG MATRIX count0=0; %FINAL MATRIX AFTER REMOVING THE ZERO'S FROM THE ZIGZAG MATRIX

Page 110: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 93

zigzagoutput0=0; %LOOP FOR THE MATRIX TO GET THE FINAL ZIGZAG VALUES for p0=2:16 mid0=0; remid0=0;%SEARCHING THE MATRIX FOR THE MATCH TO BE IN THE ORDER for i1=1:8 for j1=1:8 if i1+j1==p0 mid0=mid0+1;%LOGIC FOR ZIGZAG ORDER order=rem(p0,2); %STORING THE VALUES IN THE ORDER WITHOUT EXACT ZIGZAG remid0(mid0)=quantoutput1(i1,j1); end end end%LOGIC TO BE IN THE EXACT ZIGZAG ORDER if (order==0) for l= mid0:-1:1 x1=x1+1; res0(x1)=remid0(l); end end if (order==1) for l=1:mid0 x1=x1+1; res0(x1)=remid0(l); end end end%LOGIC FOR REMOVING THE EXTRA ZERO'S FROM THE ZIGZAG MATRIX for z=1:x1 if res0(z)==0 count0=count0+1; else count0=0; end end for ze=1:(x1-count0) zigzagoutput0(ze)=res0(ze); end %FINAL DISPLAY OF THE OUT- PUT MATRIX WITHOUT ZERO'S IN THE ZIGZAG MATRIX zigzagoutput0;

%***CODING*** noofzeros=0; incre1=1; incre2=0; resukt4=0;%STARTING THE FOR LOOP FOR 'I2’

Page 111: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 94

for i2= 1:x1-count0 if (zigzagoutput0(i2)==0)% INITIALIZING THE COUNT FOR 'NOOFZEROS' noofzeros=noofzeros+1; else% CODING FOR THE DC COMPONENT% STARTING` IF FOR DC AND AC if i2==1 present1=zigzagoutput0(i2); differ7=present1-previous1; previous1=present1; input1=differ7;%CODING FOR THE AC COMPONENT else input1=zigzagoutput0(i2);%CLOSING THE IF LOOP FOR WHETHER THE DC AND AC end %PROGRAM FOR DIVING IN TO CATEGORIES%DIVIDING INTO CATEGORIES if (input1==0) int1=0; else for n1=0:15 if(( (input1>=(2^(n1-1)))&&(input1<=((2^n1)-1)))|| ( (input1<=-(2^(n1-1)))&&(input1>=-((2^n1)-1)))) int1=n1; end end end dc=int1; ac=int1; if (i2==1) n6=dc; if n6==0 dc1='010'; length17=3; elseif n6==1 dc1='011'; length17=4; elseif n6==2 dc1='100'; length17=5;

elseif n6==3 dc1='00'; length17=5; elseif n6==4 dc1='101'; length17=7; elseif n6==5 dc1='110'; length17=8;

Page 112: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 95

elseif n6==6 dc1='1110'; length17=10; elseif n6==7 dc1='11110'; length17=12; elseif n6==8 dc1='111110'; length17=14; elseif n6==9 dc1='1111110'; length17=16; elseif n6==10 dc1='11111110'; length17=18; elseif n6==11 dc1='111111110'; length17=20;

end codelength1=length17; ac1=dc1; else % PROGRAM FOR GETTING THE AC CODES if(ac=='EOB') ac1='1010'; codelength1=4; elseif(ac==0) if noofzeros==0 ac1='1010'; codelength1=4; elseif noofzeros==15 ac1='111111110111'; codelength1=12; end% LOGIC FOR CATEGORY '1' elseif(ac==1)

if noofzeros==0 ac1='00'; codelength1=3;

elseif noofzeros==1 ac1='1100'; codelength1=5;

elseif noofzeros==2 ac1='11011'; codelength1=6;

elseif noofzeros==3 ac1='111010'; codelength1=7;

elseif noofzeros==4 ac1='111011';

Page 113: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 96

codelength1=7; elseif noofzeros==5

ac1='1111010'; codelength1=8;

elseif noofzeros==6 ac1='1111011'; codelength1=8;

elseif noofzeros==7 ac1='11111001'; codelength1=9;

elseif noofzeros==8 ac1='11111010'; codelength1=9;

elseif noofzeros==9 ac1='111111000'; codelength1=10;

elseif noofzeros==10 ac1='111111001'; codelength1=10;

elseif noofzeros==11 ac1='111111010'; codelength1=10;

elseif noofzeros==12 ac1='1111111010'; codelength1=11;

elseif noofzeros==13 ac1='11111111010'; codelength1=12;

elseif noofzeros==14 ac1='111111110110'; codelength1=13;

elseif noofzeros==15 ac1='1111111111110101'; codelength1=17;

end% LOGIC FOR CATEGORY '2' elseif (ac==2) if noofzeros==0

ac1='01'; codelength1=4;

elseif noofzeros==1 ac1='111001'; codelength1=8;

elseif noofzeros==2 ac1='11111000'; codelength1=10;

elseif noofzeros==3 ac1='111110111'; codelength1=11;

elseif noofzeros==4

Page 114: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 97

ac1='1111111000'; codelength1=12;

elseif noofzeros==5 ac1='1111111001'; codelength1=12;

elseif noofzeros==6 ac1='11111111000'; codelength1=13;

elseif noofzeros==7 ac1='11111111001'; codelength1=13;

elseif noofzeros==8 ac1='111111111000000'; codelength1=17;

elseif noofzeros==9 ac1='1111111110111111'; codelength1=18;

elseif noofzeros==10 ac1='1111111111001000'; codelength1=18;

elseif noofzeros==11 ac1='1111111111010001'; codelength1=18;

elseif noofzeros==12 ac1='1111111111011010'; codelength1=18;

elseif noofzeros==13 ac1='1111111111100011'; codelength1=18;

elseif noofzeros==14 ac1='1111111111101100'; codelength1=18;

elseif noofzeros==15 ac1='1111111111110110'; codelength1=18;

end% LOGIC FOR CATEGORY '3' elseif (ac==3)

if noofzeros==0 ac1='100'; codelength1=6;

elseif noofzeros==1 ac1='1111001'; codelength1=10;

elseif noofzeros==2 ac1='1111110111'; codelength1=13;

elseif noofzeros==3 ac1='11111110111'; codelength1=14;

Page 115: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 98

elseif noofzeros==4 ac1='1111111110010111'; codelength1=19;

elseif noofzeros==5 ac1='1111111110011111'; codelength1=19;

elseif noofzeros==6 ac1='1111111110100111'; codelength1=19;

elseif noofzeros==7 ac1='1111111110101111'; codelength1=19;

elseif noofzeros==8 ac1='1111111110110111'; codelength1=19;

elseif noofzeros==9 ac1='1111111111000000'; codelength1=19;

elseif noofzeros==10 ac1='1111111111001001'; codelength1=19;

elseif noofzeros==11 ac1='1111111111010010'; codelength1=19;

elseif noofzeros==12 ac1='1111111111011011'; codelength1=19;

elseif noofzeros==13 ac1='1111111111100100'; codelength1=19;

elseif noofzeros==14 ac1='1111111111101101'; codelength1=19;

elseif noofzeros==15 ac1='1111111111110111'; codelength1=19;

end% LOGIC FOR CATEGORY '4' elseif (ac==4)

if noofzeros==0 ac1='1011'; codelength1=8;

elseif noofzeros==1 ac1='111110110'; codelength1=13;

elseif noofzeros==2 ac1='1111111110001001'; codelength1=20;

elseif noofzeros==3 ac1='1111111110010000';

Page 116: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 99

codelength1=20; elseif noofzeros==4

ac1='1111111110011000'; codelength1=20;

elseif noofzeros==5 ac1='1111111110100000'; codelength1=20;

elseif noofzeros==6 ac1='1111111110101000'; codelength1=20;

elseif noofzeros==7 ac1='1111111110110000'; codelength1=20;

elseif noofzeros==8 ac1='1111111110111000'; codelength1=20;

elseif noofzeros==9 ac1='1111111111000001'; codelength1=20;

elseif noofzeros==10 ac1='1111111111001010'; codelength1=20;

elseif noofzeros==11 ac1='1111111111010011'; codelength1=20;

elseif noofzeros==12 ac1='1111111111011100'; codelength1=20;

elseif noofzeros==13 ac1='1111111111100101'; codelength1=20;

elseif noofzeros==14 ac1='1111111111101110'; codelength1=20;

elseif noofzeros==15 ac1='1111111111111000'; codelength1=20;

end% LOGIC FOR CATEGORY '5' elseif (ac==5)

if noofzeros==0 ac1='11010'; codelength1=10;

elseif noofzeros==1 ac1='11111110110'; codelength1=16;

elseif noofzeros==2 ac1='1111111110001010'; codelength1=21;

elseif noofzeros==3

Page 117: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 100

ac1='1111111110010001'; codelength1=21;

elseif noofzeros==4 ac1='1111111110011001'; codelength1=21;

elseif noofzeros==5 ac1='1111111110100001'; codelength1=21;

elseif noofzeros==6 ac1='1111111110101001'; codelength1=21;

elseif noofzeros==7 ac1='1111111110110001'; codelength1=21;

elseif noofzeros==8 ac1='1111111110111001'; codelength1=21;

elseif noofzeros==9 ac1='1111111111000010'; codelength1=21;

elseif noofzeros==10 ac1='1111111111001011'; codelength1=21;

elseif noofzeros==11 ac1='1111111111010100'; codelength1=21;

elseif noofzeros==12 ac1='1111111111011101'; codelength1=21;

elseif noofzeros==13 ac1='1111111111100110'; codelength1=21;

elseif noofzeros==14 ac1='1111111111101111'; codelength1=21;

elseif noofzeros==15 ac1='1111111111111001'; codelength1=21;

end% LOGIC FOR CATEGORY '6' elseif (ac==6)

if noofzeros==0 ac1='111000'; codelength1=12;

elseif noofzeros==1 ac1='1111111110000100'; codelength1=22;

elseif noofzeros==2 ac1='1111111110001011'; codelength1=22;

Page 118: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 101

elseif noofzeros==3 ac1='1111111110010010'; codelength1=22;

elseif noofzeros==4 ac1='1111111110011010'; codelength1=22;

elseif noofzeros==5 ac1='1111111110100010'; codelength1=22;

elseif noofzeros==6 ac1='1111111110101010'; codelength1=22;

elseif noofzeros==7 ac1='1111111110110010'; codelength1=22;

elseif noofzeros==8 ac1='1111111110111010'; codelength1=22;

elseif noofzeros==9 ac1='1111111111000011'; codelength1=22;

elseif noofzeros==10 ac1='1111111111001100'; codelength1=22;

elseif noofzeros==11 ac1='1111111111010101'; codelength1=22;

elseif noofzeros==12 ac1='1111111111011110'; codelength1=22;

elseif noofzeros==13 ac1='1111111111100111'; codelength1=22;

elseif noofzeros==14 ac1='1111111111110000'; codelength1=22;

elseif noofzeros==15 ac1='1111111111111010'; codelength1=22;

end% LOGIC FOR CATEGORY '7' elseif (ac==7)

if noofzeros==0 ac1='1111000'; codelength1=14;

elseif noofzeros==1 ac1='1111111110000101'; codelength1=23;

elseif noofzeros==2 ac1='1111111110001100';

Page 119: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 102

codelength1=23; elseif noofzeros==3

ac1='1111111110010011'; codelength1=23;

elseif noofzeros==4 ac1='1111111110011011'; codelength1=23;

elseif noofzeros==5 ac1='1111111110100011'; codelength1=23;

elseif noofzeros==6 ac1='1111111110101011'; codelength1=23;

elseif noofzeros==7 ac1='1111111110110011'; codelength1=23;

elseif noofzeros==8 ac1='1111111110111011'; codelength1=23;

elseif noofzeros==9 ac1='1111111111000100'; codelength1=23;

elseif noofzeros==10 ac1='1111111111001101'; codelength1=23;

elseif noofzeros==11 ac1='1111111111010110'; codelength1=23;

elseif noofzeros==12 ac1='1111111111011111'; codelength1=23;

elseif noofzeros==13 ac1='1111111111101000'; codelength1=23;

elseif noofzeros==14 ac1='1111111111110001'; codelength1=23;

elseif noofzeros==15 ac1='1111111111111011'; codelength1=23 ;

end% LOGIC FOR CATEGORY '8' elseif (ac==8)

if noofzeros==0 ac1='1111110110'; codelength1=18;

elseif noofzeros==1 ac1='1111111110000110'; codelength1=24;

elseif noofzeros==2

Page 120: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 103

ac1='1111111110001101'; codelength1=24;

elseif noofzeros==3 ac1='1111111110010100'; codelength1=24;

elseif noofzeros==4 ac1='1111111110011100'; codelength1=24;

elseif noofzeros==5 ac1='1111111110100100'; codelength1=24;

elseif noofzeros==6 ac1='1111111110101100'; codelength1=24;

elseif noofzeros==7 ac1='1111111110110100'; codelength1=24;

elseif noofzeros==8 ac1='1111111110111100'; codelength1=24;

elseif noofzeros==9 ac1='1111111111000101'; codelength1=24;

elseif noofzeros==10 ac1='1111111111001110'; codelength1=24;

elseif noofzeros==11 ac1='1111111111010111'; codelength1=24;

elseif noofzeros==12 ac1='1111111111100000'; codelength1=24;

elseif noofzeros==13 ac1='1111111111101001'; codelength1=24;

elseif noofzeros==14 ac1='1111111111110010'; codelength1=24;

elseif noofzeros==15 ac1='1111111111111100'; codelength1=24;

end end% ENDING FOR LOOP FOR WHETHER DC OR AC end [waste1,givenlength1]=size(ac1); diff1=codelength1-givenlength1;% LOGIC FOR EXTRA CODE LENGTH if diff1==0 result2=ac1;

Page 121: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 104

else% LOGIC FOR EXTRA CODE LENGTH FOR NEGATIVE NUMBERS if (input1<=0) input1=input1*(-1); q = quantizer([26 0]); b1= num2bin(q,input1); inter1=b1(26-diff1+1:26); for j3=1:diff1 if inter1(j3)=='1' inter1(j3)='0'; else inter1(j3)='1'; end end % LOGIC FOR EXTRA CODE LENGTH FOR POSITIVE NUMBERS else q = quantizer([26 0]); b1= num2bin(q,input1); inter1=b1(26-diff1+1:26); end end result2='0';% LOGIC FOR JOINING THE GIVEN CODE AND THE GENERATED CODE for i5=1:givenlength1 result2(i5)=ac1(i5); end x1=1; for j6=givenlength1+1:codelength1 result2(j6)=inter1(x1); x1=x1+1; end result2; incre2=incre2+codelength1; k7=1; for i9= incre1:incre2 result4(i9)=result2(k7); k7=k7+1; end incre1=incre1+codelength1;%SETTING THE COUNT FOR 'NOOFZEROS' TO '0' noofzeros=0; %CLOSING THE IF LOOP FOR 'ZIGZAGOUTPUT0' end %CLOSING THE FOR LOOP 'I2' end %CODE FOR THE WHOLE BLOCK result4; %FINDING THE SIZE OF THE WHOLE CODE BLOCK [waste9,blockcodelength1]=size(result4); % LOGIC FOR ADDING ‘ END OF BLOCK ’ TO THE CODED BLOCK EOB4='1010'; x8=1;

Page 122: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 105

% STARTING 'FOR' LOOP FOR ADDING THE END OF BLOCK for k6=blockcodelength1+1:blockcodelength1+4 result4(k6)=EOB4(x8); x8=x8+1;% CLOSING 'FOR' LOOP FOR ADDING THE ‘END OF BLOCK’ end result4; end1=end1+blockcodelength1+4; l8=1; for p5 = start1:end1 resultfinal1(p5)=result4(l8); l8=l8+1; end start1=start1+blockcodelength1+4; result4='0';% CLOSING OF THE FOR LOOP FOR 'COLUMN2' IN DIVIDING IN TO BLOCKS LOGIC end % CLOSING OF THE FOR LOOP FOR 'ROW2' IN DIVIDING INTO BLOCKS LOGICend resultfinal1actualsize1=row1*column1*8;

%*** COMPRESSION RATIO***compressionratio1=actualsize1/end1

Page 123: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

Appendix-B(DE-COMPRESSION CODE)

Page 124: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 106

%***DECODING ***finalblock28=0;decompressedimag1=0;decodinginput1=resultfinal1;[row7,column7]=size(decodinginput1);start7=1;u8=1;dc6=0;%STARTING OF THE WHILE LOOP FOR ' START7’ UNTIL END OF BIT STREAM IS REACHED while start7<column7 next2=1; k3=3;%STARTING OF THE FOR LOOP FOR MATCHING THE NUMBERS FOR EACH CODE 'K3' while next2<132 count3=1; count4=1; temperaory1=0; temperaory1=decodinginput1(start7:start7+k3-1); incrementit1=0; basecode1=0; endofblock1=0; changedc1=0;% FOR DC COEFFICIENTS if(dc6==0) if(next2==1)&&(k3==3) categoerydc1=0; basecode1='010'; addzeros1=0; incrementit1=1; elseif(next2==2)&&(k3==4) categoerydc1=1; basecode1='011'; addzeros1=0; incrementit1=1; elseif(next2==3)&&(k3==5) categoerydc1=2; basecode1='100'; addzeros1=0; elseif(next2==4)&&(k3==5) categoerydc1=3;

basecode1='00'; addzeros1=0; incrementit1=1;

elseif(next2==5)&&(k3==6) incrementit1=1;

elseif(next2==6)&&(k3==7) categoerydc1=4; basecode1='101'; addzeros1=0;

Page 125: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 107

incrementit1=1; elseif(next2==7)&&(k3==8)

categoerydc1=5; basecode1='110'; addzeros1=0; incrementit1=1;

elseif(next2==8)&&(k3==9) incrementit1=1;

elseif(next2==9)&&(k3==10) categoerydc1=6; basecode1='1110'; addzeros1=0; incrementit1=1;

elseif(next2==10)&&(k3==11) incrementit1=1;

elseif(next2==11)&&(k3==12) categoerydc1=7; basecode1='11110'; addzeros1=0; incrementit1=1;

elseif(next2==12)&&(k3==13) incrementit1=1;

elseif(next2==13)&&(k3==14) categoerydc1=8; basecode1='111110'; addzeros1=0; incrementit1=1;

elseif(next2==14)&&(k3==15) incrementit1=1;

elseif(next2==15)&&(k3==16) categoerydc1=9; basecode1='1111110'; addzeros1=0; incrementit1=1;

elseif(next2==16)&&(k3==17) incrementit1=1;

elseif(next2==17)&&(k3==18) categoerydc1=10; basecode1='11111110'; addzeros1=0; incrementit1=1;

elseif(next2==18)&&(k3==19) incrementit1=1;

elseif(next2==19)&&(k3==20) categoerydc1=11; basecode1='111111110'; addzeros1=0; incrementit1=1;

end changedc1=1;

Page 126: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 108

% FOR AC COEFFICIENTS else if (next2==1)&&(k3==3)

categoerydc1=1; basecode1='00'; addzeros1=0; incrementit1=1;

elseif (next2==2)&&(k3==4) categoerydc1=0; basecode1='1010'; addzeros1=0; endofblock1=1;

elseif (next2==3)&&(k3==4) categoerydc1=2; basecode1='01'; addzeros1=0; incrementit1=1;

elseif(next2==4)&&(k3==5) categoerydc1=1; basecode1='1100'; addzeros1=1; incrementit1=1;

elseif(next2==5)&&(k3==6) categoerydc1=3; basecode1='100'; addzeros1=0;

elseif(next2==6)&&(k3==6) categoerydc1=1; basecode1='11011'; addzeros1=2; incrementit1=1;

elseif(next2==7)&&(k3==7) categoerydc1=1; basecode1='111010'; addzeros1=3;

elseif(next2==8)&&(k3==7) categoerydc1=1; basecode1='111011'; addzeros1=4; incrementit1=1;

elseif (next2==9)&&(k3==8) categoerydc1=4; basecode1='1011'; addzeros1=0;

elseif (next2==10)&&(k3==8) categoerydc1=2; basecode1='111001'; addzeros1=1;

elseif (next2==11)&&(k3==8) categoerydc1=1;

Page 127: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 109

basecode1='1111010'; addzeros1=5;

elseif (next2==12)&&(k3==8) categoerydc1=1; basecode1='1111011'; addzeros1=6; incrementit1=1;

elseif(next2==13)&&(k3==9) categoerydc1=1; basecode1='11111010'; addzeros1=8;

elseif (next2==14)&&(k3==9) categoerydc1=1; basecode1='11111001'; addzeros1=7; incrementit1=1;

elseif (next2==15)&&(k3==10) categoerydc1=5; basecode1='11010'; addzeros1=0;

elseif (next2==16)&&(k3==10) categoerydc1=3; basecode1='1111001'; addzeros1=1;

elseif (next2==17)&&(k3==10) categoerydc1=2; basecode1='11111000'; addzeros1=2;

elseif (next2==18)&&(k3==10) categoerydc1=1; basecode1='111111000'; addzeros1=9;

elseif (next2==19)&&(k3==10) categoerydc1=1; basecode1='111111001'; addzeros1=10;

elseif (next2==20)&&(k3==10) categoerydc1=1; basecode1='111111010'; addzeros1=11; incrementit1=1;

elseif (next2==21)&&(k3==11) categoerydc1=2; basecode1='111110111'; addzeros1=3;

elseif (next2==22)&&(k3==11) categoerydc1=1; basecode1='1111111010'; addzeros1=11; incrementit1=1;

Page 128: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 110

elseif (next2==23)&&(k3==12) categoerydc1=6; basecode1='111000'; addzeros1=0;

elseif (next2==24)&&(k3==12) categoerydc1=2; basecode1='1111111000'; addzeros1=4;

elseif (next2==25)&&(k3==12) categoerydc1=2; basecode1='1111111001'; addzeros1=5;

elseif (next2==26)&&(k3==12) categoerydc1=1; basecode1='11111111010'; addzeros1=13;

elseif (next2==27)&&(k3==12) categoerydc1=0; basecode1='111111110111'; addzeros1=15; incrementit1=1;

elseif (next2==28)&&(k3==13) categoerydc1=4; basecode1='111110110'; addzeros1=1;

elseif (next2==29)&&(k3==13) categoerydc1=3; basecode1='1111110111'; addzeros1=2;

elseif (next2==30)&&(k3==13) categoerydc1=2; basecode1='11111111000'; addzeros1=6;

elseif (next2==31)&&(k3==13) categoerydc1=2; basecode1='11111111001'; addzeros1=7;

elseif (next2==32)&&(k3==13) categoerydc1=1; basecode1='111111110110'; addzeros1=14; incrementit1=1;

elseif (next2==33)&&(k3==14) categoerydc1=7; basecode1='1111000'; addzeros1=0;

elseif (next2==34)&&(k3==14) categoerydc1=3; basecode1='11111110111'; addzeros1=3;

Page 129: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 111

incrementit1=1; elseif (next2==35)&&(k3==15)

incrementit1=1; elseif (next2==36)&&(k3==16)

categoerydc1=5; basecode1='11111110110'; addzeros1=1; incrementit1=1;

elseif(next2==37)&&(k3==17) categoerydc1=2; basecode1='111111111000000'; addzeros1=8;

elseif (next2==38)&&(k3==17) categoerydc1=1; basecode1='1111111111110101'; addzeros1=15; incrementit1=1;

elseif (next2==39)&&(k3==18) categoerydc1=1; basecode1='1111111111110101'; addzeros1=15;

elseif (next2==40)&&(k3==18) categoerydc1=2; basecode1='1111111110111111'; addzeros1=9;

elseif(next2==41)&&(k3==18) categoerydc1=2; basecode1='1111111111001000'; addzeros1=10;

elseif (next2==42)&&(k3==18) categoerydc1=2; basecode1='1111111111010001'; addzeros1=11;

elseif (next2==43)&&(k3==18) categoerydc1=2; basecode1='1111111111011010'; addzeros1=12;

elseif (next2==44)&&(k3==18) categoerydc1=2; basecode1='1111111111100011'; addzeros1=13;

elseif (next2==45)&&(k3==18) categoerydc1=2; basecode1='1111111111101100'; addzeros1=14;

elseif (next2==46)&&(k3==18) categoerydc1=2; basecode1='1111111111110110'; addzeros1=15; incrementit1=1;

Page 130: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 112

elseif (next2==47)&&(k3==19) categoerydc1=3; basecode1='1111111110010111'; addzeros1=4;

elseif (next2==48)&&(k3==19) categoerydc1=3; basecode1='1111111110011111'; addzeros1=5;

elseif (next2==49)&&(k3==19) categoerydc1=3; basecode1='1111111110100111'; addzeros1=6;

elseif (next2==50)&&(k3==19) categoerydc1=3; basecode1='1111111110101111'; addzeros1=7;

elseif (next2==51)&&(k3==19) categoerydc1=3; basecode1='1111111110110111'; addzeros1=8;

elseif (next2==52)&&(k3==19) categoerydc1=3; basecode1='1111111111000000'; addzeros1=9;

elseif (next2==53)&&(k3==19) categoerydc1=3; basecode1='1111111111001001'; addzeros1=10;

elseif (next2==54)&&(k3==19) categoerydc1=3; basecode1='1111111111010010'; addzeros1=11;

elseif (next2==55)&&(k3==19) categoerydc1=3; basecode1='1111111111011011'; addzeros1=12;

elseif (next2==56)&&(k3==19) categoerydc1=3; basecode1='1111111111100100'; addzeros1=13;

elseif (next2==57)&&(k3==19) categoerydc1=3; basecode1='1111111111101101'; addzeros1=14;

elseif (next2==58)&&(k3==19) categoerydc1=3; basecode1='1111111111110111'; addzeros1=15; incrementit1=1;

elseif (next2==59)&&(k3==20)

Page 131: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 113

categoerydc1=4; basecode1='1111111110011000'; addzeros1=4;

elseif (next2==60)&&(k3==20) categoerydc1=4; basecode1='1111111110100000'; addzeros1=5;

elseif (next2==61)&&(k3==20) categoerydc1=4; basecode1='1111111110101000'; addzeros1=6;

elseif (next2==62)&&(k3==20) categoerydc1=4; basecode1='1111111110110000'; addzeros1=7;

elseif (next2==63)&&(k3==20) categoerydc1=4; basecode1='1111111110111000'; addzeros1=8;

elseif (next2==64)&&(k3==20) categoerydc1=4; basecode1='1111111111000001'; addzeros1=9;

elseif (next2==65)&&(k3==20) categoerydc1=4; basecode1='1111111111001010'; addzeros1=10;

elseif (next2==66)&&(k3==20) categoerydc1=4; basecode1='1111111111010011'; addzeros1=11;

elseif (next2==67)&&(k3==20) categoerydc1=4; basecode1='1111111111011100'; addzeros1=12;

elseif (next2==68)&&(k3==20) categoerydc1=4; basecode1='1111111111100101'; addzeros1=13;

elseif (next2==69)&&(k3==20) categoerydc1=4; basecode1='1111111111101110'; addzeros1=14;

elseif (next2==70)&&(k3==20) categoerydc1=4; basecode1='1111111111111000'; addzeros1=15;

elseif (next2==71)&&(k3==20) categoerydc1=4; basecode1='1111111110001001';

Page 132: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 114

addzeros1=2; elseif (next2==72)&&(k3==20)

categoerydc1=4; basecode1='1111111110010000'; addzeros1=3; incrementit1=1;

elseif (next2==73)&&(k3==21) categoerydc1=5; basecode1='1111111110001010'; addzeros1=2;

elseif (next2==74)&&(k3==21) categoerydc1=5; basecode1='1111111110010001'; addzeros1=3;

elseif (next2==75)&&(k3==21) categoerydc1=5; basecode1='1111111110011001'; addzeros1=4;

elseif (next2==76)&&(k3==21) categoerydc1=5; basecode1='1111111110100001'; addzeros1=5;

elseif (next2==77)&&(k3==21) categoerydc1=5; basecode1='1111111110101001'; addzeros1=6;

elseif (next2==78)&&(k3==21) categoerydc1=5; basecode1='1111111110110001'; addzeros1=7;

elseif (next2==79)&&(k3==21) categoerydc1=5; basecode1='1111111110111001'; addzeros1=8;

elseif (next2==80)&&(k3==21) categoerydc1=5; basecode1='1111111111000010'; addzeros1=9;

elseif (next2==81)&&(k3==21) categoerydc1=5; basecode1='1111111111001011'; addzeros1=10;

elseif (next2==82)&&(k3==21) categoerydc1=5; basecode1='1111111111010100'; addzeros1=11;

elseif (next2==83)&&(k3==21) categoerydc1=5; basecode1='1111111111011101'; addzeros1=12;

Page 133: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 115

elseif (next2==84)&&(k3==21) categoerydc1=5; basecode1='1111111111100110'; addzeros1=13;

elseif (next2==85)&&(k3==21) categoerydc1=5; basecode1='1111111111101111'; addzeros1=14;

elseif (next2==86)&&(k3==21) categoerydc1=5; basecode1='1111111111111001'; addzeros1=15; incrementit1=1;

elseif (next2==87)&&(k3==22) categoerydc1=6; basecode1='1111111110000100'; addzeros1=1;

elseif (next2==88)&&(k3==22) categoerydc1=6; basecode1='1111111110001011'; addzeros1=2;

elseif (next2==89)&&(k3==22) categoerydc1=6; basecode1='1111111110010010'; addzeros1=3;

elseif (next2==90)&&(k3==22) categoerydc1=6; basecode1='1111111110011010'; addzeros1=4;

elseif (next2==91)&&(k3==22) categoerydc1=6; basecode1='1111111110100010'; addzeros1=5;

elseif (next2==92)&&(k3==22) categoerydc1=6; basecode1='1111111110101010'; addzeros1=6;

elseif (next2==93)&&(k3==22) categoerydc1=6; basecode1='1111111110110010'; addzeros1=7;

elseif (next2==94)&&(k3==22) categoerydc1=6; basecode1='1111111110111010'; addzeros1=8;

elseif (next2==95)&&(k3==22) categoerydc1=6; basecode1='1111111111000011'; addzeros1=9;

elseif (next2==96)&&(k3==22)

Page 134: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 116

categoerydc1=6; basecode1='1111111111001100'; addzeros1=10;

elseif (next2==97)&&(k3==22) categoerydc1=6; basecode1='1111111111010101'; addzeros1=11;

elseif (next2==98)&&(k3==22) categoerydc1=6; basecode1='1111111111011110'; addzeros1=12;

elseif (next2==99)&&(k3==22) categoerydc1=6; basecode1='1111111111100111'; addzeros1=13;

elseif (next2==100)&&(k3==22) categoerydc1=6; basecode1='1111111111110000'; addzeros1=14;

elseif (next2==101)&&(k3==22) categoerydc1=6; basecode1='1111111111111010'; addzeros1=15; incrementit1=1;

elseif (next2==102)&&(k3==23) categoerydc1=7; basecode1='1111111110000101'; addzeros1=1;

elseif (next2==103)&&(k3==23) categoerydc1=7; basecode1='1111111110001100'; addzeros1=2;

elseif (next2==104)&&(k3==23) categoerydc1=7; basecode1='1111111110010011'; addzeros1=3;

elseif (next2==105)&&(k3==23) categoerydc1=7; basecode1='1111111110011011'; addzeros1=4;

elseif (next2==106)&&(k3==23) categoerydc1=7; basecode1='1111111110100011'; addzeros1=5;

elseif (next2==107)&&(k3==23) categoerydc1=7; basecode1='1111111110101011'; addzeros1=6;

elseif (next2==108)&&(k3==23) categoerydc1=7;

Page 135: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 117

basecode1='1111111110110011'; addzeros1=7;

elseif (next2==109)&&(k3==23) categoerydc1=7; basecode1='1111111110111011'; addzeros1=8;

elseif (next2==110)&&(k3==23) categoerydc1=7; basecode1='1111111111000100'; addzeros1=9;

elseif (next2==111)&&(k3==23) categoerydc1=7; basecode1='1111111111001101'; addzeros1=10;

elseif (next2==112)&&(k3==23) categoerydc1=7; basecode1='1111111111010110'; addzeros1=11;

elseif (next2==113)&&(k3==23) categoerydc1=7; basecode1='1111111111011111'; addzeros1=12;

elseif (next2==114)&&(k3==23) categoerydc1=7; basecode1='1111111111101000'; addzeros1=13;

elseif (next2==115)&&(k3==23) categoerydc1=7; basecode1='1111111111110001'; addzeros1=14;

elseif (next2==116)&&(k3==23) categoerydc1=7; basecode1='1111111111111011'; addzeros1=15; incrementit1=1;

elseif (next2==117)&&(k3==24) categoerydc1=8; basecode1='1111111110000110'; addzeros1=1;

elseif (next2==118)&&(k3==24) categoerydc1=8; basecode1='1111111110001101'; addzeros1=2;

elseif (next2==119)&&(k3==24) categoerydc1=8; basecode1='1111111110010100'; addzeros1=3;

elseif (next2==120)&&(k3==24) categoerydc1=8; basecode1='1111111110011100';

Page 136: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 118

addzeros1=4; elseif (next2==121)&&(k3==24)

categoerydc1=8; basecode1='1111111110100100'; addzeros1=5;

elseif (next2==122)&&(k3==24) categoerydc1=8; basecode1='1111111110101100'; addzeros1=6;

elseif (next2==123)&&(k3==24) categoerydc1=8; basecode1='1111111110110100'; addzeros1=7;

elseif (next2==124)&&(k3==24) categoerydc1=8; basecode1='1111111110111100'; addzeros1=8;

elseif (next2==125)&&(k3==24) categoerydc1=8; basecode1='1111111111000101'; addzeros1=9;

elseif (next2==126)&&(k3==24) categoerydc1=8; basecode1='1111111111001110'; addzeros1=10;

elseif (next2==127)&&(k3==24) categoerydc1=8; basecode1='1111111111010111'; addzeros1=11;

elseif (next2==128)&&(k3==24) categoerydc1=8; basecode1='1111111111100000'; addzeros1=12;

elseif (next2==129)&&(k3==24) categoerydc1=8; basecode1='1111111111101001'; addzeros1=13;

elseif (next2==130)&&(k3==24) categoerydc1=8; basecode1='1111111111110010'; addzeros1=14;

elseif (next2==131)&&(k3==24) categoerydc1=8; basecode1='1111111111111100'; addzeros1=15; incrementit1=1;

end% ENDING THE IF LOOP, WHETHER IT IS AC OR DC COEFFICIENT end% FINDING THE LENGTH OF THE BASECODE1

Page 137: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 119

[waste6,givendclength1]=size(basecode1);% STARTING OF FOR LOOP 'PO2' WHETHER THE BASE CODE IS THE CORRECT MATCH OR %NOT for po2=1:givendclength1 if basecode1(po2)==temperaory1(po2) count3=0;

else count3=1; break end% ENDING OF FOR LOOP 'PO2' WHETHER THE BASE CODE IS THE CORRECT MATCH OR %NOT end% STARTING THE IF LOOP FOR REMAINING BITS if (k3-givendclength1)>0 && count3==0% STARTING OF THE FOR LOOP 'PO3' FOR POSITIVE NUMBERS IN A GIVEN CATEGORY for po3 = 2^(categoerydc1-1):(2^categoerydc1)-1 q65 = quantizer([26 0]); b1= num2bin(q65,po3); diff3=k3-givendclength1; temperin1=b1(26-diff3+1:26);% STARTING THE FOR LOOP PO4 FOR MATCHING EACH BIT IN THE REMAINING CODE for po4=1:diff3% STARTING THE IF CONDITION FOR MATCHING THE BITS OF THE REMAINING CODE if temperaory1(givendclength1+po4)==temperin1(po4) count4=0; else count4=1; break% ENDING THE IF CONDITION FOR MATCHING THE BITS OF THE REMAINING CODE end% ENDING THE FOR LOOP PO4 FOR MATCHING EACH BIT IN THE REMAINING CODE end%STARTING THE IF CONDITION; IF THE CODE GETS MATCHED THEN IT IS STORED if count4==0 corrrectnumber1=po3; break%ENDING THE IF CONDITION; IF THE CODE GETS MATCHED THEN IT IS STORED end% ENDING OF THE FOR LOOP 'PO3' FOR POSITIVE NUMBERS IN A GIVEN CATEGORY end% STARTING THE IF LOOP IF THE CODE DOESN'T GET MATCHED IN THE PREVIOUS %SECTION if count4>0% STARTING OF THE FOR LOOP 'PO3' FOR NEGATIVE NUMBERS IN A GIVEN CATEGORY for po3 = -(2^categoerydc1)+1:-2^(categoerydc1-1) po2=po3*-1; q65 = quantizer([26 0]); b1= num2bin(q65,po2); diff3=k3-givendclength1; temperin1=b1(26-diff3+1:26);

Page 138: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 120

for j31=1:diff3 if temperin1(j31)=='1' temperin1(j31)='0'; else temperin1(j31)='1'; end end % STARTING THE FOR LOOP 'PO4' FOR MATCHING EACH BIT IN THE REMAININGCODE for po4=1:diff3% STARTING THE IF CONDITION FOR MATCHING THE BITS OF THE REMAINING CODE if temperaory1(givendclength1+po4)==temperin1(po4) count4=0; else count4=1; break% ENDING THE IF CONDITION FOR MATCHING THE BITS OF THE CODE end% ENDING THE FOR LOOP "PO4" FOR MATCHING EACH BIT IN THE REMAINING CODE end%STARTING THE IF CONDITION; IF THE CODE GETS MATCHED THEN IT IS STORED if count4==0 corrrectnumber1=po3; categoerydc1=0; break%ENDING THE IF CONDITION; IF THE CODE GETS MATCHED THEN IT IS STORED end % ENDING OF THE FOR LOOP 'PO3' FOR NEGATIVE NUMBERS IN A GIVEN CATEGORY end% ENDING THE IF LOOP IF THE CODE DOESN'T GET MATCHED IN THE PREVIOUS % SECTION end elseif (k3-givendclength1)<=0 && count3==0 corrrectnumber1=categoerydc1; count4=0;% ENDING THE IF LOOP FOR REMAINING BITS end%STARTING THE IF CONDITION IF THE CODE GETS MATCHED THEN IT IS STORED IN %THE ARRAY if count4==0 ||count3==0 start7=start7+k3;% STARTING IF LOOP FOR ADDING ZERO’S FOR END OF BLOCK if endofblock1==1 addzeros1=64-rem(u8,64); dc6=0;% ENDING IF LOOP FOR ADDING ZERO’S FOR END OF BLOCK end% STARTING IF LOOP FOR ADDING ZERO‘S if addzeros1>0 f inalblock28(u8:u8+addzeros1-1)=0; u8=u8+addzeros1;% ENDING IF LOOP FOR ADDING ZEROS end

Page 139: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 121

finalblock28(u8)=corrrectnumber1;% CHANGING THE DC VALUES ONCE ITS OVER if (changedc1==1) dc6=1; changedc1=0; end corrrectnumber1=0; u8=u8+1; count3=1; count4=1; break%ENDING THE IF CONDITION IF THE CODE GETS MATCHED THEN IT IS STORED IN %THE ARRAY

end if ( incrementit1==1) k3=k3+1; end next2=next2+1;%ENDING OF THE FOR LOOP FOR MATCHING THE NUMBERS FOR EACH CODE 'K3' end if next2==132 disp('wrong code') break end%ENDING OF THE WHILE LOOP FOR ' START7’ UNTIL END OF BIT STREAM IS REACHED endfinalblock28

%***ADDING THE DC COMPONENETS***adddc1=fix(u8/64);addthedccomponenet=0;j0=1;% LOOP FOR ADDING THE DC COMPONENETSwhile j0<=adddc1 finalblock28((64*(j0-1))+1)=finalblock28((64*(j0-1))+1)+addthedccomponenet; addthedccomponenet=finalblock28((64*(j0-1))+1); j0=j0+1;endfinalblock28;%****INVERSE ZIGZAG***j0=1;while j0<=adddc1 decodedoutput1=finalblock28((64*(j0-1))+1:64*j0); t5=0; for p=2:16 for i=1:8 for j=1:8 if i+j==p t5=t5+1; if ( rem(p,2)==1)

Page 140: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 122

i1=i; j1=j; else i1=j; j1=i; end inversezizzag1(i1,j1)=decodedoutput1(t5); end end end endinversezizzag1;

%***DEQUANTIZATION***%QUANTIZATION TABLEquanttable1=1*[16 11 10 16 24 40 51 61; 12 12 14 19 26 58 60 55; 14 13 16 24 40 57 69 56; 14 17 22 29 51 87 80 62; 18 22 37 56 68 109 103 77; 24 35 55 64 81 104 113 92; 49 64 78 87 103 121 120 101; 72 92 95 98 112 100 103 99];dequntizedoutput1=inversezizzag1.*quanttable1;

%***INVERSE DCT***% STARTING OF FOR LOOP FOR THE 'Y5' IN THE IDCT PROGRAMfor y5=0:7 % STARTING OF FOR LOOP FOR THE 'X5' IN THE IDCT PROGRAM for x5=0:7 % INITIALIZING SUM TO ZERO sum2=0; % STARTING OF FOR LOOP FOR THE 'V5' IN THE IDCT PROGRAM for v5=0:7 if v5==0 q1=sqrt(1/8); end if v5>0 q1=sqrt(2/8); end% STARTING OF FOR LOOP FOR THE 'U5' IN THE IDCT PROGRAM for u5=0:7 if u5==0 q2=sqrt(1/8); end if u5>0 q2=sqrt(2/8); end% SUMMATION OF ALL THE PRODUCTS sum2 = sum2 + q2*q1*dequntizedoutput1(u5+1,v5+1) *cos(((2*x5)+1)*u5*pi/(2*8))* cos(((2*y5)+1)*v5*pi/(2*8));% ENDING OF FOR LOOP FOR THE 'U5' IN THE IDCT PROGRAM end

Page 141: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 123

% ENDING OF FOR LOOP FOR THE 'V5' IN THE IDCT PROGRAM end idctoutput1(x5+1,y5+1)=round(sum2);% ENDING OF FOR LOOP FOR THE 'X5' IN THE IDCT PROGRAM end% STARTING OF FOR LOOP FOR THE 'Y5' IN THE IDCT PROGRAM end

% DISPLAYING THE FINAL IDCT RESULTidctoutput1;%ADDING 128 TO ALL THE ELEMENTS IN THE MATRIXadd1281=idctoutput1+128;%ADDING INTO ONE MATRIXnearfinal1(1:8,8*(j0-1)+1:8*j0)=add1281(1:8,1:8);j0=j0+1;end%GROUPING THE BLOCKS TO FORM A IMAGErow15=sqrt(fix(u8/64));j10=1;% STARTING THE FOR LOOP OF 'J15'IN GROUPINGfor j15=1:row15% STARTING THE FOR LOOP OF 'I15'IN GROUPING for i15=1:row15 decompressedimage1(8*(j15-1)+1:8*j15,8*(i15-1)+1:8*i15) = nearfinal1(1:8,8*(j10-1)+1:8*j10); j10=j10+1;% ENDING THE FOR LOOP OF 'I15'IN GROUPING end% ENDING THE FOR LOOP OF 'J15'IN GROUPINGenddecompressedimage1;

%***DISPLAYING THE DECOMPRESSED IMAGE***colormap(gray)figure, imshow(decompressedimage1,[])

Page 142: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

BIBLIOGRAPHY

Page 143: PROJECT REPORT ON JPEG IMPLEMENTATION USING MATLABread.pudn.com/downloads182/doc/comm/851424/JPEG.pdf · CERTIFICATE This is to certify that B.DHEERAJ REDDY, student of Bachelor of

JPEG Implementation Using MATLAB

Department of Electronics and Communication Engineering (N.I.E.T) 124

BIBLIOGRAPHYThe following books and sites were referred while doing the analysis phase and execution phase of the project.

DIGITAL IMAGE PROCESSINGBY RAFAEL C. GONZALEZ & RICHARD E.WOODS

DIGITAL IMAGE PROCESSING USING MATLABBY RAFAEL C. GONZALEZ, RICHARD E.WOODS, STEVEN L. EDDINS

WEBSITES:

http://www.faqs.com

http://en.wikipedia.org