shyam-singh
May 27, 2024
[1]: print("1. Welcome to Poornima Group")
print("2. My name is shyam singh")
print("3. today is wednesday")
print("4. This is first lab of digital image processing lab")
print("5. Batch C2")
1. Welcome to Poornima Group
2. My name is shyam singh
3. today is wednesday
4. This is first lab of digital image processing lab
5. Batch C2
[2]: # print("-------------------welcome to poornima group----------------------")
# print("------------items with amount------------")
# print("1. pizza ", " 150")
# print("2. burger ", " 50")
# print("3. samosa ", " 30")
# print("4. petij ", " 40")
# print(" select your choice number 1-4")
# a=int(input("enter your choice number "))
# items=[1,2,3,4]
# if(a in items):
# if(a == 1):
# print("your amount is 150")
# if(a == 2):
# print("your amount is 50 rupees")
# if(a == 3):
# print("your amount is 30 rupees")
# if(a == 4):
# print("your amount is 40 rupees")
[1]: import numpy as np
import pandas as pd
import cv2 as cv #Conda install -c forge openCV
import matplotlib.pyplot as plt
1
1 Reading , writing and display the image
[2]: # Read the image
image = cv.imread('bird.jpeg')
# # Check if the image was successfully loaded
# if image is not None:
# # print("Image loaded successfully.")
# # Display the image
# cv.imshow('Image', image)
# cv.waitKey(0) # Wait for any key press to close the window
# cv.destroyAllWindows() # Close all OpenCV windows
# else:
# print("Error: Unable to load the image.")
[5]: plt.imshow(image)
[5]: <matplotlib.image.AxesImage at 0x1be790c43a0>
[3]: image.shape
[3]: (180, 320, 3)
[5]: h=image.shape[0]
w=image.shape[1]
print(h,w,sep="\n")
2
z=image.shape[2]
z
180
320
[5]: 3
[8]: print(image)
[[[ 95 125 126]
[ 94 124 125]
[ 93 121 122]
…
[133 136 140]
[127 130 135]
[125 129 134]]
[[ 95 123 124]
[ 94 122 123]
[ 92 117 119]
…
[132 135 139]
[126 129 133]
[122 126 131]]
[[ 95 120 122]
[ 92 117 119]
[ 90 113 115]
…
[132 136 137]
[123 128 131]
[120 125 128]]
[[ 66 63 72]
[ 45 42 51]
[ 43 40 49]
…
[ 63 56 59]
[106 99 102]
[119 112 115]]
[[105 102 111]
[ 56 53 62]
[ 36 33 42]
…
3
[ 50 43 46]
[ 80 73 76]
[ 94 87 90]]
[[150 147 156]
[ 71 68 77]
[ 36 33 42]
…
[ 52 45 48]
[ 64 57 60]
[ 76 69 72]]]
2 Separating different channels from the image
[6]: # Assuming "image" is your original image in BGR format
# Convert BGR image to grayscale
img_gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
# Display the grayscale image
plt.imshow(img_gray)
[6]: <matplotlib.image.AxesImage at 0x24e7f843ac0>
[10]: plt.grid('bird.jpeg')
plt.xlabel('X_AXIS')
4
plt.ylabel('Y_AXIS')
plt.imshow(image)
[10]: <matplotlib.image.AxesImage at 0x24e059a5120>
[11]: Scale_per = 50
width = int(image.shape[1]* Scale_per/100)
height = int(image.shape[0]* Scale_per/100)
image_res = cv.resize(image,(width, height))
print("original shape", image.shape)
print("resized shape", image_res.shape)
plt.imshow(image)
plt.imshow(image_res)
original shape (180, 320, 3)
resized shape (90, 160, 3)
[11]: <matplotlib.image.AxesImage at 0x1be792077f0>
5
[ ]:
[12]: Scale_per = 75
width = int(image.shape[1]* Scale_per/100)
image_resh = cv.resize(image,(width,image.shape[0]))
print("original shape", image.shape)
print("resized shape", image_resh.shape)
plt.imshow(image)
plt.imshow(image_resh)
original shape (180, 320, 3)
resized shape (180, 240, 3)
[12]: <matplotlib.image.AxesImage at 0x1be792272e0>
6
[13]: Scale_per = 50
height = int(image.shape[0]* Scale_per/100)
image_resw = cv.resize(image,(image.shape[1], height))
print("original shape", image.shape)
print("resized shape", image_resw.shape)
plt.imshow(image)
plt.imshow(image_resw)
original shape (180, 320, 3)
resized shape (90, 320, 3)
[13]: <matplotlib.image.AxesImage at 0x1be79476e60>
7
[14]: # Read the image
img1 = cv.imread('bird.jpeg')
print(img1.shape)
img2=img1+50
print(img2.shape)
plt.imshow(img2)
(180, 320, 3)
(180, 320, 3)
[14]: <matplotlib.image.AxesImage at 0x1be79504190>
8
[15]: img3=img1-50
plt.imshow(img3)
[15]: <matplotlib.image.AxesImage at 0x1be7957b610>
[16]: img4=img1*50
plt.imshow(img4)
[16]: <matplotlib.image.AxesImage at 0x1be795fb070>
9
[17]: img5=img1/50
plt.imshow(img5)
Clipping input data to the valid range for imshow with RGB data ([0..1] for
floats or [0..255] for integers).
[17]: <matplotlib.image.AxesImage at 0x1be79423310>
[18]: # Read the image
imgg= cv.imread('bird.jpeg')
print(imgg.shape)
plt.subplot(141)
plt.imshow(imgg)
plt.subplot(142)
plt.imshow(imgg[:,::-1]) #negative of x
plt.subplot(143)
plt.imshow(imgg[::-1,:]) #reverse of y
plt.subplot(144)
plt.imshow(imgg[::-1,::-1]) #reverse of both x and y
(180, 320, 3)
[18]: <matplotlib.image.AxesImage at 0x1be7971f220>
10
[19]: #flipping of an image
# Read the image
imgg= cv.imread('bird.jpeg')
plt.subplot(221)
plt.imshow(imgg)
img_fh = cv.flip(imgg, 0) #around x axis
plt.imshow(img_fh)
plt.subplot(222)
img_fv = cv.flip(imgg, 1) #y-axis
plt.imshow(img_fv)
plt.subplot(223)
img_fhv = cv.flip(imgg,-1) #both axis
plt.imshow(img_fhv)
plt.subplot(224)
plt.imshow(imgg)
[19]: <matplotlib.image.AxesImage at 0x1be796fa320>
11
[ ]:
[ ]:
[ ]:
[20]: # # Convert the image to grayscale
# img_gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
# # Display the grayscale image
# cv.imshow('Grayscale Image', img_gray)
[21]: image_bgr = cv.cvtColor(image, cv.COLOR_RGB2BGR)
plt.imshow(image_bgr)
[21]: <matplotlib.image.AxesImage at 0x1be7ae523b0>
12
[22]: image_rgb = cv.cvtColor(img_gray, cv.COLOR_GRAY2RGB)
plt.imshow(image_rgb)
[22]: <matplotlib.image.AxesImage at 0x1be7aebbac0>
13
[23]: plt.grid('bird.jpeg')
plt.xlabel('X_AXIS')
plt.ylabel('Y_AXIS')
plt.imshow(image)
[23]: <matplotlib.image.AxesImage at 0x1be7ad0e4a0>
[24]: angle = np.radians(20)
x_img = np.float32([
[np.cos(angle), -np.sin(angle), 0],
[np.sin(angle), np.cos(angle), 0],
[0, 0, 1]
])
rotated_img = cv.warpPerspective(image, x_img, (image.shape[1], image.shape[0]))
plt.imshow(rotated_img)
plt.show()
14
3 Blending of img1 and img2
[12]: # Read the image
img1 = cv.imread('cat.jpeg')
print(img1.shape)
plt.imshow(img1)
(180, 180, 3)
[12]: <matplotlib.image.AxesImage at 0x24e059e92a0>
15
[13]: # Read the image
img2 = cv.imread('dog.jpg')
print(img2.shape)
plt.imshow(img2)
(768, 1024, 3)
[13]: <matplotlib.image.AxesImage at 0x24e05b9a3e0>
16
[14]: img2_resize = cv.resize(img2, (img1.shape[1], img1.shape[0]))
print(img2_resize.shape)
print(img1.shape)
(180, 180, 3)
(180, 180, 3)
[15]: alpha=0.5 #weight of img1
beta=0.8 #weight of img2
gamma=0.3 #scaling factor of blending
result = cv.addWeighted(img1, alpha, img2_resize, beta, gamma) #alpha*img1 +␣
↪beta* img2 + gamma
plt.imshow(result)
[15]: <matplotlib.image.AxesImage at 0x24e05c10c40>
17
[16]: # import PIL as pl
plt.subplot(1,2,1)
plt.title("original")
plt.imshow(img1)
# Assuming "image" is your original image in BGR format
# Convert BGR image to grayscale
img_gray = cv.cvtColor(img1, cv.COLOR_BGR2GRAY)
equalized_img = cv.equalizeHist(img_gray)
cv.imwrite('equalized.jpeg',equalized_img)
plt.subplot(1,2,2)
plt.title("equalized")
plt.imshow(equalized_img)
[16]: <matplotlib.image.AxesImage at 0x24e0615a0b0>
18
[17]: plt.imshow(img1)
[17]: <matplotlib.image.AxesImage at 0x24e05c37550>
19
4 1. remove noise from image 2. sharpness of an image 3. inverse
transfrom of an image. (color also change)
[18]: # 1. remove noise from image
# In summary, (5, 5) determines the size of the blurring kernel, and 0 implies␣
↪that
# OpenCV will calculate the standard deviation based on the kernel size.
# These parameters collectively control the amount of blurring applied to the␣
↪image.
import cv2 as cv
import matplotlib.pyplot as plt
# Assuming img1 is your original image
# Apply Gaussian blur to remove noise
img1_blurred = cv.GaussianBlur(img1, (5, 5), 0)
# Display the blurred image
# res=cv.imshow('Blurred Image', img1_blurred)
plt.title('Blurred Image')
plt.imshow(img1_blurred)
[18]: <matplotlib.image.AxesImage at 0x24e05b99ea0>
20
2. sharpness of an image
Converting the image to grayscale before applying sharpening filters simplifies the process and can
improve the results. Here’s why:
Dimensionality: Grayscale images have only one channel, whereas color images have three channels
(typically Red, Green, and Blue). By converting to grayscale, you simplify the image data to a
single channel, which simplifies the operations and reduces computational complexity.
Focus on Structure: Sharpening filters, such as the Laplacian filter, primarily enhance the edges
and fine details in the image. These features are often better represented in grayscale images since
they focus on intensity changes rather than color changes. Converting to grayscale helps emphasize
these structural features.
Reduced Sensitivity to Color Variations: Color variations might not always correspond to edges
or details that need sharpening. By converting to grayscale, you focus on the intensity variations,
which are more directly related to image structure.
[32]: import cv2 as cv
import numpy as np
# Assuming img1 is your original image
21
# Convert image to grayscale
img_gray = cv.cvtColor(img1, cv.COLOR_BGR2GRAY)
# Apply Laplacian filter for sharpening
laplacian = cv.Laplacian(img_gray, cv.CV_64F)
# Convert the output back to the original data type
sharpened_img = np.uint8(np.clip(laplacian, 0, 255))
# Display the sharpened image
plt.title('sharpened Image')
plt.imshow(sharpened_img)
[32]: <matplotlib.image.AxesImage at 0x1be7b7eb400>
[35]: import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
# Assuming img1 is your original image
22
# Define the transformation function (example: brightness adjustment)
def adjust_brightness(img, alpha):
return cv.convertScaleAbs(img, alpha=1/alpha, beta=0)
# Apply the original transformation (example: increasing brightness)
alpha = 1.5
transformed_img = adjust_brightness(img1, alpha)
# Apply the inverse transformation
inverse_transformed_img = adjust_brightness(transformed_img, alpha=1/alpha)
# Display the transformed image
plt.subplot(1,2,1)
plt.title('Transformed Image')
plt.imshow(transformed_img)
# Display the inverse transformed image
plt.subplot(1,2,2)
plt.title('Inverse Transformed Image')
plt.imshow(inverse_transformed_img)
[35]: <matplotlib.image.AxesImage at 0x1be7cb77c70>
23
5 Edge Detection
[22]: import numpy as np
import pandas as pd
import cv2 as cv #Conda install -c forge openCV
import matplotlib.pyplot as plt
# Edge Detection
def main():
img=cv.imread("ele.jpeg", 1)
img=cv.cvtColor(img, cv.COLOR_BGR2RGB)
k1=np.array(([1, 0, -1],
[0, 0, 0],
[-1, 0, 1]), np.float32)
k2=np.array(([0, -1, 0],
[-1, 4, -1],
[0, -1, 0]), np.float32)
k3=np.array(([-1, -1, -1],
[-1, 8, -1],
[-1, -1, -1]), np.float32)
output1=cv.filter2D(img, -1, k1)
output2=cv.filter2D(img, -1, k2)
output3=cv.filter2D(img, -1, k3)
plt.subplot(2, 2, 1)
plt.imshow(img)
plt.title('Original Image')
plt.subplot(2,2, 2)
plt.imshow(output1)
plt.title('Filtered Image-Edge Detection-k1')
plt.subplot(2, 2, 3)
plt.imshow(output2)
plt.title('Filtered Image-Edge Detection-k2')
plt.subplot(2, 2, 4)
plt.imshow(output3)
plt.title('Filtered Image-Edge Detection-k3')
plt.show()
if __name__ == "__main__":
main()
24
[16]: img=cv.imread('cat.jpeg',1)
img=cv.cvtColor(img,cv.COLOR_BGR2RGB)
k1=np.array(([1,0,-1],
[0,0,0],
[-1,0,1]),np.float32)
k2=np.array(([0,-1,0],
[-1,4,-1],
[0,-1,0]),np.float32)
k3=np.array(([-1,-1,-1],
[-1,8,-1],
[-1,-1,-1]),np.float32)
output1=cv.filter2D(img,-1,k1)
output2=cv.filter2D(img,-1,k2)
output3=cv.filter2D(img,-1,k3)
plt.subplot(2, 2, 1)
plt.imshow(img)
plt.title('original image')
plt.subplot(2, 2, 2)
plt.imshow(output1)
plt.title("filtered image edge detection k1")
plt.subplot(2, 2, 3)
plt.imshow(output2)
25
plt.title("filtered image edge detection k2")
plt.subplot(2, 2, 4)
plt.imshow(output3)
plt.title("filtered image edge detection k3")
[16]: Text(0.5, 1.0, 'filtered image edge detection k3')
6 Box Blur
[24]: #box blur
def main():
img=cv.imread("cat.jpeg", 1)
img=cv.cvtColor(img, cv.COLOR_BGR2RGB)
k=np.array(np.ones((11,11), np.float32))/121
print(k)
output=cv.filter2D(img, -1, k)
26
plt.subplot(1,2,1)
plt.imshow(img)
plt.title("Original Image")
plt.subplot(1,2,2)
plt.imshow(output)
plt.title("filtered Image-Box Blur")
plt.show()
if __name__ == "__main__":
main()
[[0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446
0.00826446 0.00826446 0.00826446 0.00826446 0.00826446]
[0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446
0.00826446 0.00826446 0.00826446 0.00826446 0.00826446]
[0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446
0.00826446 0.00826446 0.00826446 0.00826446 0.00826446]
[0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446
0.00826446 0.00826446 0.00826446 0.00826446 0.00826446]
[0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446
0.00826446 0.00826446 0.00826446 0.00826446 0.00826446]
[0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446
0.00826446 0.00826446 0.00826446 0.00826446 0.00826446]
[0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446
0.00826446 0.00826446 0.00826446 0.00826446 0.00826446]
[0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446
0.00826446 0.00826446 0.00826446 0.00826446 0.00826446]
[0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446
0.00826446 0.00826446 0.00826446 0.00826446 0.00826446]
[0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446
0.00826446 0.00826446 0.00826446 0.00826446 0.00826446]
[0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446
0.00826446 0.00826446 0.00826446 0.00826446 0.00826446]]
27
[26]: def main():
img=cv.imread("cat.jpeg", 1)
img=cv.cvtColor(img, cv.COLOR_BGR2RGB)
k1=np.array(([0,-1,0],[-1,5,-1],[0,-1,0]), np.float32)
print(k1)
print(type(k1))
output=cv.filter2D(img, -1, k1)
plt.subplot(1,2,1)
plt.imshow(img)
plt.title("Original Image")
plt.subplot(1,2,2)
plt.imshow(output)
plt.title("Sharpen Edges")
plt.show()
if __name__ == "__main__":
main()
[[ 0. -1. 0.]
[-1. 5. -1.]
[ 0. -1. 0.]]
<class 'numpy.ndarray'>
28
6.1 Remove noise and get how much as image noise contain
[33]: #exp 8
import random
def main():
img=cv.imread("cat.jpeg", 1)
img=cv.cvtColor(img, cv.COLOR_BGR2RGB)
plt.imshow(img)
rows,cols,chan = img.shape
p=0.25
output = np.zeros(img.shape, np.uint8)
for i in range(rows):
for j in range(cols):
r=random.random()
if r<p/2:
output[i][j] = [0,0,0]
elif r<p:
#pepper sprinkled
output[i][j] =[255,255,255]
else:
#salt sprinkled
output[i][j]=img[i][j]
29
denoised = cv.medianBlur(output, 3)
result = [img, output, denoised]
titles = ['Original', 'Noisy', 'Denoised']
for i in range(3):
plt.subplot(1,3,i+1)
plt.imshow(result[i])
plt.title(titles[i])
plt.xticks([])
plt.yticks([])
plt.show()
if __name__ == "__main__":
main()
C:\Users\Shyam Singh\AppData\Local\Temp\ipykernel_11012\560947424.py:30:
MatplotlibDeprecationWarning: Auto-removal of overlapping axes is deprecated
since 3.6 and will be removed two minor releases later; explicitly call
ax.remove() as needed.
plt.subplot(1,3,i+1)
[12]: import cv2 as cv
import random
import numpy as np
import matplotlib.pyplot as plt
def main():
img = cv.imread("cat.jpeg", 1)
img = cv.cvtColor(img, cv.COLOR_BGR2RGB)
plt.imshow(img)
rows, cols, chan = img.shape
p = 0.25
30
output = np.zeros(img.shape, np.uint8)
for i in range(rows):
for j in range(cols):
r = random.random()
if r < p / 2:
output[i][j] = [0, 0, 0]
elif r < p:
# pepper sprinkled
output[i][j] = [255, 255, 255]
else:
# salt sprinkled
output[i][j] = img[i][j]
# Noisy image
noisy_img = output.copy()
# Gaussian blur to smooth out noise
noisy_img_blurred = cv.GaussianBlur(noisy_img, (5, 5), 0)
# Denoise using fastNlMeansDenoisingColored
denoised = cv.fastNlMeansDenoisingColored(noisy_img_blurred, None, h=20,␣
↪hColor=15, templateWindowSize=7, searchWindowSize=21)
result = [img, noisy_img, denoised]
titles = ['Original', 'Noisy', 'Denoised']
for i in range(3):
plt.subplot(1, 3, i+1)
plt.imshow(result[i])
plt.title(titles[i])
plt.xticks([])
plt.yticks([])
plt.show()
if __name__ == "__main__":
main()
C:\Users\Shyam Singh\AppData\Local\Temp\ipykernel_31992\3058065973.py:40:
MatplotlibDeprecationWarning: Auto-removal of overlapping axes is deprecated
since 3.6 and will be removed two minor releases later; explicitly call
ax.remove() as needed.
plt.subplot(1, 3, i+1)
31
[1]: #displayling the sample image - Monochrome Format
from skimage import data
from skimage import filters
from skimage.color import rgb2gray
import matplotlib.pyplot as plt
#sample image of scikit image package
cat = data.cat()
gray_cat = rgb2gray(cat)
#setting the plot size to 15,15
plt.figure(figsize=(15,15))
for i in range(10):
binarized_gray = (gray_cat > i * 0.1) * 1
plt.subplot(5,2,i+1)
#rounding of the threshold
#value of 1 decimal point
plt.title("Threshold: >"+str(round(i*0.1,1)))
#displaying the binarized images
#of various thresholds
plt.imshow(binarized_gray, cmap='gray')
plt.tight_layout()
C:\Users\Shyam Singh\anaconda3\lib\site-packages\paramiko\transport.py:219:
CryptographyDeprecationWarning: Blowfish has been deprecated
"class": algorithms.Blowfish,
32
33
[ ]:
[8]: #image segmentation using threshold value
import cv2 as cv
from skimage import data
from skimage import filters
from skimage.color import rgb2gray
import matplotlib.pyplot as plt
#loading the image named test.jpg
img = cv.imread(r"cat.jpeg")
# converting color mode to grayscale
# as thresholding requires a single channeled image
# img = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
plt.imshow(img)
[8]: <matplotlib.image.AxesImage at 0x11acb3fd840>
34
[9]: #Binary Threshold
ret, thresh = cv.threshold(img,127,255,cv.THRESH_BINARY)
plt.imshow(thresh)
[9]: <matplotlib.image.AxesImage at 0x11acb485210>
[5]: #binary Inverse Threshold
ret, thresh = cv.threshold(img,127,255,cv.THRESH_BINARY_INV)
plt.imshow(thresh)
[5]: <matplotlib.image.AxesImage at 0x11acb129420>
35
[6]: #Threshold Truncate
ret, thresh = cv.threshold(img,127,255,cv.THRESH_TRUNC)
plt.imshow(thresh)
[6]: <matplotlib.image.AxesImage at 0x11acb2e8f40>
36
[7]: #Zero Threshold
ret, thresh = cv.threshold(img,127,255,cv.THRESH_TOZERO)
plt.imshow(thresh)
[7]: <matplotlib.image.AxesImage at 0x11acb36d810>
37
[ ]:
38