TP1
ipynb5 kBPython · 10 cellsSolution of TP 1: Introduction to OpenCV
TP1- OpenCV
import cv2
import numpy as np
import matplotlib.pyplot as pltExercise I - Image conversion
Given an RGB colored image, write a function that converts the image into gray scale one. The gray value of a pixel having the triplet (R, G, B) is the one value (R+G+B)/3. Compare your result to the command in OpenCV
img_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)def convertToGrayScale(imagePath):
image = cv2.imread(imagePath)
grayImage = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv2.imshow("Gray Image", grayImage)
cv2.waitKey(0)
cv2.destroyAllWindows()Exercise II- Image conversion
Given an image that may be an RGB colored image or a grayscale one, write a function that converts the image into binary one. Compare your result to the command in OpenCV “(thresh, blackAndWhiteImage) = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY)”.
def convertToBinary(imagePath, threshold=128):
image = cv2.imread(imagePath, cv2.IMREAD_GRAYSCALE)
_, binaryImage = cv2.threshold(image, threshold, 255, cv2.THRESH_BINARY)
cv2.imshow("Binary Image", binaryImage)
cv2.waitKey(0)
cv2.destroyAllWindows()Exercise III - Plotting each channel separately
In this exercise, we want to take a colored image and plot each channel separately. To do so, the first method is to plot each channel separately as if it is a gray scale image. In the second method, to show the amount of red in each pixel, we leave the red channel untouched and we set the two channels (green and blue) to zero and then we show the image.
def plotImage_1(imagePath):
image = cv2.imread(imagePath)
(B, G, R) = cv2.split(image)
zeros = np.zeros(image.shape[:2], dtype="uint8")
cv2.imshow("Red Channel", cv2.merge([zeros, zeros, R]))
cv2.imshow("Green Channel", cv2.merge([zeros, G, zeros]))
cv2.imshow("Blue Channel", cv2.merge([B, zeros, zeros]))
cv2.waitKey(0)
cv2.destroyAllWindows()
def plotImage_2(imagePath):
image = cv2.imread(imagePath)
(B, G, R) = cv2.split(image)
cv2.imshow("Red Channel", R)
cv2.imshow("Green Channel", G)
cv2.imshow("Blue Channel", B)
cv2.waitKey(0)
cv2.destroyAllWindows()Exercise IV - Histogram
We want to compute the histogram of gray scale images. An histogram of a gray scale image is a 256-array that counts how many times a gray value is present in the image. For example, the value at position 0 in the array will contain how many pixels in the image have the gray value 0 and so on. Write a function that compute the histogram of a gray scale image and plot the histogram using the matplotlib as follows:
def plotHistogram(imagePath):
image = cv2.imread(imagePath, cv2.IMREAD_GRAYSCALE)
histogram = cv2.calcHist([image], [0], None, [256], [0, 256])
plt.plot(histogram)
plt.title("Grayscale Histogram")
plt.xlabel("Pixel Value")
plt.ylabel("Frequency")
plt.xlim([0, 256])
plt.show()