0% found this document useful (0 votes)
8 views16 pages

IP Japson

The document outlines procedures for converting colored images between various color spaces including RGB, HSI, YCbCr, and LAB, detailing the mathematical transformations involved. It also discusses the concepts of sampling and quantization in digital imaging, emphasizing their impact on image quality and resolution. The document includes MATLAB code examples for practical implementation of these conversions and processes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views16 pages

IP Japson

The document outlines procedures for converting colored images between various color spaces including RGB, HSI, YCbCr, and LAB, detailing the mathematical transformations involved. It also discusses the concepts of sampling and quantization in digital imaging, emphasizing their impact on image quality and resolution. The document includes MATLAB code examples for practical implementation of these conversions and processes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Ex. No: 3.

a
Date: Colorspaceconversion(RGBtoHSV,YCbCrcolorspace)

Aim:

i. To convertthe coloredimagefromone colorspacetoothercolorspace.


ii. Toperformsamplingandquantization forthegiven image.

HardwareandSoftware Required:
Pentiumprocessorcorei3,WindowsOperatingsystem,Matlab2017orlaterversion, and
Webcam

Color spaceConversion:

i. RGB TO HSI:

Intensity:I=(R +G+B) / 3
Saturation:S=1-(3/(R+G+B+esp))*min(R,G,B)
Hue:
Theta=cos^(-1)((0.5*[(R-G)+(R-B)])/sqrt((R-G)^2+(R-B)(G-B)+eps))
Adjusthuetodifferentcases:
H=theta
IfB>G,H=(2*pi)-H
H=H/(2*pi) (Normalisetorange[0,1])
HSIimage=(H,S,I)

ii. HSItoRGB:

Intermediatevalues:

X=I*(1-S)

Y=I*(1+S*cosH/cos(60deg-H))

Z=3I=(X+Y)

HueH(degree)isdividedinto 3 regions:
1) 0<=H<=120–Redsector
R=Y, G=Z, B=X
2) 120<=H<=240–Greensector
R=X, G=Y, B=Z
3) 240<=H<=360–Bluesector
R=Z, G=X, B=Y

RGB image=(R,G,B)
iii. RGB toYCbCr:

Y=0.299R+0.587G+ 0.114B

Cb=128+(-0.168736R-0.331264G+0.5B)

Cr=128+(0.5R - 0.418688G - 0.081312B)

iv. YCbCrtoRGB:(Y,Cb,Crareinrange[0,1])

R=Y+1.402Cr

G=Y-0.344136Cb-0.714136Cr

B=Y+1.773Cb

v. RGB to LAB:

1) NormaliseRGB
R(norm)=R/255;G(norm)=G/255; B(norm)=B/255
2) Gammacorrection
ForeachchannelC(whereCcanbeR(norm),G(norm)orB(norm)) C(linear)=
C(norm)/12.92, if C(norm)<=0.04045
=((C(norm)+0.055)/1.055)^2.4,if C(norm)>0.04045
3) XYZtransformation
X 0.4124564 0.3575761 0.1804375 R(linear)
Y = 0.2126729 0.7151522 0.0721750 G(linear)
Z 0.0193339 0.1191920 0.9503041 B(linear)

4) NormaliseXYZ
x=X/Xn,y=Y/Yn,z=Z/Zn whereXn=95.047,Yn=100.00,Zn=108.83
5)
f(t)=t^(1/3),if t>0.008856
=7.787t +(16/116),ift<=0.008856

 L(lightness)=116f(y)–16
 A=500(f(x)–f(y))
 B=200(f(y)–f(z))
Program:
i. RGBtoHSIColorconversion

rgbImage=imread(‘vimal.jpg’);
rgbImage=im2double(rgbImage)
; R = rgbImage(:,:,1);
G= rgbImage(:,:,2);
B= rgbImage(:,:,3);
I= (R +G +B)/ 3;
minRGB=min(min(R,G),B);
S = 1 - (3 ./ (R + G + B + eps)) .* minRGB;
theta=acos((0.5 *((R -G) +(R -B)))./sqrt((R-G).^2 +(R -B).*(G-B)+
eps));
H= theta;
H(B>G)=2*pi -H(B>G);
H=H/(2*pihsiImage = cat(3, H, S, I);
figure;
subplot(1, 2, 1), imshow(rgbImage), title('Original RB Image');
subplot(1,2,2),imshow(hsiImage),title('ConvertedHSIImage');

Simple RGB to HSIconversion:

rgb = imread('Sakthi.jpg'); % Load an RGB image


hsiImage=rgb2hsi(rgb);%ConverttoHSIcolorspace
hsvImage=rgb2hsv(rgb);%ConverttoHSVcolorspace
figure;
subplot(1, 2, 1), imshow(rgb), title('Original RGB Image');
subplot(1,2,2),imshow(hsiImage),title('ConvertedHSIImage');
imwrite(hsiImage,'HSI.jpg');

ii. HSItoRGBColor conversion

hsiImage=im2double(imread('HSI.jpg'));%Ensuretheimageisin[0,1] H =

hsiImage(:,:,1);
S= hsiImage(:,:,2);
I= hsiImage(:,:,3);

[m,n]=size(H); R =

zeros(m, n);
G=zeros(m, n);
B=zeros(m, n);

fori =1:m
forj = 1:n
h=H(i,j)*2*pi;%Convertfrom[0,1]to[0,2π] s = S(i, j);
in=I(i, j);
if h >= 0 && h < 2*pi/3 %RGsector
B(i, j) = in * (1 - s);
R(i,j)=in*(1+s*cos(h)/cos(pi/3-h));
G(i,j)=3*in-(R(i,j)+B(i,j));

elseif h >= 2*pi/3 && h < 4*pi/3 %GBsector


h = h - 2*pi/3;
R(i,j)=in*(1-s);
G(i,j)=in*(1+s*cos(h)/cos(pi/3-h));
B(i,j)=3*in-(R(i,j)+G(i,j));

else %BRsector
h=h - 4*pi/3;
G(i,j)=in*(1-s);
B(i,j)=in*(1+s*cos(h)/cos(pi/3-h));
R(i,j)=3*in-(G(i,j)+B(i,j));
end
en
en d
d

rgbImage=cat(3,R,G,B);
subplot(1, 2, 1), imshow(hsiImage), title('Original HSI
Image');
subplot(1,2,2),imshow(rgbImage),title('ConvertedRGBImage');

iii. RGBtoYCbCr Colorconversion

YCbCrcolorspace,whichiswidelyusedinvideocompression(e.g.,JPEG,MPEG)dueto its
separation of luminance (Y) and chrominance (Cb, Cr)

rgbImage=imread('Sakthi.jpg');
rgbImage=im2double(rgbImage);%Normalizeto[0,1]

%DefinethetransformationmatrixforRGBtoYCbCr T
= [0.299,0.587,0.114; % Y
-0.1687,-0.3313,0.5; %Cb
0.5, -0.4187,-0.0813];%Cr

%ReshapeRGBchannelsformatrixmultiplication
[m, n, ~] = size(rgbImage);
rgbVector=reshape(rgbImage,[],3);%FlattentoNx3

% Apply the transformation


ycbcrVector=rgbVector*T';

% Add offsets for Cb and Cr channels


ycbcrVector(:,2:3)=ycbcrVector(:,2:3)+0.5;

%Reshapebacktoimagesize
ycbcrImage=reshape(ycbcrVector,m,n,3);

%Displaytheresults
figure;
subplot(1, 2, 1), imshow(rgbImage), title('Original RGB Image');
subplot(1,2,2),imshow(ycbcrImage),title('ConvertedYCbCrImage');
imwrite(ycbcrImage,'YCBCR.jpg');
iv. YCbCr toRGBColor conversion

%ReadtheinputYCbCr image
ycbcrImage1=im2double(imread('YCBCR.jpg'));%Ensureit'sin[0,1]range

%Getthedimensionsoftheimage
[m,n,~]=size(ycbcrImage1);%Extractimagedimensions

%Definetheinversetransformationmatrix(YCbCrtoRGB)
T_inv = [1,0, 1.402; % R
1,-0.3441,-0.7141;%G
1,1.772, 0]; %B

% Subtract offsets from the Cb and Cr channels


ycbcrImage(:,:,2:3)=ycbcrImage1(:,:,2:3)-0.5;

% Reshape the YCbCr image for matrix multiplication


ycbcrVector=reshape(ycbcrImage,[],3);%FlattentoNx3

%ApplythetransformationtoconvertYCbCrtoRGB rgbVector
= ycbcrVector * T_inv';

%Reshapebacktotheoriginalimagedimensions
rgbImage = reshape(rgbVector, m, n, 3);

%Clipvaluesto[0,1]toavoidoverfloworunderflow
rgbImage = max(min(rgbImage, 1), 0);

%DisplaytheRGBimage
subplot(1,2,1),imshow(ycbcrImage1),title('OriginalYCbCrImage');
subplot(1, 2, 2), imshow(rgbImage), title('Converted RGB Image');

v. RGB to LAB Color conversion:

LABcolorspace isoftenusedincomputer visionandimage processingfor coloranalysis because it


separates luminance (L) from color information (A and B).

% Read the input RGB image


rgbImage=imread('Sakthi.jpg');
rgbImage=im2double(rgbImage);%Normalizeto[0,1]

%ConvertRGBtoXYZ.Constantsforthetransformation
M= 0.357580, 0.180423;
[0.412453,
0.212671, 0.715160, 0.072169; %RGBtoXYZmatrix
0.019334, 0.119193, 0.950227];

%NormalizeRGBandreshapefortransformation [m,
n, ~] = size(rgbImage);
rgbVector=reshape(rgbImage,[],3);%FlattentoNx3

%ApplyRGBtoXYZconversion
xyzVector = rgbVector * M';
xyzVector=xyzVector./[0.95047,1.00000,1.08883];
%NormalizeforD65reference white
%Defineahelperfunctionforf(t)inLAB conversion
f=@(t)(t>0.008856).*(t.^(1/3))+(t<=0.008856).*(7.787.*t+ 16/116);

%Applythef(t)function fX
= f(xyzVector(:, 1));
fY=f(xyzVector(:,2));
fZ=f(xyzVector(:,3));

%CalculateL,A,B L
= 116 * fY - 16;
A= 500* (fX-fY);
B= 200* (fY-fZ);

%CombineL,A,B intoanLABimage
labImage=reshape(cat(2,L,A,B),m,n,3);
figure;
subplot(1,2,1),imshow(rgbImage),title('OriginalRGBImage');
subplot(1,2,2),imshow(labImage/max(L(:))),title('ConvertedLABImage');

Inferences:

 RGB: The most common color model used in digital imaging.RGB is not ideal
forhuman perception-based adjustments like brightness and saturation modifications.
 HSI:Commoninimageenhancement,object detection,andfeatureextraction.
 HSV:Similar to HSIbut uses Value (V)instead of Intensity (I). Preferred in graphics
software, computer vision, and color-based object recognition.
 TheYCbCrcolor spaceseparates animageinto luminance(Y) and chrominance
(Cb, Cr) components. (Blue Chrominance): Represents blue color difference. Cr (Red
Chrominance):Represents red color difference.
 LABisdesignedtomatchhumanvisionperceptionandisdevice-independent. L
(Lightness): Represents brightness (0 = black, 100 = white).
A(Green-RedChannel): Negativevalues indicate green,positiveindicatered.
B (Blue-Yellow Channel): Negativevalues indicate blue,positive indicateyellow.

Result:

The experiment demonstrates the conversion between different colour spaces (RGB,
HSI, HSV) and their impact on image representation and processing. This experiment
highlights the importance of selecting the right colour space based on the application.
Ex.No: 3.b
Date: Sampling and Quantization

Aim:

i. Toperformsampling andquantization forthe givenmatrix anddigital image.

HardwareandSoftware Required:
Pentiumprocessorcorei3,WindowsOperatingsystem,Matlab2017orlaterversion, and
Webcam

SamplingandQuantization:

Sampling:Sampling refers to the process of selecting discrete pixel locations from a


continuous image. It determines spatial resolution—how finely an image is divided into
pixels. A continuous image has infinite points, but digital images have a finite number of
pixels arranged in a grid.

Highersamplingrate→Morepixels→Betterspatialresolution(sharperimage). Lower
sampling rate → Fewer pixels → More blocky or pixelated images.
Example:
High sampling → 512×512 pixels
Lowsampling →32×32 pixels(blurry &blocky)

Quantization:Quantizationistheprocessofmappingcontinuouspixelintensityvaluesintoa finite
number of levels. It determines color or grayscale depth. An image usually has intensity
values from 0 to 255 (8-bit grayscale, 256 levels).

More quantization levels → Smoother shading & better quality.


Fewer quantization levels → Posterization (loss of smooth shading).
Example:
8-bit quantization → 256 intensity levels (smooth shading)3-
bit quantization → 8 intensity levels (visible banding)
Program:

i.DownSamplingwithMatrix:

clcclose
all
clearall
a=[1,2,3,4;5,6,7,8;9101112;13141516;17181920];
[rx,cx]=size(a)
er=3;
ec=3;
rsf=rx/er;
csf=cx/ec;
b=[]
c=1
fori =1:er
forj =1:ec
b(c)=(i-1)*rsf;
b(c+1)=(j-1)*csf;
c=c+2;
end
end
f=floor(b);
c=1
fori =1:er
forj=1:ec
s(i,j)=a(f(c)+1,f(c+1)+1);
c=c+2;
end
end
disp(a)
disp(s)

Output:

ii Down Sampling withimage:

a=imread('Sakthi.jpg');
a=rgb2gray(a);
[rx,cx]=size(a);
er=input('Enter Downsampled rows: ');
ec=input('EnterDownsampledColumns:');
rsf=rx/er;
csf=cx/ec;
b=[]
c=1;
fori =1:er
forj =1:ec
b(c)=(i-1)*rsf;
b(c+1)=(j-1)*csf;
c=c+2;
end
end
f=floor(b);
c=1
fori =1:er
forj=1:ec
s(i,j)=a(f(c)+1,f(c+1)+1);
c=c+2;
en
d
endfigur
e
subplot(1,2,1);imshow(a)
title('Original
Grayscale','FontSize',20);
subplot(1,2,2);imshow(imresize(s,
[rxcx])) title('Down-sampled
Image','FontSize',20)

Output:

iii. Upsamplingfor matrix


r=input('Enterthenumberofrowsforthematrix:');
c=input('Enterthenumberofcolumnsforthematrix:');

M=zeros(r, c);
disp('Enterthematrixelements:');
for i = 1:r
forj = 1:c
M(i,j)=input(sprintf('Element(%d,%d):',i,j));
end
end
disp('OriginalMatrix:');
disp(M);
sf=input('Enterthesamplingfactor:'); Row
= sf * r;
Col= sf* c;
b=zeros(Row,Col);
for i = 1:Row
forj = 1:Col
row = ceil(i / sf);
col = ceil(j / sf);
b(i,j)=M(row,col);
end
end

disp('UpsampledMatrix:')
; disp(b);

Output:

iv. Upsampling with an Image:

clc;clearall;closeall;
a=imread('Sakthi.jpg');
a=rgb2gray(a);
r=input('enter number of rows to be in initial image:');
c=input('enternumberofcolumnstobeininitialimage:');
a=imresize(a,[r c]);
sf=input('entertheupsamplingfactor:');
for i=1:(r*sf)
for j=1:(c*sf)
row=floor(1+((i-1)/(sf))
);
col=floor(1+((j-1)/(sf)));
b(i,j)=a(row,col);
end
end
figure
imshow(a
)
title('imputImage','FontSize',15)
figure
imshow(b
)
title('upsampledImage','FontSize',15)

Output:

v. Quantization:

a= imread('Sakthi.jpg');
a=rgb2gray(a);%Ensuregrayscale

z=input('Enterresultantbits(e.g.,6,2,1):'); z_lvl

= (2^z) - 1;
quan_img1=round(double(a)/255*z_lvl)*(255/z_lvl);

%Additionalquantizedimagesfor visualization
quan_img2=round(double(a)/255*3)*(255/3);%2-bit(4levels)
quan_img3=round(double(a)/255*1)*(255/1);%1-bit(2levels)

%Displayresults
figure;
subplot(2,2,1),imshow(a),title('OriginalImage','FontSize',10);
subplot(2, 2, 2), imshow(uint8(quan_img1)),
title(sprintf('%d-
bitQuantizedImage',z),'FontSize',10);

subplot(2,2,3),imshow(uint8(quan_img2)),
title('2-
bitQuantizedImage','FontSize',10);
subplot(2, 2, 4),
imshow(uint8(quan_img3)), title('1-
bitQuantizedImage','FontSize',10);

Output:

Inferences:

 Highersamplingratesretainmoredetails,whilelowersamplingratesresult inaloss of fine


details and pixelation (blocky appearance).Very low sampling rates cause aliasing,
where fine details appear distorted or missing

 A higher number of levels (e.g., 256 levels for an 8-bit image) preserves smooth
transitionsandfinedetails.Lowerquantizationlevels(e.g.,4-bit,2-bit)introduce
banding effects (visible abrupt changes in intensity) and loss of contrast.

Result:
Theexperimentdemonstratestheeffectsofsamplingandquantizationinimage
processing and their impact on image quality, storage, and perception. This experiment
highlightstheimportanceofselectingappropriatesamplingratesandquantizationlevelsbased on
the application.
i) RGB to HSI

ii) HSItoRGB

iii) RGB to YCbCr

iv) YCbCrtoRGB

v) RGB to LAB
Viva:

1.Give brief description about different colour Spaces and their applications in day to day life

RGB (Red, Green, Blue)


RGB is an additive color model where colors are formed by combining red, green, and blue
light. It is the standard for digital displays, image processing, and multimedia.
Applications: Used in monitors, televisions, digital cameras, web design, gaming, and digital
photography for vibrant color representation.

CMYK (Cyan, Magenta, Yellow, Black)


CMYK is a subtractive color model used in color printing. Unlike RGB, it works by
subtracting colors from a white background using ink or toner.
Applications: Essential in printing for newspapers, magazines, and packaging, ensuring
accurate color reproduction on paper.

HSV (Hue, Saturation, Value)


HSV represents colors based on human perception. Hue defines color type, saturation
determines intensity, and value controls brightness.
Applications: Used in computer vision, image segmentation, video editing, and digital art for
precise color adjustments.

Lab (CIELAB)
The Lab color space is perceptually uniform, ensuring consistent color reproduction across
devices.
Applications: Widely used in professional printing, color calibration, high-end image
processing, and photography.

Grayscale
Grayscale images contain only intensity information, reducing data size and simplifying
processing.
Applications: Common in medical imaging (X-rays, CT scans, MRIs), document scanning,
and security systems for pattern recognition.

HSI (Hue, Saturation, Intensity)


HSI is another perceptual color model similar to HSV and HSL but focuses on intensity
instead of brightness or lightness. It separates chromatic information from intensity, making it
useful for applications requiring color-based image analysis.
Applications: Commonly used in remote sensing, medical imaging, and image recognition
tasks where intensity plays a crucial role in identifying objects.
2.Show the applications related to the respective color spaces and compare them
with non applicable one. Give inference.

1. Natural Landscape

RGB ensures vibrant color display on screens. HSV helps enhance specific features like sky
saturation and brightness adjustments. YCbCr is ideal for compression and noise reduction,
preserving quality while saving storage. LAB aids in precise color correction without affecting
brightness. Each color space optimizes landscape images for display, editing, or compression.

2. Animal Skin Tone

RGB displays the red parrot’s natural colors. HSV highlights hue and saturation for color-based
segmentation. YCbCr separates brightness from color, enhancing compression efficiency. LAB
ensures accurate color reproduction, useful for photography and correction. Each space enhances
the image based on its application.

3. Indoor Image

RGB provides accurate colors on screens. HSV allows easy editing by separating hue, saturation,
and brightness. YCbCr is efficient for compression in JPEG and video formats. LAB ensures
precise color correction, beneficial for interior design and realistic rendering.

4. Pattern Print

RGB is ideal for digital display, creating vibrant colors. HSV helps in color-based segmentation
and object detection. YCbCr improves compression efficiency while maintaining clarity. LAB
offers accurate color correction, useful in pattern analysis. Each space optimizes patterns for its
intended use.

CODE:

clc;
close all;
clear all;
image=imread('image.jpg');
hsvImage=rgb2hsv(image);
YCbCrImage=rgb2ycbcr(image);
labImage=rgb2lab(image);
subplot(2,2,1);imshow(image);
title("Original image");
subplot(2,2,2);imshow(YCbCrImage);
title("YCbCr image");
subplot(2,2,3);
imshow(labImage);
title("LAB image");
subplot(2,2,4);
imshow(hsvImage);
title("HSV image");
OUTPUT:

You might also like