Exp 3
Exp 3
Aim:
1. Libraries used:
• NumPy
• Opencv-python
• Matplotlib
• Scipy
Programs:
• Read in an image
• Find the Width, Height and Color Channels of the image
• Converting to a shade
• Converting to grayscale
1. IMAGE NEGATIVE
import cv2
import matplotlib.pyplot as plt
imgpath = 'test.tiff'
img = cv2.imread('bike.jpg')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
gray = cv2.imread('bike.jpg', 0)
colored_negative = abs(255-img)
gray_negative = abs(255-gray)
imgs = [img, gray, colored_negative, gray_negative]
title = ['colored', 'gray', 'colored-negative', 'colored-gray']
plt.subplot(2, 2, 1)
plt.title(title[0])
plt.imshow(imgs[0])
plt.xticks([])
plt.yticks([])
plt.subplot(2, 2, 2)
plt.title(title[1])
plt.imshow(imgs[1], cmap='gray')
plt.xticks([])
plt.yticks([])
plt.subplot(2, 2, 3)
plt.title(title[2])
plt.imshow(imgs[2])
plt.xticks([])
plt.yticks([])
plt.subplot(2, 2, 4)
plt.title(title[3])
plt.imshow(imgs[3], cmap='gray')
plt.xticks([])
plt.yticks([])
plt.show()
OUTPUT :
2. LOGARITHMIC TRANSFORMATION :
import cv2
import numpy as np
OUTPUT :
3. POWER LAW (GAMMA) TRANSFORMATION :
import cv2
import numpy as np
OUTPUT :
4. CONTRAST STRETCHING :
import cv2
import numpy as np
# Function to map each intensity level to output intensity level.
def pixelVal(pix, r1, s1, r2, s2):
if (0 <= pix and pix <= r1):
return (s1 / r1)*pix
elif (r1 < pix and pix <= r2):
return ((s2 - s1)/(r2 - r1)) * (pix - r1) + s1
else:
return ((255 - s2)/(255 - r2)) * (pix - r2) + s2
# Open the image.
img = cv2.imread('dog.jpeg')
# Define parameters.
r1 = 70
s1 = 0
r2 = 140
s2 = 255
# Vectorize the function to apply it to each value in the Numpy array.
pixelVal_vec = np.vectorize(pixelVal)
# Apply contrast stretching.
contrast_stretched = pixelVal_vec(img, r1, s1, r2, s2)
contrast_stretched = cv2.resize(contrast_stretched, (500,500))
# Save edited image.
cv2.imshow('contrast_stretch.jpg', contrast_stretched)
cv2.waitKey(0)
cv2.destroyAllWindows()
OUTPUT :
lst = []
for i in range(img.shape[0]):
for j in range(img.shape[1]):
lst.append(np.binary_repr(img[i][j], width=8)) # width = no. of bits
cv2.imshow('a', final)
cv2.waitKey(0)
cv2.destroyAllWindows()
OUTPUT :
2. Paint and Draw on an image (Both in image and live stream)
1. Paint the image with certain color
2. Draw a Rectangle
3. Draw a circle
4. Draw a line
5. Write text
OUTPUT :
LIVE STREAM (USING WEBCAM):
import cv2
cam = cv2.VideoCapture(0)
frame_width = int(cam.get(cv2.CAP_PROP_FRAME_WIDTH))
frame_height = int(cam.get(cv2.CAP_PROP_FRAME_HEIGHT))
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter('output.mp4', fourcc, 20.0, (frame_width, frame_height))
while True:
ret, frame = cam.read()
cv2.circle(frame, (150, 150), 100, (0, 0, 255), 1)
cv2.circle(frame, (115, 125), 10, (0, 0, 255), 1)
cv2.circle(frame, (190, 125), 10, (0, 0, 255), 1)
cv2.rectangle(frame, (25, 25), (275, 275), (0, 0, 255), 1)
img = cv2.putText(frame,"Manu",(150,300),cv2.FONT_HERSHEY_COMPLEX,
1,(0,255,0),1)
out.write(frame)
cv2.imshow('Camera', frame)
if cv2.waitKey(1) == ord('q'):
break
cam.release()
out.release()
cv2.destroyAllWindows()
OUTPUT :
3. MASK OR CROP :
import cv2
import numpy as np
low_green = np.array([25, 52, 72])
high_green = np.array([102, 255, 255])
cap=cv2.VideoCapture(0)
while True:
ret,frame=cap.read()
cv2.imshow('original Frame',frame)
hsv=cv2.cvtColor(frame,cv2.COLOR_HSV2BGR)
mask=cv2.inRange(hsv,low_green,high_green)
cv2.imshow('Masked Frame',mask)
if cv2.waitKey(1)==ord('q'):
break
cap.release()
cv2.destroyAllWindows()
OUTPUT (WITH WEBCAM):
(FROM ALBUMS):
4. HISTOGRAM OF AN IMAGE :
import cv2
from matplotlib import pyplot as plt
img = cv2.imread('bike.jpg',0)
histr = cv2.calcHist([img],[0],None,[256],[0,256])
plt.plot(histr)
plt.show()
OUTPUT :
Original image :
plt.subplot(2, 3, 2)
plt.title(title[1])
plt.imshow(imgs[1], cmap='gray')
plt.xticks([])
plt.yticks([])
plt.subplot(2, 3, 3)
plt.title(title[2])
plt.imshow(imgs[2], cmap='gray')
plt.xticks([])
plt.yticks([])
plt.subplot(2, 3, 4)
plt.title(title[3])
plt.imshow(imgs[3], cmap='gray')
plt.xticks([])
plt.yticks([])
plt.subplot(2, 3, 5)
plt.title(title[4])
plt.imshow(imgs[4], cmap='gray')
plt.xticks([])
plt.yticks([])
OUTPUT :
2. ADAPTIVE THRESHOLD :
import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
img = cv.imread('pexels-pixabay-66898.jpg', cv.IMREAD_GRAYSCALE)
#img = cv.medianBlur(img, 5)
ret, th1 = cv.threshold(img, 127, 255, cv.THRESH_BINARY)
th2 = cv.adaptiveThreshold(img, 255, cv.ADAPTIVE_THRESH_MEAN_C,cv.THRESH_BINARY,
11, 2)
th3 = cv.adaptiveThreshold(img, 255,
cv.ADAPTIVE_THRESH_GAUSSIAN_C,cv.THRESH_BINARY, 11, 2)
titles = ['Original Image', 'Global Thresholding (v = 127)',
'Adaptive Mean Thresholding', 'Adaptive Gaussian Thresholding']
images = [img, th1, th2, th3]
for i in range(4):
plt.subplot(2, 2, i + 1), plt.imshow(images[i], 'gray')
plt.title(titles[i])
plt.xticks([]), plt.yticks([])
plt.show()
OUTPUT :
INPUT IMAGE :
3. OTSU THRESHOLD :
import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
img = cv.imread('pexels-futurekiiid-3551498.jpg', cv.IMREAD_GRAYSCALE)
# global thresholding
ret1, th1 = cv.threshold(img, 127, 255, cv.THRESH_BINARY)
# Otsu's thresholding
ret2, th2 = cv.threshold(img, 0, 255, cv.THRESH_BINARY + cv.THRESH_OTSU)
# Otsu's thresholding after Gaussian filtering
blur = cv.GaussianBlur(img, (5, 5), 0)
ret3, th3 = cv.threshold(blur, 0, 255, cv.THRESH_BINARY + cv.THRESH_OTSU)
# plot all the images and their histograms
images = [img, 0, th1,
img, 0, th2,
blur, 0, th3]
titles = ['Original Noisy Image', 'Histogram', 'Global Thresholding (v=127)',
'Original Noisy Image', 'Histogram', "Otsu's Thresholding",
'Gaussian filtered Image', 'Histogram', "Otsu's Thresholding"]
for i in range(3):
plt.subplot(3, 3, i * 3 + 1), plt.imshow(images[i * 3], 'gray')
plt.title(titles[i * 3]), plt.xticks([]), plt.yticks([])
plt.subplot(3, 3, i * 3 + 2), plt.hist(images[i * 3].ravel(), 256)
plt.title(titles[i * 3 + 1]), plt.xticks([]), plt.yticks([])
plt.subplot(3, 3, i * 3 + 3), plt.imshow(images[i * 3 + 2], 'gray')
plt.title(titles[i * 3 + 2]), plt.xticks([]), plt.yticks([])
plt.show()
OUTPUT :
Result:
Thus the basic image processing concepts were learnt using OpenCV in Visual studio code.
Post Lab Questions:
1. What are the applications of masking and cropping in image processing?
Masking and cropping are fundamental techniques in image processing, each serving
distinct but complementary purposes. Masking involves isolating a specific region of an
image by applying a binary mask, allowing for targeted operations like object detection,
image segmentation, background removal, and feature extraction. It is commonly used
in applications such as medical imaging (e.g., isolating tissues in CT scans), satellite
image analysis, and facial recognition, where only certain areas of the image need to be
processed. Cropping, on the other hand, involves trimming an image to a smaller region,
focusing on areas of interest while removing unnecessary parts. It is widely applied in
tasks like object localization for machine learning, data augmentation, and composition
adjustment in photography. Both techniques are often used together, where a mask first
highlights a region of interest and cropping refines the focus by cutting out irrelevant
areas, making them crucial in areas like remote sensing, document processing (e.g.,
OCR), and image registration for medical or scientific analysis.
Masking and cropping are essential techniques in image processing, each with specific
applications across various domains. Masking involves isolating a particular region of an
image using a binary mask, allowing for targeted processing without affecting the entire
image. This is especially useful in object detection, segmentation, and background
removal. For example, in medical imaging, a mask can help highlight and isolate a tumor
in an MRI scan, while in photography, masking allows the subject to be separated from
the background for further manipulation, such as background replacement. Additionally,
masking is used in satellite imagery, where only specific regions of interest are enhanced
or analyzed, and in feature extraction tasks like facial recognition. Cropping, on the other
hand, involves trimming an image to focus on a smaller region, which is useful for object
localization, data augmentation, and improving composition in photography. In deep
learning, cropping helps by providing different perspectives of the same image to train
models, while in OCR, it isolates text areas from scanned documents for efficient
recognition. Both techniques can be combined, as in the case of image registration, where
a mask isolates the region of interest, and cropping refines the image for comparison.
The concept of masking can be illustrated in a live stream scenario where someone uses
a virtual background effect. In this case, the mask can isolate the person’s body from the
background, allowing them to appear in front of a new, digitally inserted background.
This real-time masking isolates their body using a mask that dynamically adjusts to their
movements, ensuring the background remains unchanged while the subject stays
highlighted. This technique is common in video conferencing, gaming, or virtual live
streaming, where users mask out their surroundings and replace them with a virtual
backdrop.
import cv2
import numpy as np
image = cv2.imread("input_image.jpg")
height, width = image.shape[:2]
mask = np.zeros((height, width), dtype=np.uint8)
center = (width // 2, height // 2)
radius = min(height, width) // 4
cv2.circle(mask, center, radius, 255, -1)
masked_image = cv2.bitwise_and(image, image, mask=mask)
cv2.imshow("Original Image", image)
cv2.imshow("Circular Mask", masked_image)
cv2.imwrite("circular_masked_image.jpg", masked_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
4. What are the different functions available in OpenCV and Numpy packages to
calculate the histogram and histogram equalization of an image?
OpenCV Functions:
1. cv2.calcHist(): Computes image histograms.
2. cv2.equalizeHist(): Performs histogram equalization to enhance contrast.
NumPy Functions:
1. numpy.histogram(): Computes histograms from array data.
2. numpy.histogram2d(): Computes 2D histograms for multi-channel data.
cv2.setMouseCallback("Image", click_event)
cv2.waitKey(0)
cv2.destroyAllWindows()
1.
import cv2
img1 = cv2.imread('image1.jpg')
img2 = cv2.imread('image2.jpg')
added_image = cv2.add(img1, img2)
cv2.imshow("Added Image", added_image)
cv2.imwrite("added_image.jpg", added_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
2.
subtracted_image = cv2.subtract(img1, img2)
cv2.imshow("Subtracted Image", subtracted_image)
cv2.imwrite("subtracted_image.jpg", subtracted_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
3.
bitwise_and = cv2.bitwise_and(img1, img2)
bitwise_or = cv2.bitwise_or(img1, img2)
bitwise_xor = cv2.bitwise_xor(img1, img2)
bitwise_not = cv2.bitwise_not(img1)
cv2.imshow("Bitwise AND", bitwise_and)
cv2.imshow("Bitwise OR", bitwise_or)
cv2.imshow("Bitwise XOR", bitwise_xor)
cv2.imshow("Bitwise NOT", bitwise_not)
cv2.waitKey(0)
cv2.destroyAllWindows()