Repository navigation
Expand file tree
/
Copy pathimage_processing_exercises.py
More file actions
843 lines (648 loc) · 26.1 KB
/
Copy pathimage_processing_exercises.py
File metadata and controls
843 lines (648 loc) · 26.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
# -*- coding: utf-8 -*-
"""image_processing_exercises
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1aQP0V-WGy-aBz21S8C9iBQolthk0uEnv
"""
# Import necessary libraries
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Load the image
leaf_image = cv2.imread('/content/leaf.jpg')
# Convert to grayscale
leaf_gray = cv2.cvtColor(leaf_image, cv2.COLOR_BGR2GRAY)
# Apply thresholding
tau = 220
_, leaf_binary = cv2.threshold(leaf_gray, tau, 255, cv2.THRESH_BINARY)
# Display the grayscale and binary images
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.title('Grayscale Image')
plt.imshow(leaf_gray, cmap='gray')
plt.axis('off')
plt.subplot(1, 2, 2)
plt.title('Binary Image')
plt.imshow(leaf_binary, cmap='gray')
plt.axis('off')
plt.show()
# Import necessary libraries
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Load the image
leaf_image = cv2.imread('/content/leaf.jpg')
# Convert to grayscale
leaf_gray = cv2.cvtColor(leaf_image, cv2.COLOR_BGR2GRAY)
# Apply thresholding
tau = 220
_, leaf_binary = cv2.threshold(leaf_gray, tau, 255, cv2.THRESH_BINARY_INV) # Use binary inverse to get white leaf on black background
# Display the binary image to ensure it's correct
plt.figure(figsize=(5, 5))
plt.title('Binary Image')
plt.imshow(leaf_binary, cmap='gray')
plt.axis('off')
plt.show()
# Extract the contours using the Moore boundary tracing algorithm
contours, _ = cv2.findContours(leaf_binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Find the largest contour based on the area
largest_contour = max(contours, key=cv2.contourArea)
# Draw the largest contour on the original image
contour_image = leaf_image.copy()
cv2.drawContours(contour_image, [largest_contour], -1, (255, 0, 0), 2) # Red color for the contour
# Display the original image with the largest contour
plt.figure(figsize=(10, 5))
plt.title('Original Image with Contour')
plt.imshow(cv2.cvtColor(contour_image, cv2.COLOR_BGR2RGB))
plt.axis('off')
plt.show()
# Import necessary libraries
import numpy as np
import cv2
# Function to calculate Fourier Descriptors
def calculate_fourier_descriptors(contour, n_descriptors):
# Flatten the contour array
contour_array = contour[:, 0, :]
complex_contour = contour_array[:, 0] + 1j * contour_array[:, 1]
# Compute the Fourier transform
fourier_result = np.fft.fft(complex_contour)
# Zero out all but the first n_descriptors
descriptors = np.zeros_like(fourier_result)
descriptors[:n_descriptors] = fourier_result[:n_descriptors]
return descriptors
# Get the largest contour
largest_contour = max(contours, key=cv2.contourArea)
# Number of descriptors to keep
n_descriptors = len(largest_contour) # Keep all descriptors initially
fourier_descriptors = calculate_fourier_descriptors(largest_contour, n_descriptors)
# Function to reconstruct the contour from Fourier Descriptors
def reconstruct_contour(fourier_descriptors, n_points):
# Compute the inverse Fourier transform
reconstructed_complex = np.fft.ifft(fourier_descriptors)
# Convert to (x, y) coordinates
reconstructed_contour = np.vstack((reconstructed_complex.real, reconstructed_complex.imag)).T
# Normalize coordinates to the original image size
reconstructed_contour = np.int32(reconstructed_contour)
return reconstructed_contour
# Function to draw reconstructed contour on the image
def draw_reconstructed_contour(image, reconstructed_contour, color=(255, 0, 0)):
reconstructed_image = image.copy()
cv2.polylines(reconstructed_image, [reconstructed_contour], isClosed=True, color=color, thickness=2)
return reconstructed_image
# Reconstruct and display contours for different percentages of descriptors
percentages = [100, 50, 10, 1]
plt.figure(figsize=(20, 10))
for i, perc in enumerate(percentages):
n_descriptors = int(len(fourier_descriptors) * perc / 100)
reduced_descriptors = np.zeros_like(fourier_descriptors)
reduced_descriptors[:n_descriptors] = fourier_descriptors[:n_descriptors]
reconstructed_contour = reconstruct_contour(reduced_descriptors, len(largest_contour))
contour_image = draw_reconstructed_contour(leaf_image, reconstructed_contour, color=(255, 0, 0))
plt.subplot(1, 4, i + 1)
plt.title(f'{perc}% Descriptors')
plt.imshow(cv2.cvtColor(contour_image, cv2.COLOR_BGR2RGB))
plt.axis('off')
plt.show()
# Rotate and translate the image
angle = 60
tx, ty = 100, 60
# Get the rotation matrix
(h, w) = leaf_image.shape[:2]
center = (w // 2, h // 2)
M = cv2.getRotationMatrix2D(center, angle, 1.0)
# Perform the rotation
rotated_image = cv2.warpAffine(leaf_image, M, (w, h))
# Perform the translation
translated_image = cv2.warpAffine(rotated_image, np.float32([[1, 0, tx], [0, 1, ty]]), (w, h))
# Display the transformed image
plt.figure(figsize=(10, 5))
plt.title('Transformed Image')
plt.imshow(cv2.cvtColor(translated_image, cv2.COLOR_BGR2RGB))
plt.axis('off')
plt.show()
# Convert to grayscale and apply thresholding
leaf_gray_transformed = cv2.cvtColor(translated_image, cv2.COLOR_BGR2GRAY)
_, leaf_binary_transformed = cv2.threshold(leaf_gray_transformed, tau, 255, cv2.THRESH_BINARY_INV)
# Extract the contour using the Moore boundary tracing algorithm
contours_transformed, _ = cv2.findContours(leaf_binary_transformed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
largest_contour_transformed = max(contours_transformed, key=cv2.contourArea)
# Calculate the Fourier Descriptors for the transformed contour
fourier_descriptors_transformed = calculate_fourier_descriptors(largest_contour_transformed, len(largest_contour_transformed))
# Reconstruct and display contours for different percentages of descriptors
plt.figure(figsize=(20, 10))
for i, perc in enumerate(percentages):
n_descriptors = int(len(fourier_descriptors_transformed) * perc / 100)
reduced_descriptors = np.zeros_like(fourier_descriptors_transformed)
reduced_descriptors[:n_descriptors] = fourier_descriptors_transformed[:n_descriptors]
reconstructed_contour = reconstruct_contour(reduced_descriptors, len(largest_contour_transformed))
contour_image_transformed = draw_reconstructed_contour(translated_image, reconstructed_contour, color=(255, 0, 0))
plt.subplot(1, 4, i + 1)
plt.title(f'{perc}% Descriptors')
plt.imshow(cv2.cvtColor(contour_image_transformed, cv2.COLOR_BGR2RGB))
plt.axis('off')
plt.show()
# Import necessary libraries
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Load the image
lenna_image = cv2.imread('/content/lenna.jpg', cv2.IMREAD_GRAYSCALE)
# Display the original image
plt.figure(figsize=(5, 5))
plt.title('Original Image')
plt.imshow(lenna_image, cmap='gray')
plt.axis('off')
plt.show()
# Function to apply 2D-DCT to each block
def apply_dct(image, block_size=32):
h, w = image.shape
# Pad the image to make its dimensions divisible by the block size
h_padded = (h // block_size + 1) * block_size if h % block_size != 0 else h
w_padded = (w // block_size + 1) * block_size if w % block_size != 0 else w
padded_image = np.zeros((h_padded, w_padded), dtype=np.float32)
padded_image[:h, :w] = image
dct_image = np.zeros_like(padded_image, dtype=np.float32)
for i in range(0, h_padded, block_size):
for j in range(0, w_padded, block_size):
block = padded_image[i:i+block_size, j:j+block_size]
dct_block = cv2.dct(np.float32(block))
dct_image[i:i+block_size, j:j+block_size] = dct_block
return dct_image, (h, w)
dct_image, original_shape = apply_dct(lenna_image)
# Function to retain DCT coefficients using the zonal method
def zonal_method(dct_image, block_size=32, retain_percentage=50):
h, w = dct_image.shape
retain_size = int(block_size * retain_percentage / 100)
mask = np.zeros((block_size, block_size), dtype=np.float32)
mask[:retain_size, :retain_size] = 1
retained_dct = np.zeros_like(dct_image, dtype=np.float32)
for i in range(0, h, block_size):
for j in range(0, w, block_size):
block = dct_image[i:i+block_size, j:j+block_size]
retained_dct[i:i+block_size, j:j+block_size] = block * mask
return retained_dct
# Function to retain DCT coefficients using the threshold method
def threshold_method(dct_image, threshold):
retained_dct = np.where(np.abs(dct_image) > threshold, dct_image, 0)
return retained_dct
# Function to apply inverse 2D-DCT to each block
def apply_idct(dct_image, original_shape, block_size=32):
h, w = original_shape
h_padded, w_padded = dct_image.shape
idct_image = np.zeros((h_padded, w_padded), dtype=np.float32)
for i in range(0, h_padded, block_size):
for j in range(0, w_padded, block_size):
block = dct_image[i:i+block_size, j:j+block_size]
idct_block = cv2.idct(block)
idct_image[i:i+block_size, j:j+block_size] = idct_block
# Crop the image to the original size
idct_image_cropped = idct_image[:h, :w]
return np.uint8(idct_image_cropped)
# Example usage for 50% coefficients retained using zonal method
zonal_dct_50 = zonal_method(dct_image, retain_percentage=50)
reconstructed_image_zonal_50 = apply_idct(zonal_dct_50, original_shape)
# Example usage for threshold method
threshold_dct = threshold_method(dct_image, threshold=10)
reconstructed_image_threshold = apply_idct(threshold_dct, original_shape)
# Display the reconstructed images
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.title('Reconstructed Image (Zonal Method, 50%)')
plt.imshow(reconstructed_image_zonal_50, cmap='gray')
plt.axis('off')
plt.subplot(1, 2, 2)
plt.title('Reconstructed Image (Threshold Method)')
plt.imshow(reconstructed_image_threshold, cmap='gray')
plt.axis('off')
plt.show()
# Function to calculate MSE
def calculate_mse(original, reconstructed):
return np.mean((original - reconstructed) ** 2)
# Retain percentages to evaluate
retain_percentages = [5, 10, 20, 30, 40, 50]
mse_zonal = []
mse_threshold = []
# Calculate MSE for each retain percentage using zonal method
for perc in retain_percentages:
zonal_dct = zonal_method(dct_image, retain_percentage=perc)
reconstructed_image = apply_idct(zonal_dct, original_shape)
mse = calculate_mse(lenna_image, reconstructed_image)
mse_zonal.append(mse)
# Calculate MSE for each retain percentage using threshold method
threshold_values = [5, 10, 20, 30, 40, 50]
for thresh in threshold_values:
threshold_dct = threshold_method(dct_image, threshold=thresh)
reconstructed_image = apply_idct(threshold_dct, original_shape)
mse = calculate_mse(lenna_image, reconstructed_image)
mse_threshold.append(mse)
# Plot the MSE results
plt.figure(figsize=(10, 5))
plt.plot(retain_percentages, mse_zonal, label='Zonal Method')
plt.plot(threshold_values, mse_threshold, label='Threshold Method')
plt.xlabel('Percentage of Retained Coefficients / Threshold Value')
plt.ylabel('Mean Squared Error')
plt.legend()
plt.title('MSE vs. Retained Coefficients / Threshold Value')
plt.show()
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Load the image
board_image = cv2.imread('/content/board.png', cv2.IMREAD_GRAYSCALE)
# Function to add Gaussian noise to an image
def add_gaussian_noise(image, snr_db):
# Calculate the signal power
signal_power = np.mean(image**2)
# Calculate the noise power
snr_linear = 10**(snr_db / 10)
noise_power = signal_power / snr_linear
# Generate Gaussian noise
mean = 0
std_dev = np.sqrt(noise_power)
noise = np.random.normal(mean, std_dev, image.shape)
# Add noise to the image
noisy_image = image + noise
noisy_image_clipped = np.clip(noisy_image, 0, 255).astype(np.uint8)
return noisy_image_clipped
# Add Gaussian noise with SNR = 15 dB
snr_db = 15
noisy_image_gaussian = add_gaussian_noise(board_image, snr_db)
# Calculate the actual SNR to confirm
actual_snr = 10 * np.log10(np.mean(board_image**2) / np.mean((board_image - noisy_image_gaussian)**2))
print(f'Actual SNR: {actual_snr:.2f} dB')
# Display the original and noisy images
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.title('Original Image')
plt.imshow(board_image, cmap='gray')
plt.axis('off')
plt.subplot(1, 2, 2)
plt.title('Image with Gaussian Noise (SNR = 15 dB)')
plt.imshow(noisy_image_gaussian, cmap='gray')
plt.axis('off')
plt.show()
# Function to apply moving average filter
def apply_moving_average_filter(image, kernel_size):
return cv2.blur(image, (kernel_size, kernel_size))
# Function to apply median filter
def apply_median_filter(image, kernel_size):
return cv2.medianBlur(image, kernel_size)
# Define kernel sizes
kernel_sizes = [3, 5, 7, 9]
# Apply filters to the noisy image with Gaussian noise
plt.figure(figsize=(15, 10))
plt.subplot(2, 5, 1)
plt.title('Noisy Image (Gaussian)')
plt.imshow(noisy_image_gaussian, cmap='gray')
plt.axis('off')
for i, size in enumerate(kernel_sizes, start=2):
avg_filtered = apply_moving_average_filter(noisy_image_gaussian, size)
plt.subplot(2, 5, i)
plt.title(f'Avg Filter {size}x{size}')
plt.imshow(avg_filtered, cmap='gray')
plt.axis('off')
median_filtered = apply_median_filter(noisy_image_gaussian, size)
plt.subplot(2, 5, i + 5)
plt.title(f'Median Filter {size}x{size}')
plt.imshow(median_filtered, cmap='gray')
plt.axis('off')
plt.show()
# Function to add salt-and-pepper noise to an image
def add_salt_and_pepper_noise(image, density):
noisy_image = image.copy()
num_salt = np.ceil(density * image.size * 0.5).astype(int)
num_pepper = np.ceil(density * image.size * 0.5).astype(int)
# Add salt
coords = [np.random.randint(0, i - 1, num_salt) for i in image.shape]
noisy_image[coords[0], coords[1]] = 255
# Add pepper
coords = [np.random.randint(0, i - 1, num_pepper) for i in image.shape]
noisy_image[coords[0], coords[1]] = 0
return noisy_image
# Add salt-and-pepper noise with 30% density
density = 0.3
noisy_image_sp = add_salt_and_pepper_noise(board_image, density)
# Display the original and noisy images
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.title('Original Image')
plt.imshow(board_image, cmap='gray')
plt.axis('off')
plt.subplot(1, 2, 2)
plt.title('Image with Salt-and-Pepper Noise (30% density)')
plt.imshow(noisy_image_sp, cmap='gray')
plt.axis('off')
plt.show()
# Apply filters to the noisy image with salt-and-pepper noise
plt.figure(figsize=(15, 10))
plt.subplot(2, 5, 1)
plt.title('Noisy Image (Salt-and-Pepper)')
plt.imshow(noisy_image_sp, cmap='gray')
plt.axis('off')
for i, size in enumerate(kernel_sizes, start=2):
avg_filtered_sp = apply_moving_average_filter(noisy_image_sp, size)
plt.subplot(2, 5, i)
plt.title(f'Avg Filter {size}x{size}')
plt.imshow(avg_filtered_sp, cmap='gray')
plt.axis('off')
median_filtered_sp = apply_median_filter(noisy_image_sp, size)
plt.subplot(2, 5, i + 5)
plt.title(f'Median Filter {size}x{size}')
plt.imshow(median_filtered_sp, cmap='gray')
plt.axis('off')
plt.show()
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Load the images
dark_road_1 = cv2.imread('/content/dark_road_1.jpg', cv2.IMREAD_GRAYSCALE)
dark_road_2 = cv2.imread('/content/dark_road_2.jpg', cv2.IMREAD_GRAYSCALE)
dark_road_3 = cv2.imread('/content/dark_road_3.jpg', cv2.IMREAD_GRAYSCALE)
images = [dark_road_1, dark_road_2, dark_road_3]
titles = ['Dark Road 1', 'Dark Road 2', 'Dark Road 3']
plt.figure(figsize=(15, 10))
for i, img in enumerate(images):
plt.subplot(3, 2, 2*i + 1)
plt.title(titles[i])
plt.imshow(img, cmap='gray')
plt.axis('off')
plt.subplot(3, 2, 2*i + 2)
plt.title(f'Histogram of {titles[i]}')
plt.hist(img.ravel(), 256, [0, 256])
plt.show()
# Function to apply global histogram equalization
def global_histogram_equalization(image):
return cv2.equalizeHist(image)
plt.figure(figsize=(15, 10))
for i, img in enumerate(images):
equalized_img = global_histogram_equalization(img)
plt.subplot(3, 2, 2*i + 1)
plt.title(f'Equalized {titles[i]}')
plt.imshow(equalized_img, cmap='gray')
plt.axis('off')
plt.subplot(3, 2, 2*i + 2)
plt.title(f'Histogram of Equalized {titles[i]}')
plt.hist(equalized_img.ravel(), 256, [0, 256])
plt.show()
# Function to apply local histogram equalization (CLAHE)
def local_histogram_equalization(image, clip_limit=2.0, tile_grid_size=(8, 8)):
clahe = cv2.createCLAHE(clipLimit=clip_limit, tileGridSize=tile_grid_size)
return clahe.apply(image)
plt.figure(figsize=(15, 10))
for i, img in enumerate(images):
clahe_img = local_histogram_equalization(img)
plt.subplot(3, 2, 2*i + 1)
plt.title(f'CLAHE {titles[i]}')
plt.imshow(clahe_img, cmap='gray')
plt.axis('off')
plt.subplot(3, 2, 2*i + 2)
plt.title(f'Histogram of CLAHE {titles[i]}')
plt.hist(clahe_img.ravel(), 256, [0, 256])
plt.show()
import cv2
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import convolve2d, wiener
# Load the image
new_york_image = cv2.imread('/content/new_york.png', cv2.IMREAD_GRAYSCALE)
# Function to degrade the image using Gaussian blur and Gaussian noise
def degrade_image(image, std_dev, snr_db):
# Create Gaussian blur kernel
kernel_size = int(6 * std_dev + 1)
gaussian_kernel = cv2.getGaussianKernel(kernel_size, std_dev)
gaussian_kernel_2d = gaussian_kernel @ gaussian_kernel.T
# Apply Gaussian blur
blurred_image = convolve2d(image, gaussian_kernel_2d, mode='same', boundary='symm')
# Calculate signal power and noise power
signal_power = np.mean(blurred_image**2)
snr_linear = 10**(snr_db / 10)
noise_power = signal_power / snr_linear
noise_std_dev = np.sqrt(noise_power)
# Add Gaussian noise
noise = np.random.normal(0, noise_std_dev, image.shape)
noisy_blurred_image = blurred_image + noise
return noisy_blurred_image, gaussian_kernel_2d
# Degrade the image
std_dev = 1.5 # Standard deviation for Gaussian blur
snr_db = 7 # Signal-to-noise ratio in dB
degraded_image, psf = degrade_image(new_york_image, std_dev, snr_db)
# Display the original and degraded images
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.title('Original Image')
plt.imshow(new_york_image, cmap='gray')
plt.axis('off')
plt.subplot(1, 2, 2)
plt.title('Degraded Image')
plt.imshow(degraded_image, cmap='gray')
plt.axis('off')
plt.show()
# Function to display the PSF and its frequency response
def display_psf_and_frequency_response(psf):
psf_fft = np.fft.fftshift(np.fft.fft2(psf))
psf_magnitude = np.abs(psf_fft)
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.title('Point Spread Function (PSF)')
plt.imshow(psf, cmap='gray')
plt.axis('off')
plt.subplot(1, 2, 2)
plt.title('Frequency Response of PSF')
plt.imshow(np.log1p(psf_magnitude), cmap='gray')
plt.axis('off')
plt.show()
# Display the PSF and its frequency response
display_psf_and_frequency_response(psf)
# Function to apply Wiener deconvolution
def wiener_deconvolution(image, psf, snr):
# Compute the Fourier transforms
image_fft = np.fft.fft2(image)
psf_fft = np.fft.fft2(psf, s=image.shape)
psf_fft_conj = np.conj(psf_fft)
# Compute the Wiener filter
H = psf_fft * psf_fft_conj
G = psf_fft_conj * image_fft
wiener_filter = G / (H + 1/snr)
# Apply the Wiener filter and compute the inverse FFT
restored_image_fft = wiener_filter
restored_image = np.fft.ifft2(restored_image_fft)
restored_image = np.abs(restored_image)
return restored_image
# Known SNR
known_snr = 10**(snr_db / 10)
# Restore the image with known noise power
restored_image_known = wiener_deconvolution(degraded_image, psf, known_snr)
# Estimate noise power from the degraded image
estimated_noise_power = np.var(degraded_image - new_york_image)
estimated_snr = 10 * np.log10(np.mean(degraded_image**2) / estimated_noise_power)
# Restore the image with estimated noise power
restored_image_estimated = wiener_deconvolution(degraded_image, psf, 10**(estimated_snr / 10))
# Display the restored images
plt.figure(figsize=(15, 10))
plt.subplot(1, 3, 1)
plt.title('Degraded Image')
plt.imshow(degraded_image, cmap='gray')
plt.axis('off')
plt.subplot(1, 3, 2)
plt.title('Restored Image (Known SNR)')
plt.imshow(restored_image_known, cmap='gray')
plt.axis('off')
plt.subplot(1, 3, 3)
plt.title('Restored Image (Estimated SNR)')
plt.imshow(restored_image_estimated, cmap='gray')
plt.axis('off')
plt.show()
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Load the image
hallway_image = cv2.imread('/content/hallway.png', cv2.IMREAD_GRAYSCALE)
# Apply Sobel masks to estimate the gradient components
sobel_x = cv2.Sobel(hallway_image, cv2.CV_64F, 1, 0, ksize=3)
sobel_y = cv2.Sobel(hallway_image, cv2.CV_64F, 0, 1, ksize=3)
# Compute the gradient magnitude
gradient_magnitude = np.sqrt(sobel_x**2 + sobel_y**2)
gradient_magnitude = cv2.convertScaleAbs(gradient_magnitude)
# Display the gradient components and the gradient magnitude
plt.figure(figsize=(15, 10))
plt.subplot(2, 2, 1)
plt.title('Original Image')
plt.imshow(hallway_image, cmap='gray')
plt.axis('off')
plt.subplot(2, 2, 2)
plt.title('Sobel X')
plt.imshow(cv2.convertScaleAbs(sobel_x), cmap='gray')
plt.axis('off')
plt.subplot(2, 2, 3)
plt.title('Sobel Y')
plt.imshow(cv2.convertScaleAbs(sobel_y), cmap='gray')
plt.axis('off')
plt.subplot(2, 2, 4)
plt.title('Gradient Magnitude')
plt.imshow(gradient_magnitude, cmap='gray')
plt.axis('off')
plt.show()
# Function to apply global thresholding
def global_thresholding(image, threshold_value):
_, binary_image = cv2.threshold(image, threshold_value, 255, cv2.THRESH_BINARY)
return binary_image
# Apply global thresholding
threshold_value = 50 # You can adjust this value
binary_edges = global_thresholding(gradient_magnitude, threshold_value)
# Display the binary edge image
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.title('Gradient Magnitude Histogram')
plt.hist(gradient_magnitude.ravel(), 256, [0, 256])
plt.axvline(x=threshold_value, color='r', linestyle='--')
plt.subplot(1, 2, 2)
plt.title('Binary Edge Image')
plt.imshow(binary_edges, cmap='gray')
plt.axis('off')
plt.show()
# Function to apply Hough transform
def hough_transform(image):
lines = cv2.HoughLinesP(image, rho=1, theta=np.pi/180, threshold=80, minLineLength=30, maxLineGap=10)
line_image = np.copy(hallway_image)
if lines is not None:
for line in lines:
x1, y1, x2, y2 = line[0]
cv2.line(line_image, (x1, y1), (x2, y2), (255, 0, 0), 2)
return line_image
# Apply the Hough transform to detect straight lines
hough_lines_image = hough_transform(binary_edges)
# Display the result of the Hough transform
plt.figure(figsize=(10, 5))
plt.title('Hough Transform Result')
plt.imshow(hough_lines_image, cmap='gray')
plt.axis('off')
plt.show()
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Load the image
coins_image = cv2.imread('/content/coins.png', cv2.IMREAD_GRAYSCALE)
# Compute histogram and find optimal threshold using Otsu's method
def otsu_thresholding(image):
blur = cv2.GaussianBlur(image, (5, 5), 0)
_, binary_image = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
return binary_image
binary_coins = otsu_thresholding(coins_image)
# Display the histogram and the thresholded image
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.title('Histogram of Coins Image')
plt.hist(coins_image.ravel(), 256, [0, 256])
plt.axvline(x=binary_coins.mean(), color='r', linestyle='--')
plt.subplot(1, 2, 2)
plt.title('Binary Image (Otsu\'s Thresholding)')
plt.imshow(binary_coins, cmap='gray')
plt.axis('off')
plt.show()
# Display the segmented coins on a black background
segmented_coins = cv2.bitwise_and(coins_image, coins_image, mask=binary_coins)
plt.figure(figsize=(5, 5))
plt.title('Segmented Coins on Black Background')
plt.imshow(segmented_coins, cmap='gray')
plt.axis('off')
plt.show()
# Find contours of the coins
contours, _ = cv2.findContours(binary_coins, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Create an empty image to draw the contours
coins_contours = np.zeros_like(coins_image)
for i, contour in enumerate(contours):
cv2.drawContours(coins_contours, [contour], -1, (255), thickness=cv2.FILLED)
# Display each coin separately
coin = cv2.bitwise_and(coins_image, coins_image, mask=coins_contours)
plt.figure(figsize=(3, 3))
plt.title(f'Coin {i+1}')
plt.imshow(coin, cmap='gray')
plt.axis('off')
plt.show()
# Clear the mask for the next coin
coins_contours = np.zeros_like(coins_image)
# Create an empty image to draw the contours
coins_contours = np.zeros_like(coins_image)
coin_info = []
for i, contour in enumerate(contours):
# Draw the contour
cv2.drawContours(coins_contours, [contour], -1, (255), thickness=cv2.FILLED)
# Compute center and diameter
M = cv2.moments(contour)
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])
diameter = int(np.sqrt(4 * M["m00"] / np.pi))
coin_info.append((cX, cY, diameter))
# Display each coin with center and diameter
coin = cv2.bitwise_and(coins_image, coins_image, mask=coins_contours)
plt.figure(figsize=(3, 3))
plt.title(f'Coin {i+1}')
plt.imshow(coin, cmap='gray')
plt.scatter([cX], [cY], color='red')
plt.text(cX, cY, f'{diameter}', color='red')
plt.axis('off')
plt.show()
# Clear the mask for the next coin
coins_contours = np.zeros_like(coins_image)
ε# Load the image
football_image = cv2.imread('/content/football.jpg')
# Function to apply k-means clustering
def kmeans_segmentation(image, k):
pixel_values = image.reshape((-1, 3))
pixel_values = np.float32(pixel_values)
# Define criteria and apply k-means
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 0.2)
_, labels, centers = cv2.kmeans(pixel_values, k, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
centers = np.uint8(centers)
segmented_image = centers[labels.flatten()]
segmented_image = segmented_image.reshape(image.shape)
return segmented_image
# Apply k-means clustering for k = [2, 3, 4]
k_values = [2, 3, 4]
for k in k_values:
segmented_image = kmeans_segmentation(football_image, k)
plt.figure(figsize=(5, 5))
plt.title(f'Segmented Image with k={k}')
plt.imshow(cv2.cvtColor(segmented_image, cv2.COLOR_BGR2RGB))
plt.axis('off')
plt.show()