10
To create a program for segmentation of an image using watershed
transforms.
import numpy as np
import cv2
from matplotlib import pyplot as plt
# Load the image
img = [Link]('[Link]')
gray = [Link](img, cv2.COLOR_BGR2GRAY)
# Thresholding to find the markers
ret, thresh = [Link](gray, 0, 255, cv2.THRESH_BINARY_INV +
cv2.THRESH_OTSU)
# Noise removal using morphological operations
kernel = [Link]((3,3), np.uint8)
opening = [Link](thresh, cv2.MORPH_OPEN, kernel, iterations = 2)
# Background area determination
sure_bg = [Link](opening, kernel, iterations = 3)
# Foreground area determination
dist_transform = [Link](opening, cv2.DIST_L2, 5)
ret, sure_fg = [Link](dist_transform, 0.7*dist_transform.max(), 255, 0)
# Finding unknown region
sure_fg = np.uint8(sure_fg)
unknown = [Link](sure_bg, sure_fg)
# Marker labelling
ret, markers = [Link](sure_fg)
# Add one to all labels so that sure background is not 0, but 1
markers = markers + 1
# Mark the region of unknown with zero
markers[unknown == 255] = 0
# Apply the watershed algorithm
markers = [Link](img, markers)
img[markers == -1] = [255, 0, 0]
# Display the result
[Link]([Link](img, cv2.COLOR_BGR2RGB))
[Link]()
OUTPUT
9
To create a program performs discrete wavelet transform on image.
import pywt
import cv2
import numpy as np
import [Link] as plt
# Function to perform DWT on an image
def discrete_wavelet_transform(image_path, wavelet='haar'):
# Read the image
img = [Link](image_path, cv2.IMREAD_GRAYSCALE)
if img is None:
print("Error: Could not read the image. Please check the image path.")
return
# Perform Discrete Wavelet Transform
coeffs2 = pywt.dwt2(img, wavelet)
cA, (cH, cV, cD) = coeffs2
# Plot the results
fig = [Link](figsize=(12, 3))
titles = ['Approximation', ' Horizontal detail', 'Vertical detail', 'Diagonal
detail']
for i, a in enumerate([cA, cH, cV, cD]):
ax = fig.add_subplot(1, 4, i + 1)
[Link](a, interpolation="nearest", cmap=[Link])
ax.set_title(titles[i], fontsize=10)
ax.set_xticks([])
ax.set_yticks([])
fig.tight_layout()
[Link]()
# Path to the image file
image_path = '[Link]' # Replace with the actual path to your image
# Perform DWT on the image
discrete_wavelet_transform(image_path)
OUTPUT
8
To obtain the R, B, G colour values and resolved colour values
from a colour box by choosing any colour.
import cv2
import numpy as np
from tkinter import Tk
from [Link] import askcolor
# Function to get RGB and resolved color values
def get_color_values():
# Open color chooser dialog
Tk().withdraw() # we don't want a full GUI, so keep the root window from
appearing
color_hex, color_rgb = askcolor()
if color_rgb is not None:
# Convert RGB to BGR for OpenCV
color_bgr = tuple(reversed(color_rgb))
# Create a 100x100 pixel BGR color box
color_box = [Link]((100, 100, 3), dtype=np.uint8)
color_box[:] = color_bgr
# Display the color box
[Link]('Color Box', color_box)
[Link](0)
[Link]()
# Print the RGB and resolved color values
print(f"Selected RGB Color: {color_rgb}")
print(f"Resolved Color (Hex): {color_hex}")
else:
print("No color was selected.")
# Call the function to get color values
get_color_values()
OUTPUT
2
To create a vision program to find histogram value and display
histograph of a grayscale and color image.
import cv2
import numpy as np
from matplotlib import pyplot as plt
# Function to calculate and plot histogram for grayscale image
def histogram_grayscale(image_path):
# Read the image in grayscale
gray_image = [Link](image_path, cv2.IMREAD_GRAYSCALE)
# Check if image is loaded correctly
if gray_image is None:
print("Error: Could not read the image. Please check the image path.")
return
# Calculate histogram using [Link]
hist = [Link]([gray_image], [0], None, [256], [0, 256])
# Plot histogram
[Link](figsize=(10, 4))
[Link]('Grayscale Histogram')
[Link]('Bins')
[Link]('# of Pixels')
[Link](hist)
[Link]([0, 256])
[Link]()
# Function to calculate and plot histogram for color image
def histogram_color(image_path):
# Read the image
image = [Link](image_path)
# Check if image is loaded correctly
if image is None:
print("Error: Could not read the image. Please check the image path.")
return
# Convert to RGB
image = [Link](image, cv2.COLOR_BGR2RGB)
# Calculate histograms for each channel
color = ('r', 'g', 'b')
for i, col in enumerate(color):
hist = [Link]([image], [i], None, [256], [0, 256])
[Link](hist, color=col)
# Plot histogram
[Link]('Color Histogram')
[Link]('Bins')
[Link]('# of Pixels')
[Link]([0, 256])
[Link]()
# Path to the grayscale image file
grayscale_image_path = 'Negative_image.jpg' # Replace with the actual path to
your grayscale image
# Path to the color image file
color_image_path = '[Link]' # Replace with the actual path to your color image
# Calculate and plot histogram for grayscale image
histogram_grayscale(grayscale_image_path)
# Calculate and plot histogram for color image
histogram_color(color_image_path)
OUTPUT
7
To create a color image and perform read and write operation.
from PIL import Image
import [Link] as plt
# Create a new color image
width, height = 300, 200
color = (228, 150, 150) # RGB color tuple
img = [Link]('RGB', (width, height), color)
# Save the image to a file
[Link]('color_image.png')
# Read the image back from the file
img_read = [Link]('color_image.png')
# Perform some operations (for example, rotate the image)
img_rotated = img_read.rotate(45)
# Save the rotated image to a file
img_rotated.save('color_image_rotated.png')
[Link](1, 2, 1) # 1 row, 2 columns, 1st subplot
[Link](img_read, cmap='gray')
[Link]('Original Image')
[Link]('off')
[Link](1, 2, 2) # 1 row, 2 columns, 2nd subplot
[Link](img_rotated, cmap='gray')
[Link]('color_image_rotated')
[Link]('off') # Hide axis labels and ticks
[Link]()
OUTPUT
4
To create a vision program to determine the edge detection of an
image using different operators.
import cv2
import numpy as np
import [Link] as plt
# Load an image (replace "[Link]" with the actual image file)
image_path = "[Link]"
image = [Link](image_path, cv2.IMREAD_GRAYSCALE)
# Apply different edge detection operators
sobel_x = [Link](image, cv2.CV_64F, 1, 0, ksize=3)
sobel_y = [Link](image, cv2.CV_64F, 0, 1, ksize=3)
laplacian = [Link](image, cv2.CV_64F)
canny = [Link](image, 100, 200)
# Display the original image and edge-detected images
[Link](figsize=(12, 6))
[Link](2, 3, 1), [Link](image, cmap='gray'), [Link]('Original Image')
[Link](2, 3, 2), [Link](sobel_x, cmap='gray'), [Link]('Sobel X')
[Link](2, 3, 3), [Link](sobel_y, cmap='gray'), [Link]('Sobel Y')
[Link](2, 3, 4), [Link](laplacian, cmap='gray'), [Link]('Laplacian')
[Link](2, 3, 5), [Link](canny, cmap='gray'), [Link]('Canny')
plt.tight_layout()
[Link]()
OUTPUT
1
To create a program to display grayscale image using read and
write operation
import cv2
# Load a grayscale image (replace "[Link]" with your image file)
image_path = "[Link]"
gray_image = [Link](image_path, cv2.IMREAD_GRAYSCALE)
# Display the grayscale image
[Link]("Grayscale Image", gray_image)
[Link](0)
[Link]()
# Save the grayscale image as "grayscale_output.jpg"
output_path = "grayscale_output.jpg"
[Link](output_path, gray_image)
print(f"Grayscale image saved as {output_path}")
OUTPUT
3
To create a vision program for nonlinear filtering technique using
edge detection
import cv2
import numpy as np
import [Link] as plt
# Load a grayscale image (replace "[Link]" with your image file)
image_path = "[Link]"
gray_image = [Link](image_path, cv2.IMREAD_GRAYSCALE)
# Apply a median filter to reduce noise
filtered_image = [Link](gray_image, 5) # Use a 5x5 kernel size
# Display the original image and the filtered image
[Link](figsize=(10, 5))
[Link](1, 2, 1), [Link](gray_image, cmap='gray'), [Link]('Original
Image')
[Link](1, 2, 2), [Link](filtered_image, cmap='gray'),
[Link]('Filtered Image')
plt.tight_layout()
[Link]()
OUTPUT
5
To create a program to discretize an image using Fourier
transformation.
import cv2
import numpy as np
import [Link] as plt
# Load an image (replace "[Link]" with the actual image file)
image_path = "[Link]"
image = [Link](image_path, cv2.IMREAD_GRAYSCALE)
# Perform 2D discrete Fourier transform
f_transform = [Link].fft2(image)
# Shift the zero frequency component to the center
f_transform_shifted = [Link](f_transform)
# Compute the magnitude spectrum (log scale for visualization)
magnitude_spectrum = [Link]([Link](f_transform_shifted) + 1)
# Display the original image and its magnitude spectrum
[Link](figsize=(10, 5))
[Link](1, 2, 1), [Link](image, cmap='gray'), [Link]('Original Image')
[Link](1, 2, 2), [Link](magnitude_spectrum, cmap='gray'),
[Link]('Magnitude Spectrum')
plt.tight_layout()
[Link]()
OUTPUT
6
To create a program to eliminate the high frequency components of
an image.
import cv2
import numpy as np
import [Link] as plt
# Load an image (replace "[Link]" with the actual image file)
image_path = "[Link]"
image = [Link](image_path, cv2.IMREAD_GRAYSCALE)
# Perform 2D discrete Fourier transform
f_transform = [Link].fft2(image)
# Shift the zero frequency component to the center
f_transform_shifted = [Link](f_transform)
# Set a threshold to eliminate high-frequency components (e.g., keep only the
central region)
rows, cols = [Link]
center_row, center_col = rows // 2, cols // 2
radius = 30 # Adjust this value to control the amount of high-frequency removal
# Create a circular mask to keep the low-frequency components
mask = [Link]((rows, cols), dtype=np.uint8)
mask[center_row - radius:center_row + radius, center_col - radius:center_col +
radius] = 1
# Apply the mask to the shifted Fourier transform
f_transform_filtered = f_transform_shifted * mask
# Shift the zero frequency component back to the corner
f_transform_filtered_shifted = [Link](f_transform_filtered)
# Perform inverse 2D Fourier transform to get the filtered image
filtered_image = [Link]([Link].ifft2(f_transform_filtered_shifted))
# Display the original image and the filtered image
[Link](figsize=(10, 5))
[Link](1, 2, 1), [Link](image, cmap='gray'), [Link]('Original Image')
[Link](1, 2, 2), [Link](filtered_image, cmap='gray'),
[Link]('Filtered Image')
plt.tight_layout()
[Link]()
OUTPUT