Skip to main content

Display Images using plt and cv2

· 2 min read
Shaurya Singhal

Source: View original notebook on GitHub

Category: Machine Learning / Project1 FaceDetection

Face Detection with Python using OpenCV with Haar_Cascade-Classifier

Learn more from DataCamp (Nicely explained) https://www.datacamp.com/community/tutorials/face-detection-python-opencv

Display Images using plt and cv2

%matplotlib inline
import cv2

# Loading Images - BY DEFAULT cv2 opens image in BGR sequence (Blue frame on top)
mario_img = cv2.imread('Mario.jpg')
mickey_img = cv2.imread('mickey.jpeg')
mario_img .shape # 3 are the channels

Output:

(244, 500, 3)

Using plt.imshow()

import matplotlib.pyplot as plt
# OpenCV reads images in the form of BGR, matplotlib, on the other hand, follows the order of RGB
# if using plt we need to convert it to RGB first
# so we need to convert it from BGR to RGB
mariocvt = cv2.cvtColor(mario_img,cv2.COLOR_BGR2RGB)
mickeycvt = cv2.cvtColor(mickey_img,cv2.COLOR_BGR2RGB)

plt.imshow(mario_img)
plt.show()
plt.imshow(mickey_img)
plt.show()

Output

Output

plt.imshow(mariocvt)
plt.show()
plt.imshow(mickeycvt)
plt.show()

Output

Output

Using cv2.imshow()

cv2.imshow('My Mario Image' , mario_img)
cv2.imshow('My Mickey Image' , micky_img)

'''
Necessery lines to be there to hold on the loaded frames
'''

cv2.waitKey(0) # wait for the user keyboard infinitely.
cv2.destroyAllWindows() # need to use in jupyter notebook so to destroy all windows after key is pressed.
import numpy as np
# programs are wriiten on same folder in FaceDetection.py
import os
import numpy as np
X = []
Y = []
class_id = 0 # to give numerical indexing to person
mapping = []

data_path = './Captured_face_data_for_training/' # ./ is for curent folder
for file in os.listdir(data_path):
if file.endswith('.npy'):
# Adding X(data)
print(file)

data = np.load(data_path + file) # data is of size n * 10000
X.append(data)
# Adding Y(target)
samples = data.shape[0]
target = class_id * np.ones(samples)
Y.append(target)
mapping.append(file[:-4]) # appending name of person with class_id
class_id += 1

X = np.concatenate(X)
Y = np.concatenate(Y)

Output:

mamta.npy
priyansh.npy
saksham.npy
shaurya.npy
X.shape

Output:

(51, 30000)
Y.shape

Output:

(51,)
mapping

Output:

['shaurya']