Professional Documents
Culture Documents
Input:
import cv2
import numpy as np
from matplotlib import pyplot as plt
def histogram_equalization(img):
hist, bins = np.histogram(img.flatten(), 256, [0,256])
cdf = hist.cumsum()
cdf_normalized = cdf * hist.max() / cdf.max()
new_pixels = np.round(cdf_normalized[img.flatten()]).astype(np.uint8)
new_img = np.reshape(new_pixels, img.shape)
return new_img
img = cv2.imread('moon.jpg', cv2.IMREAD_GRAYSCALE)
equalized_img = histogram_equalization(img)
fig, axs = plt.subplots(1, 2, figsize=(10,5))
axs[0].hist(img.flatten(), 256, [0,256], color='b')
axs[0].set_title('Input Image Histogram')
axs[1].hist(equalized_img.flatten(), 256, [0,256], color='b')
axs[1].set_title('Equalized Image Histogram')
plt.show()
cv2.imshow('Equalized Image', equalized_img)
cv2.imshow('Input Image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Output:
2. Sharpening using the second derivative.
Input:
import cv2
import numpy as np
from matplotlib import pyplot as plt img = cv2.imread('moon.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) blur = cv2.GaussianBlur(gray, (5,5), 0)
laplacian = cv2.Laplacian(blur, cv2.CV_64F)
sharpened = gray + laplacian
sharpened = cv2.normalize(sharpened, None, alpha=0, beta=255, norm_type=cv2.NORM_MINMA
fig, axs = plt.subplots(1, 2, figsize=(10,5)) axs[0].imshow(cv2.cvtColor(img, cv2.COLOR_BGR2R
axs[1].imshow(sharpened, cmap='gray') axs[1].set_title('Sharpened Image') plt.show()
Output:
3. Compute the function gradient_magnitude that calculates the
magnitude of gradient vector image corresponding to a given image. T
Input:
import cv2
import numpy as np
def gradient_magnitude(image):
sobel_x = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]])
sobel_y = np.array([[-1, -2, -1], [0, 0, 0], [1, 2, 1]])
gx = cv2.filter2D(image, cv2.CV_32F, sobel_x)
gy = cv2.filter2D(image, cv2.CV_32F, sobel_y)
magnitude = np.sqrt(gx*2 + gy*2)
magnitude = cv2.normalize(magnitude, None, 0, 255, cv2.NORM_MINMAX,
dtype=cv2.CV_8U)
return magnitude
image = cv2.imread('moon.jpg', cv2.IMREAD_GRAYSCALE)
gradient_magnitude_image = gradient_magnitude(image)
cv2.imshow('Input image', image)
cv2.imshow('Gradient magnitude image', gradient_magnitude_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
Output: