Top Banner

of 22

Kompresi Gambar Dengan Matlab 7

Jul 17, 2015

Download

Documents

Teknik Mcu
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript

Kompresi gambar Dengan Matlab 7.1

KOMPRESISecara garis besar, kompresi merupakan proses untuk menghilangkan berbagai kerumitan yang tidak penting (redundansi) dari suatu informasi dengan cara memadatkan isi file sehingga ukurannya menjadi lebih kecil dengan memaksimalkan kesederhanaannya dan tetap menjaga kualitas penggambaran dari informasi tersebut. Kompresi data menjadi sangat penting karena memperkecil pengiriman kebutuhan data, penyimpanan data, mempercepat memperkecil kebutuhan

bandwith.Teknik kompresi bisa dilakukan terhadap data teks/biner, gambar (JPEG, PNG, TIFF), audio (MP3, AAC, RMA, WMA), dan video (MPEG, H261, H263).

Langkah-Langkah Aplikasi

Pembuatan

Kompresi

Aplikasi kompresi yang kami buat, menggunakan MATLAB 7, yaitu software yang digunakan sebagai alat pemrograman standar bidang matematika, rekayasa dan keilmuan yang terkait. MATLAB menyediakan beberapa pilihan untuk dipelajari yaitu metode visualisasi dan pemrograman.. Ada beberapa tahap dalam pembuatannya, tahap pertama adalah membuat design figure sseperti gambar berikut

Design figure merupakan tahap untuk mendesain tampilan dari aplikasi yang akan dibuat. Ada beberapa component palette yang digunakan, yaitu dua buah axes untuk menampilkan gambar asli dan gambar hasil konversi. Kemudian ada beberapa static text untuk menampilkan nama file dan ukuran dari gambar yang dibuka serta yang telah di kompressi. Selain itu ada pula pushbutton yang berfungsi untuk menyediakan menu dari aplikasi ini yaitu, buka gambar, kompres, dan keluar. Untuk mengedit atau mengatur component pallet, klik dua kali pada pallete yang ingin diedit dan akan keluar tampilan property inspector

Setelah membuat desain, selanjutnya adalah membuat source code program. Untuk memulai membuatnya, buka layout figure yang telah dibuat kemudian klik kanan pada figure dan pilih M-file, kemudian ketik source code pada editor M-file

Pada function buka_Callback, kita ketikkan source code seperti berikut[nama_file1, {'*.bmp;,*.jpg','File nama_path1]=uigetfile( Citra(*.bmp,*.jpg)'; ... '*.bmp','File

Bitmap(*.bmp)';... '*.jpg','File File(*.*)'},... 'Buka File ~isequal(nama_file1,

JPEG(*.jpg)'; '*.*','Semua Citra Host/Asli'); if 0)

handles.data1=imread(fullfile(nama_path1,nama_file1)); guidata(hObject,handles); handles.current_data1=handles.data1; imshow(handles.current_data1); set(handles.text2,'String',nama_file1); set(handles.text8,'String',size(handles.data1,1)); set(handles.text11,'String',size(handles.data1,2)); else return; end axes(handles.citra1);

script tersebut menjelaskan bahwa pada function buka_Callback terdapat fungsi uigetfile yang digunakan untuk membaca file citra dengan format yang ditentukan yaitu *.bmp, *.jpg sebagai filter. Berikutnya ketikkan script berikut pada function kompres_Callback[nama_file_simpan, path_simpan]=uiputfile(... {'*.jpg','File citra(*.jpg)'; '*.jpg','Citra imwrite(handles.data1, nama_file_simpan)); citra_kompres=imread(fullfile(path_simpan, nama_file_simpan)); axes(handles.citra2); guidata(hObject,handles); imshow(citra_kompres); JPEG(*.jpg)';... '*.*','Semua fullfile(path_simpan, File(*.*)'},... 'Menyimpan File Citra Hasil Kompresi JPEG');

set(handles.text4,'String',nama_file_simpan);

set(handles.text12,'String',size(handles.data1,1)); set(handles.text13,'String',size(handles.data1,2));

script tersebut menyatakan bahwa terdapat fungsi uigetfile pada function kompres_Callback yang digunakan untuk membuat file citra yang di kompresi akan berformat *.jpg apapun format awal file citra tersebut. Terakhir adalah mengetikkan script pada bagian function keluar_Callback, script yang diketikkan adalah

selection=questdlg(['Keluar ['Keluar 'Ya','Tidak','Ya'); if return; end delete(handles.figure1) '

'

get(handles.figure1,'Name')''],... get(handles.figure1,'Name')''],...

strcmp(selection,'Tidak')

Script tersebut berfungsi menampilkankotak dialog yang berisi dua pushbutton yaitu Ya dan Tidak yang akan menanyakan apakah pengguna ingin keluar dari aplikasi atau tidak. Hasil dari aplikasi ini jika dijalankan adalah sebagai berikut,

Tampilan Awal

Tampilan Pilih Menu Buka Gambar

Tampilan Gambar Asli

Tampilan Pilih Menu Kompres (simpan nama file hasil kompresi)

Tampilan Gambar Asli & Gambar Kompresi

Tampilan Menu Keluar

Aplikasi Kompresi Gambar menggunakan MATLABPosted: 26 November 2010 in Tidak terkategori

3 Nama Anggota Kelompok PPC : 1. Achmad Thohir (50407016)

2. Wenny Rahmawati (50407891) Pengolahan Citra adalah Pemrosesan citra, khususnya dengan menggunakan komputer, menjadikan citra dengan kualitas yang lebih baik. Pengolahan Citra bertujuan untuk memperbaiki kualitas citra agar mudah diinterprestasi oleh manusia atau mesin (dalam hal ini komputer). Teknik-teknik pengolahan citra mentransformasikan citra menjadi citra lain, salah satunya adalah kompresi citra (image compression). Jadi, masukannya adalah citra dan keluarannya juga citra, namun citra keluarannya mempunyai ukuran citra lebih kecil daripada citra masukannya. Kompresi merupakan proses untuk menghilangkan berbagai kerumitan yang tidak penting (redudansi) dari suatu informasi dengan cara memadatkan isi file sehingga ukurannya menjadi lebih kecil dengan memaksimalkan kesederhanaannya dan tetap menjaga kualitas penggambaran dari informasi tersebut. Aplikasi kompresi yang saya buat menggunakan masukan (input) berupa citra dengan beberapa format seperti format JPEG, Bitmap, PNG, dan TIF dan menghasilkan keluaran (output) berupa citra dengan format JPEG. Langkah langkah pembuatan Program Kompresi A. Membuat Desain Figure Aplikasi kompresi ini dibuat menggunakan MATLAB 7.1 dengan membuat sebuah user interface MATLAB dengan fasilitas GUIDE. Untuk membuat sebuah user interface dimulai dengan mmbuat desain sebuah figure dengan memanfaatkan uicontrol (control user interface) yang tersedia di editor figure. Uicontrol yang digunakan untuk membuat aplikasi kompresi ini adalah : 1. Axes Axes digunakan untuk menampilkan sebuah grafik atau gambar (image). Pada pembuatan aplikasi ini digunakan 2 Axes yang digunakan untuk menampilkan citra asli dan citra kompresi. 2. Static Text Static Text akan menghasilkan teks bersifat tetap sehingga user tidak dapat melakukan perubahan. Teks dan beberapa fasilitas lainnya dapat diatur dalam static text. Seperti jenis dan ukuran font, warna dll. Pada pembuatan aplikasi kompresi ini terdapat 2 static text yaitu Nama file untuk citra masukan dan Nama file untuk citra keluaran. 3. Pushbutton Pushbutton merupakan jenis control berupa tombol tekan yang akan menghasilkan sebuah tindakan jika diklik. Pada pembuatan aplikasi ini, pushbutton yang digunakan adalah Pilih Gambar, Kompres dan Keluar. Berikut adalah Desain Aplikasi Kompres JPEG :

Pembuatan Source Code Program Kompresi Penulisan source code pada pembuatan aplikasi dengan MATLAB menggunakan editor M-file. a. Buka Layout Figure yang telah dibuat, lalu klik kanan pada figure pilih M-file. b. Ketikkan source code pada Editor M-file. Program kompresi ini disimpan dengan nama PPC.fig. Pada MATLAB terdapat function yang tersedia secara otomatis seperti dibawah ini : function varargout = PPC(varargin) % PPC M-file for PPC.fig % % % % % % % % % PPC(CALLBACK,hObject,eventData,handles,) calls the local function named CALLBACK in PPC.M with the given input arguments. H = PPC returns the handle to a new PPC or the handle to the existing singleton*. PPC, by itself, creates a new PPC or raises the existing singleton*.

% % % % % % % % %

PPC(Property,'Value,) creates a new PPC or raises the existing singleton*. Starting from the left, property value pairs are applied to the GUI before PPC_OpeningFunction gets called. An unrecognized property name or invalid value makes property application stop. All inputs are passed to PPC_OpeningFcn via varargin.

*See GUI Options on GUIDEs Tools menu. Choose GUI allows only one instance to run (singleton).

% See also: GUIDE, GUIDATA, GUIHANDLES % Edit the above text to modify the response to help PPC % Last Modified by GUIDE v2.5 23-Nov-2010 15:28:23 % Begin initialization code DO NOT EDIT gui_Singleton = 1; gui_State = struct( gui_Name, gui_Singleton, gui_OpeningFcn, gui_OutputFcn, gui_LayoutFcn, gui_Callback, gui_Singleton, @PPC_OpeningFcn, @PPC_OutputFcn, [] , []); mfilename,

if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end

if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code DO NOT EDIT % Executes just before PPC is made visible. function PPC_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to PPC (see VARARGIN) % Choose default command line output for PPC handles.output = hObject; % Update handles structure guidata(hObject, handles); % UIWAIT makes PPC wait for user response (see UIRESUME) % uiwait(handles.figure1); % Outputs from this function are returned to the command line. function varargout = PPC_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure

% eventdata reserved to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; % Executes on button press in buka. function buka_Callback(hObject, eventdata, handles) % hObject handle to buka (see GCBO) % eventdata reserved to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) %Bagian ini merupakan bagian yang mengatur satuan gambar yang digunakan untuk kompresi citra masukan. [nama_file1, nama_path1]=uigetfile( {*.bmp;,*.jpg,'File Citra(*.bmp,*.jpg); *.bmp,'File Bitmap(*.bmp); *.jpg,'File JPEG(*.jpg); *.*,'Semua File(*.*)}, Buka File Citra Host/Asli); if ~isequal(nama_file1, 0) handles.data1=imread(fullfile(nama_path1,nama_file1)); guidata(hObject,handles); handles.current_data1=handles.data1; axes(handles.Gambar1); imshow(handles.current_data1); set(handles.text2,String,nama_file1);

else return; end % Executes on button press in kompres. function kompres_Callback(hObject, eventdata, handles) % hObject handle to kompres (see GCBO) % eventdata reserved to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) %Bagian ini menunjukkan bahwa hasil kompresi hanya akan berformat .jpg [nama_file_simpan, path_simpan]=uiputfile( {*.jpg,'File citra(*.jpg); *.jpg,'Citra JPEG(*.jpg); *.*,'Semua File(*.*)}, Menyimpan File Citra Hasil Kompresi JPEG); imwrite(handles.data1, fullfile(path_simpan, nama_file_simpan)); citra_kompres=imread(fullfile(path_simpan, nama_file_simpan)); guidata(hObject,handles); axes(handles.Gambar2); imshow(citra_kompres); set(handles.text4,String,nama_file_simpan); % Executes on button press in keluar. function keluar_Callback(hObject, eventdata, handles) % hObject handle to keluar (see GCBO)

% eventdata reserved to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) %Bagian ini merupakan perintah untuk kotak dialog keluar selection=questdlg(['Keluar ' get(handles.figure1,'Name')''], ['Keluar ' get(handles.figure1,'Name')''], Ya,Tidak,Ya); if strcmp(selection,Tidak) return; end delete(handles.figure1)

c. Setelah di compile dan di run, hasilnya seperti ini :

d. Jika kita memilih button Pilih Gambar, maka akan muncul kotak dialog seperti dibawah ini :

e. Selanjutnya kita pilih gambar yang kita inginkan masing-masing. Dalam hal ini saya memilih file nolte.bmp

f. Langkah selanjutnya setelah kita memilih button kompress, program ini terlebih dahulu meminta direktori yang akan menjadi tempat tujuan disimpannya file gambar tersebut setelah dikompresi. Lihat kotak dialog dibawah ini :

g. Hasil kompresi dapat dilihat dibawah ini. Perubahan terjadi, gambar masukan awalnya berformat .bmp menjadi .jpg dengan ukuran yang lebih kecil.

h. Dan jika kita memilih button Keluar, muncul kotak dialog untuk memastikan apakah kita serius untuk keluar dari program kompresi ini.

Selamat Mencoba!% MATLAB 4.2c JPEG image compression program % by Scott Teresi, www.teresi.us % March 15-17, 1997 % Data Classification and Compression class % Dr. Salari, Univ. of Toledo % This program compresses an image using the JPEG algorithm % Enter matlab, then type the name of this file (jpeg) to execute it. % It requires a ".mat" file containing raw black-and-white image data % stored in matrix variable "X". The matrix contains the pixel intensities. % Also, store a colormap in variable "map" (see first few lines of program). % Initializations

clear load lenna matrix orig_img = X; quant_multiple = 1; levels file) blocksize = 8; 8) DCT_quantizer = ... matrix) [ 16 11 10 12 12 14 14 13 16 14 17 22 18 22 37 24 35 55 49 64 78 72 92 95

% clear all variables from previous sessions % load file of variables containing a gray image % image matrix was stored in variable X % image colormap is stored in variable map % set the multiplier to change size of quant. % (fractions decrease distortion) % vary quant_mult from .1 to 3 (see jpeg.results % set the size of chunks to take the DCT of ( =< % levels for quantizing the DCT block (8x8 16 24 40 19 26 58 24 40 57 29 51 87 56 68 109 64 81 104 87 103 121 98 112 100 51 61; ... 60 55; ... 69 56; ... 80 62; ... 103 77; ... 113 92; ... 120 101; ... 103 99 ];

sz = size(orig_img); rows = sz(1,1); cols = sz(1,2); colors = max(max(orig_img)); image % % % % % % % %

% finds image's rows and columns % guess at the number of colors in the

Replace a color colormap with a grayscale one map_sz = size(map); clrs = map_sz(1,1); gray_map = (0:clrs-1)' / (clrs-1); gray_map = [gray_map gray_map gray_map]; map = gray_map; colormap(map)

% Introduction str = str2mat( ... 'Scott Teresi, March 1997.', ... 'This program implements the JPEG data compression algorithm.'); ssdisp(0, str); fprintf fprintf fprintf fprintf fprintf (1, (1, (1, (1, (1, 'Image used: 'Its size is: 'Number of colors (guess): 'DCT block size: 'Quant. size multiplier: lenna.mat\n'); %dx%d\n', rows, cols); %d\n', colors); %dx%d\n', blocksize, blocksize); %d\n', quant_multiple);

% Display the original image figure(1) image(orig_img) colormap(map) title('Original image') figure(2)

% Prepare image for transform % Level-shift the image (center intensity values around 0) orig_img = orig_img - ceil(colors/2); % Replicate edges of image to make its dimensions a multiple of blocksize pad_cols = (1 - (cols/blocksize - floor(cols/blocksize))) * blocksize; if pad_cols == blocksize, pad_cols = 0; end pad_rows = (1 - (rows/blocksize - floor(rows/blocksize))) * blocksize; if pad_rows == blocksize, pad_rows = 0; end for extra_cols = 1:pad_cols orig_img(1:rows, cols+extra_cols) = orig_img(1:rows, cols); end cols = cols + pad_cols; % orig_img is now pad_cols wider

for extra_rows = 1:pad_rows orig_img(rows+extra_rows, 1:cols) = orig_img(rows, 1:cols); end rows = rows + pad_rows; % orig_img is now pad_rows taller

% calculate the DCT transform matrix % (from page 336 of the Intro to Data Compression book) i = 0; for j = 0: blocksize - 1 DCT_trans(i + 1, j + 1) = sqrt(1 / blocksize) ... * cos ((2 * j + 1) * i * pi / (2 * blocksize)); end for i = 1: blocksize - 1 for j = 0: blocksize - 1 DCT_trans(i + 1, j + 1) = sqrt(2 / blocksize) ... * cos ((2 * j + 1) * i * pi / (2 * blocksize)); end end

% Take DCT of blocks of size blocksize fprintf(1, '\nFinding the DCT and quantizing...\n'); starttime = cputime; % "cputime" is an internal cpu time counter jpeg_img = orig_img - orig_img; image for row = 1: blocksize: rows for col = 1: blocksize: cols % take a block of the image: DCT_matrix = orig_img(row: row + blocksize-1, col: col + blocksize1); % perform the transform operation on the 2-D block % (from page 331 of the Intro to Data Compression book) DCT_matrix = DCT_trans * DCT_matrix * DCT_trans'; % quantize it (levels stored in DCT_quantizer matrix): DCT_matrix = floor (DCT_matrix ... ./ (DCT_quantizer(1:blocksize, 1:blocksize) * quant_multiple) + 0.5); % place it into the compressed-image matrix: jpeg_img(row: row + blocksize-1, col: col + blocksize-1) = DCT_matrix; end end fprintf(1, ' CPU time used: %1.3f\n', (cputime - starttime)) % zero the matrix for the compressed

% Reverse the process (take the Inverse DCT) fprintf(1, 'Reconstructing quantized values and taking the inverse DCT...\n'); starttime = cputime; recon_img = orig_img - orig_img; reconstructed image for row = 1: blocksize: rows for col = 1: blocksize: cols % take a block of the image: IDCT_matrix = jpeg_img(row: row + blocksize-1, col: col + blocksize-1); % zero the matrix for the

% reconstruct the quantized values: IDCT_matrix = IDCT_matrix ... .* (DCT_quantizer(1:blocksize, 1:blocksize) * quant_multiple); % perform the inverse DCT: IDCT_matrix = DCT_trans' * IDCT_matrix * DCT_trans; % place it into the reconstructed image: recon_img(row: row + blocksize-1, col: col + blocksize-1) = IDCT_matrix; end end fprintf(1, ' CPU time used: %1.3f\n', (cputime - starttime))

% Restore image to normal % Level-shift the image back recon_img = recon_img + ceil(colors/2); orig_img = orig_img + ceil(colors/2); % Clip off padded rows and columns rows = rows - pad_rows; cols = cols - pad_cols; recon_img = recon_img(1:rows, 1:cols); % Display image colormap(map) image(recon_img) title('Decompressed JPEG image')

% Calculate signal-to-noise ratio fprintf(1, 'Finding the signal-to-noise ratio...\n'); starttime = cputime; PSNR = 0; for row = 1:rows for col = 1:cols PSNR = PSNR + (orig_img(row, col) - recon_img(row, col)) ^ 2; end end PSNR = 10 * log10 ((255^2) / (1 / (((rows + cols) / 2) ^ 2) * PSNR)); % (averaged rows and cols together) fprintf(1, ' CPU time used: %1.3f\n', (cputime - starttime))

fprintf(1, '\nThe signal-to-noise ratio (PSNR) is: %1.3f dB\n\n', PSNR);

JPEG colour compression using MATLABclc; img = imread('lena.bmp'); % JPEG compression jpegcompression(img,'lena_compressed.mat'); % JPEG decompression Irec = jpegrestoration('lena_compressed.mat'); % System performances [CR,BPP,PSNR,MSE,SNR] = systemperformances(img,Irec,'lena_compressed.mat'); % Plotting figure,subplot(1,2,1),imshow(img),title('Original image'),... subplot(1,2,2),imshow(Irec),title('Decompressed image'); disp('Compression ratio:'); disp(CR); disp('Bits per pixel:'); disp(BPP); disp('Peak signal to noise ratio:'); disp(PSNR); disp('Mean squared error:'); disp(MSE); disp('Signal to noise ratio'); disp(SNR); function [CR,BPP,PSNR,MSE,SNR]=systemperformances(I0,I1,compressed_data_file) % Performances of compression algorithm % INPUT: % I0: original image % I1: decompressed image % compressed_data_file: file name of cmpressed data % OUTPUT: % Ires: reconstructed image % CR: compression ratio % BPP: bits per pixel % PSNR: peak signal to noise ratio % MSE: mean squared error % SNR: signal to noise ratio %img = imread('lena.bmp'); % JPEG compression %jpegcompression(img,'lena_compressed.mat'); % JPEG decompression %Irec = jpegrestoration('lena_compressed.mat'); I0 = imread('lena.bmp'); % JPEG compression jpegcompression(I0,'lena_compressed.mat'); % JPEG decompression I1 = jpegrestoration('lena_compressed.mat'); I0 = double(I0); I1 = double(I1); if ndims(I0)==3 size0 = 3*8*size(I0,1)*size(I0,2); else

size0 = 1*8*size(I0,1)*size(I0,2); end file1 = dir(compressed_data_file); size1 = 8*file1.bytes; % Compression ratio CR = size0/size1; % Bits per pixel BPP = size1/(size(I0,1)*size(I0,2)); % Difference signal Id = (I0-I1); signal = sum(sum(I0(:).^2)); noise = sum(sum(Id(:).^2)); SNR = 10*log10(signal/noise); MSE = noise/numel(I0); peak = max(I0(:)); PSNR = 10*log10(peak^2/MSE);