Skip to content

Rachanak2001/Image-processing

Repository files navigation

IMAGE PROCESSING
1. Develop a program to display grayscale image using read and write operation.
pip install opencv-python
import cv2
img=cv2.imread('flower5.jpg',0)
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
OUTPUT
image


2. Develop a program to display the image using matplotlib.
import matplotlib.image as mping
import matplotlib.pyplot as plt
img=mping.imread('plant4.jpg')
plt.imshow(img)
OUTPUT
image


3. develop a program to perform linear transformation. Rotation
import cv2
from PIL import Image
img=Image.open("plant4.jpg")
img=img.rotate(180)
img.show()
cv2.waitKey(0)
cv2.destroyAllWindows()
OUTPUT
image


4. Develop a program to convert colour string to RGB color values.
from PIL import ImageColor
img1=ImageColor.getrgb("Yellow")
print(img1)
img2=ImageColor.getrgb("red")
print(img2)
OUTPUT
(255, 255, 0)
(255, 0, 0)

5. Write a program to create Image using programs.
from PIL import Image
img=Image.new('RGB',(200,400),(255,255,0))
img.show()
OUTPUT
image

6. Develop a program to visualize the image using various color space.
import cv2
import matplotlib.pyplot as plt
import numpy as np
img=cv2.imread('butterfly3.jpg')
plt.imshow(img)
plt.show()
img=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
plt.imshow(img)
plt.show()

img=cv2.cvtColor(img,cv2.COLOR_RGB2HSV)
plt.imshow(img)
plt.show()
OUTPUT
image
image
image

7. Write a program to display the image attributes.
from PIL import Image
image=Image.open('plant4.jpg')
print("FileName: ",image.filename)
print("Format: ",image.format)
print("Mode: ",image.mode)
print("Size: ",image.size)
print("Width: ",image.width)
print("Height: ",image.height)
image.close();
OUTPUT
FileName: plant4.jpg
Format: JPEG
Mode: RGB
Size: (480, 720)
Width: 480
Height: 720


8. Resize the original image.
import cv2
img=cv2.imread('pic12.jpg')
print('origial image length width',img.shape)
cv2.imshow('original image',img)
cv2.waitKey(0)
#to show the resized image
imgresize=cv2.resize(img,(150,160))
cv2.imshow('Resized image',imgresize)
print('Resized image lenght width',imgresize.shape)
cv2.waitKey(0)
OUTPUT
origial image length width (144, 349, 3)
image
Resized image lenght width (160, 150, 3)
image


9. Convert the original image to gray scale and then to binary.
import cv2
#read the image file
img=cv2.imread('butterfly3.jpg')
cv2.imshow("RGB",img)
cv2.waitKey(0)

#Grayscale

img=cv2.imread('butterfly3.jpg',0)
cv2.imshow("Gray",img)
cv2.waitKey(0)

#Binary image

ret,bw_img=cv2.threshold(img,127,255,cv2.THRESH_BINARY)
cv2.imshow("Binary",bw_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
OUTPUT
image
image
image

10.Develop a program to read image using URL.
from skimage import io
import matplotlib.pyplot as plt
url='https://www.thoughtco.com/thmb/mik7Z00SAYN786BQbieXWOzZmc8=/2121x1414/filters:fill(auto,1)/lotus-flower-828457262-5c6334b646e0fb0001dcd75a.jpg'
image=io.imread(url)
plt.imshow(image)
plt.show()

OUTPUT
image


11.Write a program to mask and blur the image.
import cv2
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
img=cv2.imread('fish2.jpg')
plt.imshow(img)
plt.show()
image

hsv_img=cv2.cvtColor(img,cv2.COLOR_RGB2HSV)
light_orange=(1,190,200)
dark_orange=(18,255,255)
mask=cv2.inRange(img,light_orange,dark_orange)
result=cv2.bitwise_and(img,img,mask=mask)
plt.subplot(1,2,1)
plt.imshow(mask,cmap="gray")
plt.subplot(1,2,2)
plt.imshow(result)
plt.show()
image

light_white=(0,0,200)
dark_white=(145,60,225)
mask_white=cv2.inRange(hsv_img,light_white,dark_white)
result_white=cv2.bitwise_and(img,img,mask=mask_white)
plt.subplot(1,2,1)
plt.imshow(mask_white,cmap="gray")
plt.subplot(1,2,2)
plt.imshow(result_white)
plt.show()
image

final_mask=mask+mask_white
final_result=cv2.bitwise_and(img,img,mask=final_mask)
plt.subplot(1,2,1)
plt.imshow(final_mask,cmap="gray")
plt.subplot(1,2,2)
plt.imshow(final_result)
plt.show()
image

blur=cv2.GaussianBlur(final_result,(7,7),0)
plt.imshow(blur)
plt.show()
image

12. Write a program to perform arithmatic operations on image.
import cv2
import matplotlib.image as mping
import matplotlib.pyplot as plt
#Reading image files
img1=cv2.imread('plant1.jpg')
img2=cv2.imread('plant3.jpg')

#Applying Numpy addition on image
fimg1=img1+img2
plt.imshow(fimg1)
plt.show()

#Saving the output image
cv2.imwrite('output.jpg',fimg1)
fimg2=img1-img2
plt.imshow(fimg2)
plt.show()

#Saving the output image
cv2.imwrite('output.jpg',fimg2)
fimg3=img1*img2
plt.imshow(fimg3)
plt.show()

#Saving the output image
cv2.imwrite('output.jpg',fimg3)
fimg4=img1/img2
plt.imshow(fimg4)

plt.show()

#Saving the output image
cv2.imwrite('output.jpg',fimg4)

OUTPUT
image image image image
13.Develop the program to change the image to different color spaces.
import cv2
img=cv2.imread("flower5.jpg")
gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
hsv=cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
lab=cv2.cvtColor(img,cv2.COLOR_BGR2LAB)
hls=cv2.cvtColor(img,cv2.COLOR_BGR2HLS)
yuv=cv2.cvtColor(img,cv2.COLOR_BGR2YUV)
cv2.imshow("GRAY image",gray)
cv2.imshow("HSV image",hsv)
cv2.imshow("LAB image",lab)
cv2.imshow("HLS image",hls)
cv2.imshow("YUV image",yuv)
cv2.waitKey(0)
cv2.destroyAllWindows()


OUTPUT
image
image
image
image
image

14.Program to create an image using 2D array.
import cv2 as c
import numpy as np
from PIL import Image
array=np.zeros([100,200,3],dtype=np.uint8)
array[:,:100]=[255,130,0]
array[:,100:]=[0,0,255]
img=Image.fromarray(array)
img.save('flower5.jpg')
img.show()
c.waitKey(0)

OUTPUT
image

15. Bitwise Operation
import cv2
import matplotlib.pyplot as plt
image1=cv2.imread('pic1.jpg',1)
image2=cv2.imread('pic1.jpg')
ax=plt.subplots(figsize=(15,10))
bitwiseAnd=cv2.bitwise_and(image1,image2)
bitwiseOr=cv2.bitwise_or(image1,image2)
bitwiseXor=cv2.bitwise_xor(image1,image2)
bitwiseNot_img1=cv2.bitwise_not(image1)
bitwiseNot_img2=cv2.bitwise_not(image2)
plt.subplot(151)
plt.imshow(bitwiseAnd)
plt.subplot(152)
plt.imshow(bitwiseOr)
plt.subplot(153)
plt.imshow(bitwiseXor)
plt.subplot(154)
plt.imshow(bitwiseNot_img1)
plt.subplot(155)
plt.imshow(bitwiseNot_img2)
cv2.waitKey(0)

OUTPUT
image

16.Blurring an Image
#importing libraries
import cv2
import numpy as np

image=cv2.imread('pic6.jpg')

cv2.imshow('Original Image',image)
cv2.waitKey(0)

#Gaussian blur
Gaussian=cv2.GaussianBlur(image,(7,7),0)
cv2.imshow('Gaussian Blurring',Gaussian)
cv2.waitKey(0)

#Medium Blur
median=cv2.medianBlur(image,5)
cv2.imshow('Median Blurring',median)
cv2.waitKey(0)

#Bilateral Blur
bilateral=cv2.bilateralFilter(image,9,75,75)
cv2.imshow('Bilateral Blurring',bilateral)
cv2.waitKey(0)
cv2.destroyAllWindows()

OUTPUT
image
image
image
image

17.Enhancement operation
from PIL import Image
from PIL import ImageEnhance
image=Image.open('pic4.jpg')
image.show()
enh_bri=ImageEnhance.Brightness(image)
brightness=1.5
image_brightened=enh_bri.enhance(brightness)
image_brightened.show()
enh_col=ImageEnhance.Color(image)
color=1.5
image_colored=enh_col.enhance(color)
image_colored.show()
enh_con=ImageEnhance.Contrast(image)
contrast=1.5
image_contrasted=enh_con.enhance(contrast)
image_contrasted.show()
enh_sha=ImageEnhance.Sharpness(image)
sharpness=3.0
image_sharped=enh_sha.enhance(sharpness)
image_sharped.show()

OUTPUT
image
image
image
image
image

18. Morphological Operation
import cv2
import numpy as np
from matplotlib import pyplot as plt
from PIL import Image,ImageEnhance
img=cv2.imread('pic1.jpg',0)
ax=plt.subplots(figsize=(20,10))
kernel=np.ones((9,9),np.uint8)
opening=cv2.morphologyEx(img,cv2.MORPH_OPEN,kernel)
closing=cv2.morphologyEx(img,cv2.MORPH_CLOSE,kernel)
erosion=cv2.erode(img,kernel,iterations=1)
dilation=cv2.dilate(img,kernel,iterations=1)
gradient=cv2.morphologyEx(img,cv2.MORPH_GRADIENT,kernel)
plt.subplot(151)
plt.imshow(opening)
plt.subplot(152)
plt.imshow(closing)
plt.subplot(153)
plt.imshow(erosion)
plt.subplot(154)
plt.imshow(dilation)
plt.subplot(155)
plt.imshow(gradient)
cv2.waitKey(0)

OUTPUT
image


**19. Develop a program to **
(i)Read the image ,convert it into grayscale image.
(ii)Write(save) the grayscale image and
(iii) Display the original image and grayscale image.
import cv2
OriginalImg=cv2.imread('pic4.jpg')
GrayImg=cv2.imread('pic4.jpg',0)
isPic=cv2.imwrite('C:\Rachana.K\Data sets\j.jpg',GrayImg)
cv2.imshow('Display original Image',OriginalImg)
cv2.imshow('Dispaly Grayscale Image',GrayImg)
cv2.waitKey(0)
cv2.destroyAllWindows()
if isPic:
print('The image is successfully saved.')

OUTPUT
The image is successfully saved.
image image
image

20. Slicing with background.
import cv2
import numpy as np
from matplotlib import pyplot as plt
image=cv2.imread('pic6.jpg',0)
x,y=image.shape
z=np.zeros((x,y))
for i in range(0,x):
for j in range(0,y):
if(image[i][j]>50 and image[i][j]<150):
z[i][j]=255
else:
z[i][j]=image[i][j]
equ=np.hstack((image,z))
plt.title('Graylevel slicing with background')
plt.imshow(equ,'gray')
plt.show()
OUTPUT
image

21. Slicing without background
import cv2
import numpy as np
from matplotlib import pyplot as plt
image=cv2.imread('pic6.jpg',0)
x,y=image.shape
z=np.zeros((x,y))
for i in range(0,x):
for j in range(0,y):
if(image[i][j]>50 and image[i][j]<150):
z[i][j]=255
else:
z[i][j]=0
equ=np.hstack((image,z))
plt.title('Graylevel slicing without background')
plt.imshow(equ,'gray')
plt.show()

OUTPUT
image

22. Analyse the image data using histogram.
#Histogram
import numpy as np
import skimage.color
import skimage.io
import matplotlib.pyplot as plt
#read the image of a plant seedling as grayscale from the outset
image1 = skimage.io.imread(fname="pic13.jpg")
image = skimage.io.imread(fname="pic13.jpg", as_gray=True)
#display the image
fig, ax = plt.subplots()
plt.imshow(image1, cmap="gray")
plt.show()
fig, ax = plt.subplots()
plt.imshow(image, cmap="gray")
plt.show()
#create the histogram
histogram, bin_edges = np.histogram(image, bins=256, range=(0, 1))
#configure and draw the histogram figure
plt.figure()
plt.title("Grayscale Histogram")
plt.xlabel("grayscale value")
plt.ylabel("pixel count")
plt.xlim([0.0, 1.0])
plt.plot(bin_edges[0:-1], histogram)
plt.show()
OUTPUT
image
image
image

23. Program to perform basic image data analysis using intensity transformation:
a) Image nagative
b)Log Transformation
c)Gamma correction

%matplotlib inline
import imageio
import matplotlib.pyplot as plt
import warnings
import matplotlib.cbook
warnings.filterwarnings("ignore",category=matplotlib.cbook.mplDeprecation)
pic=imageio.imread('pic14.jpg')
plt.figure(figsize=(6,6))
plt.imshow(pic);
plt.axis('off');
OUTPUT
image
a)Image negative
negative=255-pic #neg=(L-1)-img
plt.figure(figsize=(6,6))
plt.imshow(negative);
plt.axis('off');
OUTPUT
image
b)Log Transformation
%matplotlib inline
import imageio
import numpy as np
import matplotlib.pyplot as plt

pic=imageio.imread('pic14.jpg')
gray=lambda rgd:np.dot(rgd[...,:3],[0.299,0.587,0.114])
gray=gray(pic)

max_=np.max(gray)

def log_transform():
return(255/np.log(1+max_))*np.log(1+gray)
plt.figure(figsize=(5,5))
plt.imshow(log_transform(),cmap=plt.get_cmap(name='gray'))
plt.axis('off');
OUTPUT
image
c) Gamma correction
import imageio
import matplotlib.pyplot as plt

#Gamma encoding
pic=imageio.imread('pic14.jpg')
gamma=2.2 # Gamma < 1 ~ Dark ; Gamma > 1 ~ Bright

gamma_correction=((pic/255)**(1/gamma))
plt.figure(figsize=(5,5))
plt.imshow(gamma_correction)
plt.axis('off');
OUTPUT
image

24.Program to perform basic image manipulation:a)Sharpness b)Flipping c)Cropping
#Image sharpen
from PIL import Image
from PIL import ImageFilter
import matplotlib.pyplot as plt
#Load the image
my_image=Image.open('pic15.jpg')
#use sharpen function
sharp=my_image.filter(ImageFilter.SHARPEN)
#Save the image
sharp.save('C:\Rachana.K\image_sharpen.jpg')
sharp.show()
plt.imshow(sharp)
plt.show()
OUTPUT
image
#Image flip
import matplotlib.pyplot as plt
#Load the image
img=Image.open('pic15.jpg')
plt.imshow(img)
plt.show()
#use the flip function
flip=img.transpose(Image.FLIP_LEFT_RIGHT)

#save the image
flip.save('C:\Rachana.K\image_flip.jpg')
plt.imshow(flip)
plt.show()
OUTPUT
image
image
#Importing Image class from PIL module
from PIL import Image
import matplotlib.pyplot as plt
#Opens a image in RGB mode
im=Image.open('pic15.jpg')

#Size of the image in pixels(size of original image)
#(This is not mandotory)
width,height=im.size

#Cropped image of above dimension
#(It will not change original image)
im1=im.crop((120,10,250,160))

#shows the image in image viewer
im1.show()
plt.imshow(im1)
plt.show()
OUTPUT
image

Matrix
import numpy as np
import matplotlib.pyplot as plt

arr = np.zeros((256,256,3), dtype=np.uint8)
imgsize = arr.shape[:2]
innerColor = (255, 255, 255)
outerColor = (0, 0, 0)
for y in range(imgsize[1]):
for x in range(imgsize[0]):
distanceToCenter = np.sqrt((x - imgsize[0]//2) ** 2 + (y - imgsize[1]//2) ** 2)
distanceToCenter = distanceToCenter / (np.sqrt(2) * imgsize[0]/2)
r = outerColor[0] * distanceToCenter + innerColor[0] * (1 - distanceToCenter)
g = outerColor[1] * distanceToCenter + innerColor[1] * (1 - distanceToCenter)
b = outerColor[2] * distanceToCenter + innerColor[2] * (1 - distanceToCenter)
arr[y, x] = (int(r), int(g), int(b))
plt.imshow(arr, cmap='gray')
plt.show()
OUTPUT
image



Python3 program for printing
the rectangular pattern
Function to print the pattern
def printPattern(n):

arraySize = n * 2 - 1;
result = [[0 for x in range(arraySize)]
for y in range(arraySize)];

#Fill the values
for i in range(arraySize):
for j in range(arraySize):
if(abs(i - (arraySize // 2)) >
abs(j - (arraySize // 2))):
result[i][j] = abs(i - (arraySize // 2));
else:
result[i][j] = abs(j - (arraySize // 2));

#Print the array
for i in range(arraySize):
for j in range(arraySize):
print(result[i][j], end = " ");
print("");

#Driver Code
n = 4;

printPattern(n);

OUTPUT)
image

Program to generate matrix to image
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
w, h = 600, 600
data = np.zeros((h, w, 3), dtype=np.uint8)
data[0:100, 0:100] = [255, 0, 0]
data[100:200, 100:200] = [0,255, 0]
data[200:300, 200:300] = [0, 0, 255]
data[300:400, 300:400] = [255, 70, 0]
data[400:500, 400:500] = [255,120, 0]
data[500:600, 500:600] = [ 255, 255, 0]
#len width
img = Image.fromarray(data, 'RGB')
plt.imshow(img)
plt.axis("off")
plt.show()
OUTPUT
image

MAXIMUM PIXEL VALUE
import numpy as np
import matplotlib.pyplot as plt
array_colors = np.array([[[245, 20, 36],
[10, 215, 30],
[40, 50, 205]],
[[70, 50, 10],
[25, 230, 85],
[12, 128, 128]],
[[25, 212, 3],
[55, 5, 253],
[240, 152, 25]],
])
plt.imshow(array_colors)
np.max(array_colors)
OUTPUT
253
image
MINIMUM PIXEL VALUE
import numpy as np
import matplotlib.pyplot as plt
array_colors = np.array([[[245, 20, 36],
[10, 215, 30],
[40, 50, 205]],
[[70, 50, 10],
[25, 230, 85],
[12, 128, 128]],
[[25, 212, 3],
[55, 5, 250],
[240, 152, 25]],
])
plt.imshow(array_colors)
np.min(array_colors)
OUTPUT
3
image
STANDARD VALUE OF A PIXEL
import numpy as np
import matplotlib.pyplot as plt
array_colors = np.array([[[245, 20, 36],
[10, 215, 30],
[40, 50, 205]],
[[70, 50, 10],
[25, 230, 85],
[12, 128, 128]],
[[25, 212, 3],
[55, 5, 250],
[240, 152, 25]],
])
plt.imshow(array_colors)
np.std(array_colors)
OUTPUT
87.50068782798436
image

EDGE DETECTION

#(c) Edge detection using prewitt operator
import cv2
import numpy as np
from matplotlib import pyplot as plt
img=cv2.imread('img1.jpg')
gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
img_gaussian=cv2.GaussianBlur(gray,(3,3),0)

#prewitt
kernelx=np.array([[1,1,1],[0,0,0],[-1,-1,-1]])
kernely=np.array([[-1,0,1],[-1,0,1],[-1,0,1]])
img_prewittx=cv2.filter2D(img_gaussian,-1,kernelx)
img_prewitty=cv2.filter2D(img_gaussian,-1,kernely)

cv2.imshow("Original Image",img)
cv2.imshow("prewitt x",img_prewittx)
cv2.imshow("prewitt y",img_prewitty)
cv2.imshow("Prewitt",img_prewittx+img_prewitty)
cv2.waitKey()
cv2.destroyAllWindows()
OUTPUT
image
image
image
image

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published