cl1p.net - The internet clipboard
Login/Sign Up
cl1p.net/ip
cl1p.net/ip
Login/Sign Up
This cl1p will be deleted in in 24 days.
Copy
#lab1 #interchanging blue and red colors import cv2 as cv from matplotlib import pyplot as plt img=cv.imread('/content/rb image.jfif') b,g,r=cv.split(img) img_interchanged=cv.merge([r,g,b]) plt.figure(figsize=(5,5)) plt.subplot(121) plt.imshow(cv.cvtColor(img,cv.COLOR_BGR2RGB)) plt.title('Original Image') plt.subplot(122) plt.imshow(cv.cvtColor(img_interchanged,cv.COLOR_BGR2RGB)) plt.title('Red and Blue planes are Interchanged ') plt.show() 2........................ #saving the image in different formats and display the properties of image from PIL import Image import matplotlib.pyplot as plt image_path='//content/rb2.jpg' img=Image.open(image_path) formats=["JPEG","PNG","BMP"] for fmt in formats: img.save(f"output.{fmt.lower()}",fmt) for fmt in formats: with Image.open(f"output.{fmt.lower()}") as img: print(f"Format:{img.format}") print(f"size:{img.size}") print(f"Mode:{img.mode}") plt.imshow(img) plt.title(f"image in {img.format}format") plt.axis('off') plt.show() print() 3...................... ##Analysing the image using different color modes import cv2 import numpy as np import matplotlib.pyplot as plt def load_image(image_path): image = cv2.imread(image_path) image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) return image_rgb def convert_to_hsv(image_rgb): image_hsv = cv2.cvtColor(image_rgb, cv2.COLOR_RGB2HSV) return image_hsv def convert_to_lab(image_rgb): image_lab = cv2.cvtColor(image_rgb, cv2.COLOR_RGB2LAB) return image_lab def plot_image(image,title,color_map=None): plt.imshow(image,cmap=color_map) plt.title(title) plt.axis('off') def analyze_image(image_path): image_rgb = load_image(image_path) image_hsv = convert_to_hsv(image_rgb) image_lab = convert_to_lab(image_rgb) plt.figure(figsize=(18,6)) plt.subplot(1, 3, 1) plot_image(image_rgb, 'RGB color Model') plt.subplot(1, 3, 2) plot_image(image_hsv, 'HSV color Model') plt.subplot(1, 3, 3) plot_image(image_lab, 'LAB color Model') plt.show() image_path='/content/girl.png' analyze_image(image_path) 4..................... #perform bitwise,arithmetic ,shift operations import cv2 as cv import numpy as np from google.colab.patches import cv2_imshow def bitwiSe_operations_demo(image1_path,image2_path): img1 = cv.imread(image1_path) img2 = cv.imread(image2_path) if img1.shape!=img2.shape: raise ValueError("Images must have the same dimensions for these operations") and_operator=cv.bitwise_and(img1,img2) or_operator=cv.bitwise_or(img1,img2) xor_operator=cv.bitwise_xor(img1,img2) not_operator_img1=cv.bitwise_not(img1) not_operator_img2=cv.bitwise_not(img2) add_operator=cv.add(img1,img2) sub_operator=cv.subtract(img1,img2) left_shift_operator=cv.convertScaleAbs(img1 * 4) right_shift_operator=cv.convertScaleAbs(img1 / 4) print("original image 1") cv2_imshow(img1) print("original image 2") cv2_imshow(img2) print("Bitwise AND") cv2_imshow(and_operator) print("Bitwise OR") cv2_imshow(or_operator) print("Bitwise XOR") cv2_imshow(xor_operator) print("Bitwise NOT on Image 1") cv2_imshow(not_operator_img1) print("Bitwise Not on Image2") cv2_imshow(not_operator_img2) print("Addition") cv2_imshow(add_operator) print("Subtraction") cv2_imshow(sub_operator) print("Left shift on image 1") cv2_imshow(left_shift_operator) print("Right shift on image 2") cv2_imshow(right_shift_operator) cv.waitKey(0) cv.destroyAllWindows() image1_path="/content/one.jpg" image2_path="/content/second.jpg" bitwiSe_operations_demo(image1_path,image2_path) 5................... #Implementation of Image intensity slicing technique for image enhancement import cv2 as cv import numpy as np from google.colab.patches import cv2_imshow def intensity_slicing(image,min_intensity,max_intensity,slice_value): sliced_image=np.zeros_like(image) mask=(image>=min_intensity)&(image<=max_intensity) sliced_image[mask]=slice_value return sliced_image image=cv.imread('/content/ip.jpg',cv.IMREAD_GRAYSCALE) min_intensity=100 max_intensity=200 slice_value=255 sliced_image=intensity_slicing(image,min_intensity,max_intensity,slice_value) print("original image") cv2_imshow(image) print("sliced image") cv2_imshow(sliced_image) cv.waitKey(0) cv.destroyAllWindows() 6............................... # histogram equalization import cv2 import numpy as np import matplotlib.pyplot as plt def histogram_equalization(image): if len(image.shape)==3: image = cv.cvtColor(image, cv.COLOR_BGR2GRAY) hist,bins=np.histogram(image.flatten(),256,[0,256]) cdf=hist.cumsum() cdf_normalized=cdf*hist.max()/cdf.max() cdf_m=np.ma.masked_equal(cdf,0) cdf_m=(cdf_m - cdf_m.min()) * 255/(cdf_m.max()-cdf_m.min()) cdf=np.ma.filled(cdf_m,0).astype('uint8') equalized_image=cdf[image] return equalized_image,hist,cdf_normalized def plot_histogram(image,title): plt.hist(image.flatten(),256,[0,256],color='r') plt.xlim([0,256]) plt.title(title) plt.show() image_path='/content/rose.jpg' image = cv2.imread(image_path,cv2.IMREAD_GRAYSCALE) equalized_image,hist,cdf_normalized=histogram_equalization(image) plt.subplot(2,2,1) plt.imshow(image,cmap='gray') plt.title('Original Image') plt.subplot(2,2,2) plot_histogram(image,'Original Histogram') plt.subplot(2,2,3) plt.imshow(equalized_image,cmap='gray') plt.title('Equalized Image') plt.subplot(2,2,4) plot_histogram(equalized_image,'Equalized Histogram') plt.show() 7....................... #program to observe the intensity of image after applying mean median filters import cv2 import numpy as np import matplotlib.pyplot as plt image=cv2.imread('/content/rose.jpg',cv2.IMREAD_GRAYSCALE) noise_sigma=25 noise=np.random.normal(0,noise_sigma,image.shape) noisy_image=np.clip(image+noise,0,255).astype(np.uint8) mean_filtered_image=cv2.blur(noisy_image,(5,5)) median_filtered_image=cv2.medianBlur(noisy_image,5) plt.figure(figsize=(12,8)) plt.subplot(2,2,1) plt.imshow(image,cmap='gray') plt.title('Original Image') plt.axis('off') plt.subplot(2,2,2) plt.imshow(noisy_image,cmap='gray') plt.title('Noisy image Gaussian Noise') plt.axis('off') plt.subplot(2,2,3) plt.imshow(mean_filtered_image,cmap='gray') plt.title('Mean filtered image') plt.axis('off') plt.subplot(2,2,4) plt.imshow(median_filtered_image,cmap='gray') plt.title('Median filtered image') plt.axis('off') plt.show() 8......................... #Implement image enhancement using frequency domain filtering to perform HPF and LPF on noisy images import cv2 as cv import numpy as np import matplotlib.pyplot as plt def add_gaussian_noise(image,mean=0,sigma=25): gauss=np.random.normal(mean,sigma,image.shape) noisy_image=image+gauss noisy_image=np.clip(noisy_image,0,255) return noisy_image.astype(np.uint8) def create_low_pass_filter(rows,cols,radius): mask=np.zeros((rows,cols),np.float32) center=(rows//2,cols//2) for i in range(rows): for j in range(cols): if np.sqrt((i-center[0])**2+(j-center[1])**2)<=radius: mask[i,j]=1 return mask def create_high_pass_filter(rows,cols,radius): mask=np.ones((rows,cols),np.float32) center=(rows//2,cols//2) for i in range(rows): for j in range(cols): if np.sqrt((i-center[0])**2+(j-center[1])**2)<=radius: mask[i,j]=0 return mask def perform_dft(image): dft=cv.dft(np.float32(image),flags=cv.DFT_COMPLEX_OUTPUT) dft_shift=np.fft.fftshift(dft) magnitude_spectrum=20*np.log(cv.magnitude(dft_shift[:,:,0],dft_shift[:,:,1])+1) return dft_shift,magnitude_spectrum def apply_filter(def_shift,filter_mask): filtered_dft_shift=def_shift*filter_mask[:,:,np.newaxis] dft_ishift=np.fft.ifftshift(filtered_dft_shift) img_back=cv.idft(dft_ishift) img_back=cv.magnitude(img_back[:,:,0],img_back[:,:,1]) return img_back img=cv.imread('/content/ball1.jpg',0) noisy_img=add_gaussian_noise(img) rows,cols=img.shape dft_shift,magnitude_spectrum=perform_dft(img) low_pass_filter=create_low_pass_filter(rows,cols,30) high_pass_filter=create_high_pass_filter(rows,cols,30) lpf_img=apply_filter(dft_shift,low_pass_filter) hpf_img=apply_filter(dft_shift,high_pass_filter) plt.figure(figsize=(12,12)) plt.subplot(231),plt.imshow(img,cmap='gray'),plt.title('Original Image') plt.subplot(232),plt.imshow(noisy_img,cmap='gray'),plt.title('Noisy Image') plt.subplot(233),plt.imshow(magnitude_spectrum,cmap='gray'),plt.title('Magnitude Spectrum image') plt.subplot(234),plt.imshow(low_pass_filter,cmap='gray'),plt.title('Low Pass Filter Image') plt.subplot(235),plt.imshow(high_pass_filter,cmap='gray'),plt.title('High Pass Filtered Image') plt.subplot(236),plt.imshow(lpf_img,cmap='gray'),plt.title('Low Pass Filtered Image') plt.show() 9............................... #apply adaptive filters on an image import cv2 as cv import numpy as np import matplotlib.pyplot as plt def add_gaussian_noise(image,mean=0,var=5000): sigma=var**0.5 gaussian=np.random.normal(mean,sigma,image.shape) noisy_image=np.clip(image+gaussian,0,255) return noisy_image.astype(np.uint8) image=cv2.imread('/content/girl img.jpg') #convert the ing into gray scale if needed gray_image=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) #add gaussian noise to the image noisy_image=add_gaussian_noise(gray_image) filtered_image=cv2.bilateralFilter(noisy_image,d=15,sigmaColor=150,sigmaSpace=150) plt.figure(figsize=(15,5)) plt.subplot(1,3,1) plt.imshow(gray_image,cmap='gray') plt.title('original image') plt.axis('off') plt.subplot(1,3,2) plt.imshow(noisy_image,cmap='gray') plt.title('image with gaussian Noise') plt.axis('off') plt.subplot(1,3,3) plt.imshow(filtered_image,cmap='gray') plt.title('filtered image(Adaptive bilateral)') plt.axis('off') plt.show() 10...................... #edge detection using canny and sobel filter import cv2 import numpy as np import matplotlib.pyplot as plt img=cv2.imread("/content/girl img.jpg",cv2.IMREAD_GRAYSCALE) edges_canny=cv2.Canny(img,100,200) sobel_x=cv2.Sobel(img,cv2.CV_64F,1,0,ksize=5) sobel_y=cv2.Sobel(img,cv2.CV_64F,0,1,ksize=5) sobel_edges=cv2.magnitude(sobel_x,sobel_y) plt.figure(figsize=(10,6)) plt.subplot(1,3,1) plt.imshow(img,cmap='gray') plt.title('original image') plt.axis('off') plt.subplot(1,3,2) plt.imshow(edges_canny,cmap='gray') plt.title('Canny Edge Detection') plt.axis('off') plt.subplot(1,3,3) plt.imshow(sobel_edges,cmap='gray') plt.title('Sobel Edge Detection') plt.axis('off') plt.tight_layout() plt.show() 11............................ import cv2 import numpy as np from google.colab.patches import cv2_imshow image=cv2.imread('/content/image3.jpg') gray=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) edges=cv2.Canny(gray,50,150,apertureSize=3) lines=cv2.HoughLinesP(edges,1,np.pi/180,threshold=100,minLineLength=100,maxLineGap=10) if lines is not None: for line in lines: x1,y1,x2,y2=line[0] cv2.line(image,(x1,y1),(x2,y2),(0,255,0),2) cv2_imshow(image) 12........................ #program to detect face using featured matching import cv2 import numpy as np import matplotlib.pyplot as plt reference_image = cv2.imread('/content/monkey', 0) target_image = cv2.imread('/content/girl2.jpg', 0) orb = cv2.ORB_create() keypoints_ref, description_ref = orb.detectAndCompute(reference_image, None) keypoints_target, description_target = orb.detectAndCompute(target_image, None) bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True) matches = bf.match(description_ref, description_target) matches = sorted(matches, key=lambda x: x.distance) result_image = cv2.drawMatches(reference_image, keypoints_ref, target_image, keypoints_target, matches[:50], None, flags=cv2.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS) plt.figure(figsize=(10, 6)) plt.imshow(result_image, cmap='gray') plt.title('Feature Matching using ORB') plt.axis('off') plt.show() 13........................... #apply erosion and dilation on an image import cv2 import numpy as np import matplotlib.pyplot as plt image=cv2.imread('/content/girl img.jpg') _,binary_image=cv2.threshold(image,127,255,cv2.THRESH_BINARY) kernel=np.ones((3,3),np.uint8) erasion=cv2.erode(binary_image,kernel,iterations=1) dilation=cv2.dilate(binary_image,kernel,iterations=1) titles=['Original','Erosion','Dilation'] images=[image,erasion,dilation] for i in range(3): plt.subplot(1,3,i+1) plt.imshow(images[i],cmap='gray') plt.title(titles[i]) plt.xticks([]),plt.yticks([]) plt.show() 14……………………………… #image restoration import cv2 from matplotlib import pyplot as plt import numpy as np noisy_image=cv2.imread('/content/girl img.jpg',cv2.IMREAD_GRAYSCALE) restored_image=cv2.fastNlMeansDenoising(noisy_image,None,h=10,templateWindowSize=7,searchWindowSize=21) plt.figure(figsize=(10,5)) plt.subplot(1,2,1) plt.title('Noisy Image') plt.imshow(noisy_image,cmap='gray') plt.subplot(1,2,2) plt.title('Restored Image') plt.imshow(restored_image,cmap='gray') plt.show()