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 = cv2.imread('Coins.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Thresholding to find the markers
ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV +
cv2.THRESH_OTSU)
# Noise removal using morphological operations
kernel = np.ones((3,3), np.uint8)
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations = 2)
# Background area determination
sure_bg = cv2.dilate(opening, kernel, iterations = 3)
# Foreground area determination
dist_transform = cv2.distanceTransform(opening, cv2.DIST_L2, 5)
ret, sure_fg = cv2.threshold(dist_transform, 0.7*dist_transform.max(), 255, 0)
# Finding unknown region
sure_fg = np.uint8(sure_fg)
unknown = cv2.subtract(sure_bg, sure_fg)
# Marker labelling
ret, markers = cv2.connectedComponents(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 = cv2.watershed(img, markers)
img[markers == -1] = [255, 0, 0]
# Display the result
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.show()
OUTPUT
9
To create a program performs discrete wavelet transform on image.
import pywt
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Function to perform DWT on an image
def discrete_wavelet_transform(image_path, wavelet='haar'):
# Read the image
img = cv2.imread(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 = plt.figure(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)
ax.imshow(a, interpolation="nearest", cmap=plt.cm.gray)
ax.set_title(titles[i], fontsize=10)
ax.set_xticks([])
ax.set_yticks([])
fig.tight_layout()
plt.show()
# Path to the image file
image_path = '1.png' # 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 tkinter.colorchooser 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 = np.zeros((100, 100, 3), dtype=np.uint8)
color_box[:] = color_bgr
# Display the color box
cv2.imshow('Color Box', color_box)
cv2.waitKey(0)
cv2.destroyAllWindows()
# 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 = cv2.imread(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 cv2.calcHist
hist = cv2.calcHist([gray_image], [0], None, [256], [0, 256])
# Plot histogram
plt.figure(figsize=(10, 4))
plt.title('Grayscale Histogram')
plt.xlabel('Bins')
plt.ylabel('# of Pixels')
plt.plot(hist)
plt.xlim([0, 256])
plt.show()
# Function to calculate and plot histogram for color image
def histogram_color(image_path):
# Read the image
image = cv2.imread(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 = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# Calculate histograms for each channel
color = ('r', 'g', 'b')
for i, col in enumerate(color):
hist = cv2.calcHist([image], [i], None, [256], [0, 256])
plt.plot(hist, color=col)
# Plot histogram
plt.title('Color Histogram')
plt.xlabel('Bins')
plt.ylabel('# of Pixels')
plt.xlim([0, 256])
plt.show()
# 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 = '1.png' # 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 matplotlib.pyplot as plt
# Create a new color image
width, height = 300, 200
color = (228, 150, 150) # RGB color tuple
img = Image.new('RGB', (width, height), color)
# Save the image to a file
img.save('color_image.png')
# Read the image back from the file
img_read = Image.open('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')
plt.subplot(1, 2, 1) # 1 row, 2 columns, 1st subplot
plt.imshow(img_read, cmap='gray')
plt.title('Original Image')
plt.axis('off')
plt.subplot(1, 2, 2) # 1 row, 2 columns, 2nd subplot
plt.imshow(img_rotated, cmap='gray')
plt.title('color_image_rotated')
plt.axis('off') # Hide axis labels and ticks
plt.show()
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 matplotlib.pyplot as plt
# Load an image (replace "image.jpg" with the actual image file)
image_path = "1.png"
image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
# Apply different edge detection operators
sobel_x = cv2.Sobel(image, cv2.CV_64F, 1, 0, ksize=3)
sobel_y = cv2.Sobel(image, cv2.CV_64F, 0, 1, ksize=3)
laplacian = cv2.Laplacian(image, cv2.CV_64F)
canny = cv2.Canny(image, 100, 200)
# Display the original image and edge-detected images
plt.figure(figsize=(12, 6))
plt.subplot(2, 3, 1), plt.imshow(image, cmap='gray'), plt.title('Original Image')
plt.subplot(2, 3, 2), plt.imshow(sobel_x, cmap='gray'), plt.title('Sobel X')
plt.subplot(2, 3, 3), plt.imshow(sobel_y, cmap='gray'), plt.title('Sobel Y')
plt.subplot(2, 3, 4), plt.imshow(laplacian, cmap='gray'), plt.title('Laplacian')
plt.subplot(2, 3, 5), plt.imshow(canny, cmap='gray'), plt.title('Canny')
plt.tight_layout()
plt.show()
OUTPUT
1
To create a program to display grayscale image using read and
write operation
import cv2
# Load a grayscale image (replace "image.jpg" with your image file)
image_path = "1.png"
gray_image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
# Display the grayscale image
cv2.imshow("Grayscale Image", gray_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
# Save the grayscale image as "grayscale_output.jpg"
output_path = "grayscale_output.jpg"
cv2.imwrite(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 matplotlib.pyplot as plt
# Load a grayscale image (replace "image.jpg" with your image file)
image_path = "1.png"
gray_image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
# Apply a median filter to reduce noise
filtered_image = cv2.medianBlur(gray_image, 5) # Use a 5x5 kernel size
# Display the original image and the filtered image
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1), plt.imshow(gray_image, cmap='gray'), plt.title('Original
Image')
plt.subplot(1, 2, 2), plt.imshow(filtered_image, cmap='gray'),
plt.title('Filtered Image')
plt.tight_layout()
plt.show()
OUTPUT
5
To create a program to discretize an image using Fourier
transformation.
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Load an image (replace "image.jpg" with the actual image file)
image_path = "1.png"
image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
# Perform 2D discrete Fourier transform
f_transform = np.fft.fft2(image)
# Shift the zero frequency component to the center
f_transform_shifted = np.fft.fftshift(f_transform)
# Compute the magnitude spectrum (log scale for visualization)
magnitude_spectrum = np.log(np.abs(f_transform_shifted) + 1)
# Display the original image and its magnitude spectrum
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1), plt.imshow(image, cmap='gray'), plt.title('Original Image')
plt.subplot(1, 2, 2), plt.imshow(magnitude_spectrum, cmap='gray'),
plt.title('Magnitude Spectrum')
plt.tight_layout()
plt.show()
OUTPUT
6
To create a program to eliminate the high frequency components of
an image.
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Load an image (replace "image.jpg" with the actual image file)
image_path = "1.png"
image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
# Perform 2D discrete Fourier transform
f_transform = np.fft.fft2(image)
# Shift the zero frequency component to the center
f_transform_shifted = np.fft.fftshift(f_transform)
# Set a threshold to eliminate high-frequency components (e.g., keep only the
central region)
rows, cols = image.shape
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 = np.zeros((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 = np.fft.ifftshift(f_transform_filtered)
# Perform inverse 2D Fourier transform to get the filtered image
filtered_image = np.abs(np.fft.ifft2(f_transform_filtered_shifted))
# Display the original image and the filtered image
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1), plt.imshow(image, cmap='gray'), plt.title('Original Image')
plt.subplot(1, 2, 2), plt.imshow(filtered_image, cmap='gray'),
plt.title('Filtered Image')
plt.tight_layout()
plt.show()
OUTPUT